Commit 30d7d6b3 authored by Patrick Barroca's avatar Patrick Barroca 😁
Browse files

dev #152400 : refactoring

parent 39e70687
Pipeline #16787 passed with stage
in 35 seconds
......@@ -5,7 +5,7 @@ test:php7_latest:
- git submodule init
- git submodule update
- php --version
- ./vendor/bin/phpunit -c tests/phpunit.xml --testdox
- ./vendor/bin/phpunit -c tests/phpunit.xml
except:
- tags
tags:
......
......@@ -2,6 +2,7 @@
namespace Pellicule\Providers;
use \Fig\Http\Message\StatusCodeInterface;
use \Psr\Http\Message\ResponseInterface;
use \Pellicule\Models\Media;
use \Pellicule\Models\Record;
use \Pellicule\FileSystem;
......@@ -29,86 +30,95 @@ class ElectreNg extends Provider {
public function fetchRecord() {
// basic guards
if (!$this->_id || !$this->_secret)
return $this->_newError(StatusCodeInterface::STATUS_UNAUTHORIZED, 'invalid_credentials');
if (!$ean = $this->_getIsbnOrEan())
if (!$identifier = $this->_getIsbnOrEan())
return $this->_newError(StatusCodeInterface::STATUS_BAD_REQUEST, 'missing_param');
// getting access_token
try {
$response = static::newHttpClient()->submitForm(static::TOKEN_URL,
['grant_type' => 'password',
'client_id' => static::CLIENT_ID,
'username' => $this->_id,
'password' => $this->_secret]);
} catch(\Exception $e) {
return $this->_newError(StatusCodeInterface::STATUS_GATEWAY_TIMEOUT,
'no_answer_from_gateway');
}
if ($response->getStatusCode() != StatusCodeInterface::STATUS_OK
|| (!$body = $response->getBody())
|| 0 == $body->getSize())
return $this->_newError(StatusCodeInterface::STATUS_BAD_GATEWAY, 'provider_error');
if ((!$json_response = $this->_parseJsonResponse($response))
|| isset($json_response->error)
|| !isset($json_response->access_token))
return $this->_newError(StatusCodeInterface::STATUS_BAD_GATEWAY, 'provider_error');
$access_token = $json_response->access_token;
$token_type = $json_response->token_type ?? 'Bearer';
// getting record info
try {
$response = static::newHttpClient()
->get(str_replace('{ean}', $ean, static::API_URL),
['Authorization' => $token_type . ' ' . $access_token]);
} catch(\Exception $e) {
return $this->_newError(StatusCodeInterface::STATUS_GATEWAY_TIMEOUT,
'no_answer_from_gateway');
}
if ($response->getStatusCode() != StatusCodeInterface::STATUS_OK
|| (!$body = $response->getBody())
|| 0 == $body->getSize())
return $this->_newError(StatusCodeInterface::STATUS_BAD_GATEWAY, 'provider_error');
$token_response = $this->_getToken();
if ($token_response instanceof FetchRecordResult)
return $token_response;
if ((!$json_response = $this->_parseJsonResponse($response))
|| (!$records = $json_response->notices ?? [])
|| (!$cover_url = $records[0]->imageCouverture ?? false))
return $this->_newError(StatusCodeInterface::STATUS_BAD_GATEWAY, 'provider_error');
$cover_url = $this->_getCoverUrl($identifier, $token_response);
if ($cover_url instanceof FetchRecordResult)
return $cover_url;
// get cover
try {
$response = static::newHttpClient()->get($cover_url);
} catch(\Exception $e) {
return $this->_newError(StatusCodeInterface::STATUS_GATEWAY_TIMEOUT,
'no_answer_from_gateway');
}
$response = $this->_withHttpDo(fn($http) => $http->get($cover_url));
if ($response instanceof FetchRecordResult)
return $response;
$media = (new Media)
->setProvider($this->providerName())
->setUrl($cover_url)
->beCover()
->setFullsizeFromIdentifier($ean)
;
$media = Media::newInstance(['provider' => $this->providerName(),
'type' => Media::TYPE_COVER,
'url' => $cover_url,
'fullsize_from_identifier' => $identifier,
]);
if (!(new FileSystem)->writeMediaFrom($media, $response))
return $this->_newError(StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR,
'error_writing_cover');
$record = (new Record)
->updateAttributes($this->_search_args)
->setMedia([$media]);
$record = Record::newInstance(array_merge($this->_search_args, ['media' => [$media]]));
return (new FetchRecordResult)->beSuccess($record);
return $record->save()
? (new FetchRecordResult)->beSuccess($record)
: $this->_newError(StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR,
'error_saving_record');
}
public function providerName() {
return 'Electre';
}
protected function _getToken() {
$callback = fn($http) => $http->submitForm(static::TOKEN_URL,
['grant_type' => 'password',
'client_id' => static::CLIENT_ID,
'username' => $this->_id,
'password' => $this->_secret]);
$response = $this->_withHttpDo($callback);
if ($response instanceof FetchRecordResult)
return $response;
return (($json_response = $this->_parseJsonResponse($response))
&& isset($json_response->access_token))
? $json_response
: $this->_newError(StatusCodeInterface::STATUS_BAD_GATEWAY, 'provider_error');
}
protected function _getCoverUrl($ean, $token_response) {
$api_url = str_replace('{ean}', $ean, static::API_URL);
$headers = ['Authorization' => (($token_response->token_type ?? 'Bearer')
. ' ' . $token_response->access_token)];
$response = $this->_withHttpDo(fn($http) => $http->get($api_url, $headers));
if ($response instanceof FetchRecordResult)
return $response;
return (($json_response = $this->_parseJsonResponse($response))
&& ($records = $json_response->notices ?? [])
&& ($cover_url = $records[0]->imageCouverture ?? false))
? $cover_url
: $this->_newError(StatusCodeInterface::STATUS_BAD_GATEWAY, 'provider_error');
}
protected function _withHttpDo($callback) {
try {
$response = $callback(static::newHttpClient());
} catch(\Exception $e) {
return $this->_newError(StatusCodeInterface::STATUS_GATEWAY_TIMEOUT,
'no_answer_from_gateway');
}
return ($response->getStatusCode() === StatusCodeInterface::STATUS_OK
&& ($body = $response->getBody())
&& 0 < $body->getSize())
? $response
: $this->_newError(StatusCodeInterface::STATUS_BAD_GATEWAY, 'provider_error');
}
}
......@@ -99,7 +99,7 @@ abstract class Provider {
* @return FetchRecordResult
*/
public function _newError($status, $code) {
return (new FetchRecordResult())->beError($status, $code);
return (new FetchRecordResult)->beError($status, $code);
}
......
......@@ -3,7 +3,7 @@ namespace Pellicule\Tests;
use \Fig\Http\Message\StatusCodeInterface;
use \Slim\Psr7\Headers;
use \Storm\FileSystem\Volatile;
use \Storm\FileSystem\Volatile as VolatileFileSystem;
use \Pellicule\Providers\ElectreNg;
use \Pellicule\FileSystem;
use \Pellicule\Models\Media;
......@@ -85,7 +85,7 @@ class MediaElectreNgBadAuthenticationTest extends MediaElectreNgTestCase {
class MediaElectreNgGoodAuthenticationTest extends MediaElectreNgTestCase {
class MediaElectreNgGoodAuthenticationBadApiTest extends MediaElectreNgTestCase {
public function setUp() {
parent::setUp();
......@@ -134,7 +134,7 @@ class MediaElectreNgGoodAuthenticationTest extends MediaElectreNgTestCase {
/** @test */
public function withApiNotJsonShouldRespondBadGateway() {
$this->_http_client
$this->_http_client
->whenCalled('get')
->with(str_replace('{ean}', '9782818976173', ElectreNg::API_URL),
['Authorization' => 'Bearer ACCESS_TOKEN'])
......@@ -156,10 +156,34 @@ class MediaElectreNgGoodAuthenticationTest extends MediaElectreNgTestCase {
$this->_dispatchAndAssertStatus(StatusCodeInterface::STATUS_BAD_GATEWAY);
}
}
/** @test */
public function withApiValidJsonShouldRespondFoundMedia() {
class MediaElectreNgGoodAuthenticationGoodApiTest extends MediaElectreNgTestCase {
protected
$_json_response,
$_file_system;
public function setUp() {
parent::setUp();
$content = json_encode(['access_token' => 'ACCESS_TOKEN',
'expires_in' => 172800,
'refresh_expires_in' => 300,
'refresh_token' => 'REFRESH_TOKEN',
'token_type' => 'Bearer',
'not-before-policy' => 1637075208,
'session_state' => 'SESSION_STATE',
'scope' => 'profile email',
]);
$this->_http_client
->whenCalled('submitForm')
->answers($this->_forgePSR7Response(['content' => $content]))
;
$record = ['eansUtilises' => [],
'isbnsUtilises' => [],
'desactive' => false,
......@@ -197,24 +221,54 @@ class MediaElectreNgGoodAuthenticationTest extends MediaElectreNgTestCase {
;
FileSystem::setBasePath('./images');
FileSystem::setFileSystem($filesystem = new Volatile);
Media::setFileSystem($filesystem);
FileSystem::setFileSystem($this->_file_system = new VolatileFileSystem);
Media::setFileSystem($this->_file_system);
$this->dispatch('/1.0/media/isbn/9782818976173',
['Authorization' => ['Pellicule ' . $this->_credentials]]);
$this->_json_response = json_decode((string)$this->_response->getBody());
}
/** @test */
public function responseCodeShouldBeOk() {
$this->assertResponseCode(StatusCodeInterface::STATUS_OK);
}
/** @test */
public function mediaFullsizeShouldBeJpg() {
$this->assertEquals('/fullsize/cover/9/7/8/2/9782818976173.jpg',
Media::find(1)->getFullsize());
}
/** @test */
public function mediaFullsizeContentShouldBeImageContent() {
$this->assertEquals('image content',
$filesystem->fileGetContents('/images/fullsize/cover/9/7/8/2/9782818976173.jpg'));
$this->_file_system
->fileGetContents('/images/fullsize/cover/9/7/8/2/9782818976173.jpg'));
}
$json_response = json_decode((string)$this->_response->getBody());
/** @test */
public function jsonResponseFirstMediaFullsizeShouldBeAbsoluteUrlToFullsizeJpg() {
$this->assertEquals('http://pellicule.io:8899/images/fullsize/cover/9/7/8/2/9782818976173.jpg',
$json_response->media[0]->fullsize);
$this->_json_response->media[0]->fullsize);
}
/** @test */
public function jsonResponsFirstMediaProviderShouldBeElectre() {
$this->assertEquals('Electre',
$json_response->media[0]->provider);
$this->_json_response->media[0]->provider);
}
/** @test */
public function jsonResponseFirstMediaUrlShouldBeOriginUrl() {
$this->assertEquals('https://media.server.com/images/image-id/b212dc4.jpg',
$json_response->media[0]->url);
$this->_json_response->media[0]->url);
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment