Compare commits

..

No commits in common. "master" and "v1.0.0" have entirely different histories.

20 changed files with 88 additions and 638 deletions

1
.gitignore vendored
View File

@ -3,4 +3,3 @@ tags
vendor/ vendor/
.php_cs.cache .php_cs.cache
*.mxliff *.mxliff
composer.lock

View File

@ -1,13 +0,0 @@
install:
command -v composer && composer install || echo "Please, install Composer to use tests"
command -v phpunit || command -v composer && composer require --dev phpunit/phpunit ^8
chmod +x ./pre-push.sh
mkdir -p .git/hooks
ln -fs ../../pre-push.sh .git/hooks/pre-push
uninstall:
rm -f ./.git/hooks/pre-push
if [ -d "./vendor/phpunit" ] ; then composer remove --dev phpunit/phpunit; fi
check:
gaze '{src,tests}/**/*.php' -c "./vendor/phpunit/phpunit/phpunit --bootstrap vendor/autoload.php tests --testdox --color"

111
README.md
View File

@ -4,128 +4,53 @@ I am creating this Memsource API as a way to learn how to deal with one and to u
There are other Memsource API repositories on GibHub that appears to be fully functional if you need it. There are other Memsource API repositories on GibHub that appears to be fully functional if you need it.
## Installing ## Getting an Access Token
Install it with [Composer](https://getcomposer.org/): To be able to use the Memsource API, you need an **access token**, but to get it, you need to:
1. Create a `composer.json` file with the following content: ### Register as a developer on Memsource website
```json
{
"repositories": [
{
"type": "vcs",
"url": "https://github.com/brunofontes/Memsource-API"
}
],
"require": {
"brunofontes/memsource-api": "*"
}
}
```
2. Run `php composer.phar install`
3. Add the following line on your .php file:
```php
require_once __DIR__ . '/vendor/autoload.php';
```
## Using
This repository returns a JSON string for almost any command.
If you are not sure how to use it, just convert it to an object or an array as follows:
```php
$myObject = json_decode($response);
$myArray = json_decode($response, true);
```
### Create an instance
```php
$memsource = new \BrunoFontes\Memsource();
```
- If you have already an access token, just include it:
```php
$memsource = new \BrunoFontes\Memsource($token);
```
### Getting an Access Token
To be able to use the Memsource API, you need an **access token**. In order to get it, just follow the instructions below.
#### Register as a developer on Memsource website
So you will receive your: So you will receive your:
- *client id* - *client id*
- *client secret* - *client secret*
#### Get an Authorization Code ### Get an Authorization Code
```php ```php
$memsourceUrl = $memsource->oauth()->getAuthorizationCodeUrl($cliend_id, $callback_uri); $memsource = new \BrunoFontes\Memsource();
$url = $memsource->oauth()->getAuthorizationCodeUrl($cliend_id, $callback_uri);
``` ```
Redirect your browser to this returned `$url` so the user can login via *oauth*. Redirect your browser to this returned `$url` so the user can login via *oauth*.
The `$callback_uri` will be called by *Memsource* with a `$_GET['code']` that contains your Authorization Code, which you can use to... The `$callback_uri` will be called by **Memsource** with a `$_GET['code']` that contains your Authorization Code, which you can use to...
#### Get an Access Token ### Get an Access Token
```php ```php
$authCode = $_GET['code']; $authCode = $_GET['code'];
$memsource = new \BrunoFontes\Memsource();
$token = $memsource->oauth()->getAccessToken($authCode, $client_id, $client_secret, $callback_uri); $token = $memsource->oauth()->getAccessToken($authCode, $client_id, $client_secret, $callback_uri);
``` ```
Safely store this `$token` with the related user data and use it to instantiate the class whenever it were necessary. Safely store this `$token` with the related user data and use it on any
### Project ## Project
#### Project list ### Project list
To list all projects: To list all projects...
```php ```php
$projectList = $memsource->project()->list; $memsource = new \BrunoFontes\Memsource();
$projectList = $memsource->project()->listProjects;
``` ```
To use filters, add the API filter as parameter: To use filters, add the API filter as parâmeter:
```php ```php
$projectList = $memsource->project()->list(['name' => 'Project X']); $projectList = $memsource->project()->listProjects(['name' => 'Project X']);
``` ```
#### Get Project ## Bilingual Files
```php
$projectList = $memsource->project()->get($projectUid);
```
### Jobs
#### List Jobs
Only projectUid is essencial:
```php
$jobs = $memsource->jobs()->list($projectUid, ['count' => true, 'filename' => 'my_file.html']);
```
### Bilingual Files
#### Download Bilingual File
```php
$memsource->BilingualFile()->download($projectUid, ['JobUid1', 'jobUid2'], 'download.mxliff');
```
#### Upload Bilingual File
```php
$parameters = ['format' => 'MXLF', 'saveToTransMemory' => 'None', 'setCompleted' => 'false'];
$result = $api->bilingualFile()->upload('upload.mxliff', $parameters);
```

View File

@ -2,7 +2,6 @@
"name": "brunofontes/memsource-api", "name": "brunofontes/memsource-api",
"description": "A personal memsource api to better understand how it works", "description": "A personal memsource api to better understand how it works",
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
"version": "1.2",
"authors": [ "authors": [
{ {
"name": "Bruno F. Fontes", "name": "Bruno F. Fontes",
@ -21,8 +20,5 @@
"type": "vcs", "type": "vcs",
"url": "https://github.com/brunofontes/Memsource-API" "url": "https://github.com/brunofontes/Memsource-API"
} }
], ]
"require-dev": {
"phpunit/phpunit": "^8"
}
} }

View File

@ -1,11 +0,0 @@
params="--bootstrap vendor/autoload.php tests --testdox --color"
if [ -d ./vendor/phpunit ]; then
./vendor/phpunit/phpunit/phpunit $params
else
if [ $(command -v phpunit) ]; then
phpunit $params
else
echo "Please, run 'make install' or install phpunit globally to run the tests"
fi
fi

View File

@ -1,32 +0,0 @@
<?php
/**
* A very compact and simple Memsource API library
*
* @author Bruno Fontes <developer@brunofontes.net>
* @link https://github.com/brunofontes
*/
namespace BrunoFontes\Memsource;
class Async extends \BrunoFontes\Memsource\BaseApi
{
private $_url = '/api2/v1/async';
/**
* Get asynchronous request
*
* @param string $queryParams An array with the Query parameters to filter projects
*
* @return string The JSON answer from Memsource
*/
public function getAsyncRequest(string $asyncRequestId, array $queryParams = []): string
{
$response = $this->fetchApi->fetch('get', "{$this->_url}/{$asyncRequestId}", $queryParams);
if ($this->hasError($response)) {
throw new \Exception("Error listing AsyncRequest: " . $this->getError($response), 1);
}
return $response;
}
}

View File

@ -15,15 +15,4 @@ class BaseApi
{ {
$this->fetchApi = $fetchApi; $this->fetchApi = $fetchApi;
} }
protected function hasError(string $jsonResponse): bool
{
return isset(json_decode($jsonResponse, true)['errorCode']);
}
protected function getError(string $jsonResponse): string
{
return json_decode($jsonResponse, true)['errorDescription'];
}
} }

View File

@ -5,7 +5,6 @@
* @author Bruno Fontes <developer@brunofontes.net> * @author Bruno Fontes <developer@brunofontes.net>
* @link https://github.com/brunofontes * @link https://github.com/brunofontes
*/ */
namespace BrunoFontes\Memsource; namespace BrunoFontes\Memsource;
class BilingualFile extends \BrunoFontes\Memsource\BaseApi class BilingualFile extends \BrunoFontes\Memsource\BaseApi
@ -28,24 +27,16 @@ class BilingualFile extends \BrunoFontes\Memsource\BaseApi
* *
* @return array A list of the downloaded files * @return array A list of the downloaded files
*/ */
public function download(string $projectUid, array $jobUids, string $filename): array public function downloadBilingualFile(string $projectUid, array $jobUids, string $filename): array
{ {
$fileExtension = pathinfo($filename)['extension']; $url = "/api2/v1/projects/{$projectUid}/jobs/bilingualFile";
$fileNoExtension = basename($filename,'.'.$fileExtension);
;
$url = "/api2/v1/projects/{$projectUid}/jobs/bilingualFile?format=" . strtoupper($fileExtension);
$filenames = [];
$groupedJobUids = array_chunk($jobUids, 100); $groupedJobUids = array_chunk($jobUids, 100);
for ($i = 0; $i < count($groupedJobUids); $i++) { for ($i = 0; $i < count($groupedJobUids); $i++) {
$apiReadyArray = $this->_convertUidArrayToApiRequest($groupedJobUids[$i]); $apiReadyArray = $this->_convertUidArrayToApiRequest($groupedJobUids[$i]);
$filenames[$i] = count($groupedJobUids) > 1 ? "{$fileNoExtension}_{$i}.{$fileExtension}" : $filename; $filenames[$i] = count($groupedJobUids) > 1?"{$i}_{$filename}":$filename;
$filecontent = $this->fetchApi->fetch('jsonPost', $url, $apiReadyArray); $filecontent = $this->fetchApi->fetch('jsonPost', $url, $apiReadyArray);
if ($this->hasError($filecontent)) { $this->_saveIntoFile($filenames[$i], $filecontent);
$errorMsg = $this->getError($filecontent);
throw new \Exception("Error downloading file: {$errorMsg}", 1);
}
Helper::saveIntoFile($filenames[$i], $filecontent);
} }
return $filenames; return $filenames;
} }
@ -66,6 +57,17 @@ class BilingualFile extends \BrunoFontes\Memsource\BaseApi
return ['jobs' => $convertedArray]; return ['jobs' => $convertedArray];
} }
private function _saveIntoFile(string $filename, string $filecontent): void
{
try {
$f = fopen($filename, 'w+');
fwrite($f, $filecontent);
fclose($f);
} catch (\Exception $e) {
throw new \Exception("File could not be saved: {$e->error}", 1);
}
}
/** /**
* Upload a bilingual file to Memsource * Upload a bilingual file to Memsource
* *
@ -74,20 +76,13 @@ class BilingualFile extends \BrunoFontes\Memsource\BaseApi
* *
* @return string The http request responde from API in json format * @return string The http request responde from API in json format
*/ */
public function upload(string $filename, array $params): string public function uploadBilingualFile(string $filename, array $params): string
{ {
$urlParams = http_build_query($params); $urlParams = http_build_query($params);
try {
$fileContent = file_get_contents($filename); $fileContent = file_get_contents($filename);
} catch (\Exception $e) { if ($fileContent === false) {
throw new \Exception('File for upload inexistent or invalid: ' . $filename, 1); throw new \Exception('File for upload inexistent or invalid', 1);
} }
return $this->fetchApi->fetch('put', $this->_url . "?{$urlParams}", [$fileContent]);
$response = $this->fetchApi->fetch('put', $this->_url . "?{$urlParams}", [$fileContent]);
if ($this->hasError($response)) {
throw new \Exception("Error uploading file {$filename}: " . $this->getError($response), 1);
}
return $response;
} }
} }

View File

@ -12,18 +12,13 @@ class FetchApi
protected $base_url; protected $base_url;
protected $token; protected $token;
public function getBase_url()
{
return $this->base_url;
}
/** /**
* BaseAPI needs at least the Memsource Token to use it's API * BaseAPI needs at least the Memsource Token to use it's API
* *
* @param string $token * @param string $token
* @param string $memsourceBaseUrl [Optional] A non-standard Memsource URL base for the API to work * @param string $memsourceBaseUrl [Optional] A non-standard Memsource URL base for the API to work
*/ */
public function __construct(string $token = null, string $memsourceBaseUrl) public function __construct(string $token = null, string $memsourceBaseUrl = 'https://cloud.memsource.com/web')
{ {
$this->base_url = $memsourceBaseUrl; $this->base_url = $memsourceBaseUrl;
$this->token = $token; $this->token = $token;
@ -32,7 +27,7 @@ class FetchApi
/** /**
* Fetch API data using curl * Fetch API data using curl
* *
* @param string $method Should be 'get', 'put', 'post', 'jsonPost', 'download' or 'raw' * @param string $method Should be 'get', 'post', 'jsonPost' or 'download'
* @param string $url The api url * @param string $url The api url
* @param array $parameters Array ['key' => 'value'] of get or post fields or structured array for json requests * @param array $parameters Array ['key' => 'value'] of get or post fields or structured array for json requests
* @param string $filename [optional] Specified file in which the download request will be saved * @param string $filename [optional] Specified file in which the download request will be saved
@ -44,47 +39,30 @@ class FetchApi
$setopt = []; $setopt = [];
switch ($method) { switch ($method) {
case 'get': case 'get':
$this->checkAccessToken();
$parameters = http_build_query($parameters); $parameters = http_build_query($parameters);
$url = $url . ($parameters ? '?'.$parameters : ''); $url = $url . ($parameters ? '?'.$parameters : '');
break; break;
case 'put': case 'put':
$this->checkAccessToken();
$setopt = $this->getPutParam()+$this->getPostParam(implode("", $parameters)); $setopt = $this->getPutParam()+$this->getPostParam(implode("", $parameters));
break; break;
case 'post': case 'post':
$this->checkAccessToken();
$parameters = http_build_query($parameters); $parameters = http_build_query($parameters);
$setopt = $setopt + $this->getPostParam($parameters); $setopt = $setopt + $this->getPostParam($parameters);
break; break;
case 'jsonPost': case 'jsonPost':
$this->checkAccessToken();
$setopt = $this->getJsonPostParam($parameters); $setopt = $this->getJsonPostParam($parameters);
break; break;
case 'download': case 'download':
$this->checkAccessToken();
if (empty($filename)) { if (empty($filename)) {
throw new Exception('You need to specify a filename to download a file.', 1); throw new Exception('You need to specify a filename to download a file.', 1);
} }
$setopt = $this->getDownloadFileParam($filename) $setopt = $this->getDownloadFileParam($filename)
+ $this->getJsonPostParam($parameters); + $this->getJsonPostParam($parameters);
break; break;
case 'raw':
$setopt = $parameters;
break;
default:
throw new \Exception("Method {$method} is invalid on Fetch", 1);
} }
return $this->curl($url, $setopt); return $this->curl($url, $setopt);
} }
private function checkAccessToken()
{
if (empty($this->token)) {
throw new \Exception("Missing Access Token", 1);
}
}
private function getDownloadFileParam(string $filename) private function getDownloadFileParam(string $filename)
{ {
return [ return [
@ -120,10 +98,10 @@ class FetchApi
protected function curl(string $url, array $curl_extra_setopt = []) protected function curl(string $url, array $curl_extra_setopt = [])
{ {
if (empty($url)) { if (empty($url)) {
throw new \Exception('URL not defined', 1); throw new Exception('URL not defined', 1);
} }
$header = ($this->token ? ["Authorization: Bearer {$this->token}"] : []); $header = $this->token ? ["Authorization: Bearer {$this->token}"] : [];
$header = array_merge($header, $curl_extra_setopt[CURLOPT_HTTPHEADER]??[]); $header = array_merge($header, $curl_extra_setopt[CURLOPT_HTTPHEADER]??[]);
$curl_setopt = [ $curl_setopt = [
CURLOPT_URL => $this->base_url . $url, CURLOPT_URL => $this->base_url . $url,

View File

@ -1,19 +0,0 @@
<?php
namespace BrunoFontes\Memsource;
class Helper
{
public static function saveIntoFile(string $filename, string $filecontent): void
{
try {
$f = fopen($filename, 'w+');
fwrite($f, $filecontent);
fclose($f);
} catch (\Exception $e) {
throw new \Exception("File could not be saved: {$e->error}", 1);
}
}
}

View File

@ -10,6 +10,7 @@ namespace BrunoFontes\Memsource;
class Jobs extends \BrunoFontes\Memsource\BaseApi class Jobs extends \BrunoFontes\Memsource\BaseApi
{ {
/** /**
* List jobs of a project * List jobs of a project
* The API request returns a MAX of 50 Jobs. * The API request returns a MAX of 50 Jobs.
@ -20,48 +21,9 @@ class Jobs extends \BrunoFontes\Memsource\BaseApi
* *
* @return string The JSON answer from Memsource * @return string The JSON answer from Memsource
*/ */
public function list(string $projectUid, array $parameters = []): string public function listJobs(string $projectUid, array $parameters = []): string
{ {
$url = "/api2/v2/projects/{$projectUid}/jobs"; $url = "/api2/v2/projects/{$projectUid}/jobs";
$response = $this->fetchApi->fetch('get', $url, $parameters); return $this->fetchApi->fetch('get', $url, $parameters);
if ($this->hasError($response)) {
throw new \Exception("Error listing projects: " . $this->getError($response), 1);
} }
return $response;
}
/**
* Download a target file
*
* @param string $projectUid The project uid which contain the jobs
* @param string $jobUid Job uid to be download
* @param string $filename Filename of the saved file
* @param string $format File format: ORIGINAL or PDF
*/
public function downloadTargetFile(string $projectUid, string $jobUid, string $filename, string $format = "ORIGINAL")
{
$url = "/api2/v1/projects/{$projectUid}/jobs/{$jobUid}/targetFile";
$filecontent = $this->fetchApi->fetch('get', $url);
$f = fopen($filename, 'w+');
fwrite($f, $filecontent);
fclose($f);
}
/**
* Download a source file
*
* @param string $projectUid The project uid which contain the jobs
* @param string $jobUid Job uid to be download
*/
public function downloadOriginalFile(string $projectUid, string $jobUid, string $filename)
{
$url = "/api2/v1/projects/{$projectUid}/jobs/{$jobUid}/original";
$filecontent = $this->fetchApi->fetch('get', $url);
$f = fopen($filename, 'w+');
fwrite($f, $filecontent);
fclose($f);
}
} }

View File

@ -8,14 +8,6 @@
namespace BrunoFontes; namespace BrunoFontes;
use \BrunoFontes\Memsource\BilingualFile;
use \BrunoFontes\Memsource\FetchApi;
use \BrunoFontes\Memsource\Jobs;
use \BrunoFontes\Memsource\Oauth;
use \BrunoFontes\Memsource\Project;
use \BrunoFontes\Memsource\TM;
use \BrunoFontes\Memsource\Async;
/** /**
* Memsource API class * Memsource API class
* *
@ -28,72 +20,51 @@ class Memsource
private $_bilingualFile; private $_bilingualFile;
private $_jobs; private $_jobs;
private $_project; private $_project;
private $_tm;
private $_async;
private $_fetchApi; private $_fetchApi;
public function __construct(string $token = null, string $memsourceBaseUrl = 'https://cloud.memsource.com/web') public function __construct(string $token = null, string $memsourceBaseUrl = 'https://cloud.memsource.com/web')
{ {
$this->_fetchApi = new FetchApi($token, $memsourceBaseUrl); $this->_fetchApi = new \BrunoFontes\Memsource\FetchApi($token, $memsourceBaseUrl);
} }
/** /**
* Memsource Oauth functions * Memsource Oauth functions
* *
* @return Oauth * @return \BrunoFontes\Memsource\Oauth
*/ */
public function oauth(): Oauth public function oauth(): \BrunoFontes\Memsource\Oauth
{ {
return $this->_oauth ?? $this->_oauth = new oauth($this->_fetchApi); return $this->_oauth ?? $this->_oauth = new \BrunoFontes\Memsource\oauth();
} }
/** /**
* Memsource API BilingualFile related functions * Memsource API BilingualFile related functions
* *
* @return BilingualFile * @return \BrunoFontes\Memsource\BilingualFile
*/ */
public function bilingualFile(): BilingualFile public function bilingualFile(): \BrunoFontes\Memsource\BilingualFile
{ {
return $this->_bilingualFile ?? $this->_bilingualFile = new BilingualFile($this->_fetchApi); return $this->_bilingualFile ?? $this->_bilingualFile = new \BrunoFontes\Memsource\BilingualFile($this->_fetchApi);
} }
/** /**
* Memsource API Jobs related functions * Memsource API Jobs related functions
* *
* @return Jobs * @return \BrunoFontes\Memsource\Jobs
*/ */
public function jobs(): Jobs public function jobs(): \BrunoFontes\Memsource\Jobs
{ {
return $this->_jobs ?? $this->_jobs = new Jobs($this->_fetchApi); return $this->_jobs ?? $this->_jobs = new \BrunoFontes\Memsource\Jobs($this->_fetchApi);
} }
/** /**
* Memsource API Project related functions * Memsource API Project related functions
* *
* @return Project * @return \BrunoFontes\Memsource\Project
*/ */
public function project(): Project public function project(): \BrunoFontes\Memsource\Project
{ {
return $this->_project ?? $this->_project = new Project($this->_fetchApi); return $this->_project ?? $this->_project = new \BrunoFontes\Memsource\Project($this->_fetchApi);
}
/**
* Memsource API Async related functions
*
* @return Async
*/
public function async(): Async
{
return $this->_async ?? $this->_async = new Async($this->_fetchApi);
}
/**
* Memsource API TM related functions
*
* @return TM
*/
public function tm(): TM
{
return $this->_tm ?? $this->_tm = new TM($this->_fetchApi);
} }
} }

View File

@ -19,13 +19,9 @@ class Project extends \BrunoFontes\Memsource\BaseApi
* *
* @return string The JSON answer from Memsource * @return string The JSON answer from Memsource
*/ */
public function list(array $queryParams = []): string public function listProjects(array $queryParams = []): string
{ {
$response = $this->fetchApi->fetch('get', $this->_url, $queryParams); return $this->fetchApi->fetch('get', $this->_url, $queryParams);
if ($this->hasError($response)) {
throw new \Exception("Error listing projects: " . $this->getError($response), 1);
}
return $response;
} }
/** /**
@ -35,26 +31,8 @@ class Project extends \BrunoFontes\Memsource\BaseApi
* *
* @return string A json string with all project info * @return string A json string with all project info
*/ */
public function get(string $projectUid): string public function getProject(string $projectUid): string
{ {
$response = $this->fetchApi->fetch('get', "{$this->_url}/{$projectUid}"); return $this->fetchApi->fetch('get', "{$this->_url}/{$projectUid}");
if ($this->hasError($response)) {
throw new \Exception("Error getting project {$projectUid}: " . $this->getError($response), 1);
}
}
/**
* Edit the project status
*
* @param string $projectUid The project UID
* @param string $status The new status
*/
public function editStatus(string $projectUid, string $status): void
{
$queryParam = ['status' => $status];
$response = $this->fetchApi->fetch('jsonPost', "{$this->_url}/{$projectUid}/setStatus", $queryParam);
if ($this->hasError($response)) {
throw new \Exception("Error editing project status on project: {$projectUid}: " . $this->getError($response), 1);
}
} }
} }

View File

@ -1,74 +0,0 @@
<?php
/**
* A very compact and simple Memsource API library
*
* @author Bruno Fontes <developer@brunofontes.net>
* @link https://github.com/brunofontes
*/
namespace BrunoFontes\Memsource;
enum ExportFormat
{
case TMX;
case XLSX;
}
class TM extends \BrunoFontes\Memsource\BaseApi
{
private $_url = '/api2/v2/transMemories';
/**
* List projects
*
* @param string $queryParams An array with the Query parameters to filter projects
*
* @return string The JSON answer from Memsource
*/
public function list(array $queryParams = []): string
{
$response = $this->fetchApi->fetch('get', '/api2/v1/transMemories/', $queryParams);
if ($this->hasError($response)) {
throw new \Exception("Error listing TMs: " . $this->getError($response), 1);
}
return $response;
}
/**
* Export a TM in an async way
*
* @param string $tmUid The TM UID
* @param array[string] $targetLangs The language pairs to export
*
* @return string A json string with all translation memories info
*/
public function export(string $tmUid, array $targetLangs): string
{
$queryParam['exportTargetlangs'] = $targetLangs;
$response = $this->fetchApi->fetch('jsonPost', "{$this->_url}/{$tmUid}/export", $queryParam);
if ($this->hasError($response)) {
throw new \Exception("Error getting tm {$tmUid}: " . $this->getError($response), 1);
}
return $response;
}
/**
* Download a TM. You need to export the TM first in order to obtain the
* asyncExport id
*
* @param string $asyncId The asyncId obtainable by export function
* @param ExportFormat $format The file format that will be exported
* @param string $filename The filename that will be created to store the
* downloaded TM
*/
public function download(string $asyncId, string $filename, ExportFormat $fileFormat = ExportFormat::TMX)
{
$queryParam['format'] = $fileFormat->name;
$filecontent = $this->fetchApi->fetch('get', "/api2/v1/transMemories/downloadExport/{$asyncId}/", $queryParam);
if ($this->hasError($filecontent)) {
throw new \Exception("Error downloading TM asyncID {$asyncId}: " . $this->getError($filecontent), 1);
}
Helper::saveIntoFile($filename, $filecontent);
}
}

View File

@ -5,10 +5,9 @@
* @author Bruno Fontes <developer@brunofontes.net> * @author Bruno Fontes <developer@brunofontes.net>
* @link https://github.com/brunofontes * @link https://github.com/brunofontes
*/ */
namespace BrunoFontes\Memsource; namespace BrunoFontes\Memsource;
class Oauth extends \BrunoFontes\Memsource\BaseApi class Oauth extends \BrunoFontes\Memsource
{ {
private $_url = '/oauth'; private $_url = '/oauth';
@ -23,16 +22,8 @@ class Oauth extends \BrunoFontes\Memsource\BaseApi
*/ */
public function getAuthorizationCodeUrl(string $client_id, string $callback_uri) public function getAuthorizationCodeUrl(string $client_id, string $callback_uri)
{ {
$authorize_url = $this->fetchApi->getBase_url() . $this->_url . '/authorize'; $authorize_url = $this->base_url . $this->_url . '/authorize';
$parambeters = http_build_query( return $authorize_url . '?response_type=code&client_id=' . $client_id . '&redirect_uri=' . $callback_uri . '&scope=openid';
[
"response_type" => 'code',
"client_id" => $client_id,
"redirect_uri" => $callback_uri,
"scope" => 'openid'
]
);
return "{$authorize_url}?{$parambeters}";
} }
public function getAccessToken(string $authorization_code, string $client_id, string $client_secret, string $callback_uri) public function getAccessToken(string $authorization_code, string $client_id, string $client_secret, string $callback_uri)
@ -46,12 +37,10 @@ class Oauth extends \BrunoFontes\Memsource\BaseApi
CURLOPT_POST => true, CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $content CURLOPT_POSTFIELDS => $content
]; ];
$response = json_decode($this->fetchApi->fetch('raw', $token_url, $params), true); $response = $this->curl($token_url, $params);
if ($respose['error']) {
if (isset($response['error'])) { throw new Exception("Error getting access token", 1);
throw new \Exception("Error getting TOKEN: " . $response['error_description'], 1);
} }
return $response['access_token']; return $response['access_token'];
} }
} }

View File

@ -1,37 +0,0 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class BilingualFileTest extends TestCase
{
public function testEmptyDownloadJobUidListShouldReturnEmptyFilenames()
{
$api = new Memsource('fakeToken');
$this->assertEquals(
[],
$api->bilingualFile()->download('uid', [], 'filename.xliff')
);
}
public function testInvalidDownloadUidsShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->bilingualFile()->download('uid', ['a'], 'filename.xliff');
}
public function testUploadInexistentFileShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->bilingualFile()->upload('myInvalidFile', []);
}
public function testUploadWithNoTokenShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->bilingualFile()->upload('tests/bilingualFileTest.php', []);
}
}

View File

@ -1,57 +0,0 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource\FetchApi;
final class FetchApiTest extends TestCase
{
public function testEmptyFetchUrlShouldThrowError()
{
$fetch = new FetchApi('fakeToken', 'https://google.com');
$this->expectExceptionMessage('URL not defined');
$this->assertNotEmpty($fetch->fetch('get', ''));
}
public function testNotEmptyTokenOnFetchShouldNotThrowError()
{
$fetch = new FetchApi('fakeToken', 'https://google.com');
$this->assertNotEmpty($fetch->fetch('get', '/'));
}
public function testEmptyTokenOnFetchRawShouldNotThrowError()
{
$fetch = new FetchApi(null, 'http://google.com');
$this->assertNotEmpty($fetch->fetch('raw', '/'));
}
public function testEmptyTokenOnFetchGetShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('get', 'url');
}
public function testEmptyTokenOnFetchPutShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('put', 'url');
}
public function testEmptyTokenOnFetchPostShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('post', 'url');
}
public function testEmptyTokenOnFetchJsonPostShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('jsonPost', 'url');
}
public function testEmptyTokenOnFetchDownloadShouldThrowError()
{
$fetch = new FetchApi(null, 'http://testUrl.com');
$this->expectExceptionMessage('Missing Access Token');
$fetch->fetch('download', 'url');
}
}

View File

@ -1,33 +0,0 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class JobsTest extends TestCase
{
public function testInvalidProjectUidShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->jobs()->list('invalidProjectUid', []);
}
public function testDownloadTargetFileReturnsNull()
{
$api = new Memsource('fakeToken');
$this->assertEquals(
null,
$api->jobs()->downloadTargetFile('projUid', 'jobUid', 'filename.xliff')
);
}
public function testDownloadOriginalFileReturnsNull()
{
$api = new Memsource('fakeToken');
$this->assertEquals(
null,
$api->jobs()->downloadOriginalFile('projUid', 'jobUid', 'filename.xliff')
);
}
}

View File

@ -1,34 +0,0 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class oauthTest extends TestCase
{
public function testOauthGetAuthorizationCodeUrl()
{
$customServerURL = 'http://myPersonalMemsource.com';
$api = new Memsource(null, $customServerURL);
$expected = $customServerURL . '/oauth/authorize?response_type=code&client_id=id&redirect_uri=http%3A%2F%2Furi&scope=openid';
$memsourceUrl = $api->oauth()->getAuthorizationCodeUrl('id', 'http://uri');
$this->assertEquals(
$expected,
$memsourceUrl
);
}
public function testGetAccessTokenExceptionOnFakeCode()
{
$api = new Memsource();
$this->expectException(\Exception::class);
$token = $api->oauth()->getAccessToken('fakeCode', 'fakeId', 'fakePass', 'http://any');
}
public function testGetAccessTokenExceptionOnEmptyCode()
{
$api = new Memsource();
$this->expectException(\Exception::class);
$token = $api->oauth()->getAccessToken('', '', '', '');
}
}

View File

@ -1,22 +0,0 @@
<?php
declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use BrunoFontes\Memsource;
final class ProjectTest extends TestCase
{
public function testNoTokenShouldThrowError()
{
$api = new Memsource();
$this->expectExceptionMessage('Missing Access Token');
$api->project()->list();
}
public function testInvalidProjectUidShouldThrowError()
{
$api = new Memsource('fakeToken');
$this->expectException(\Exception::class);
$api->project()->get('invalidProjectUid');
}
}