Skip to content

Instantly share code, notes, and snippets.

@ssddanbrown
Created July 25, 2022 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssddanbrown/52834d8230d04d2783f751b8e4ba8f1b to your computer and use it in GitHub Desktop.
Save ssddanbrown/52834d8230d04d2783f751b8e4ba8f1b to your computer and use it in GitHub Desktop.
<?php
namespace App\Services;
use Closure;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
class AkeneoApi
{
protected string $baseUrl;
/**
* @var array{client_id: string, grant_type: string, username: string, password: string, client_id: string, secret: string, endpoint: string}
*/
protected array $authConfig;
public function __construct(string $baseUrl, array $authConfig)
{
$this->baseUrl = $baseUrl;
$this->authConfig = $authConfig;
}
public function get(string $requestUri, array $params = []): array|object
{
$response = $this->getAuthorizedHttpClient()->get($this->buildUrl($requestUri), $params);
$response->onError(Closure::fromCallable([$this, 'handleErrorResponse']));
return $response->object();
}
public function getPaginated(string $requestUri, array $params = []): array
{
$items = [];
$responseData = $this->get($requestUri, $params);
array_push(...$responseData->_embedded->items ?? []);
$nextPageLink = $responseData->_links->next->href ?? false;
while ($nextPageLink) {
$responseData = $this->get($nextPageLink);
$nextPageLink = $responseData->_links->next->href ?? false;
array_push(...$responseData->_embedded->items ?? []);
}
return $items;
}
protected function buildUrl(string $uri): string
{
return rtrim($this->baseUrl, '/') . '/' . ltrim($uri, '/');
}
protected function handleErrorResponse(Response $response)
{
throw new AkenoApiException("Request to Akeno failed with status {$response->status()} and error: {$response->reason()}");
}
protected function getAuthorizedHttpClient(): PendingRequest
{
$accessToken = cache()->remember('akeno_access_token', 3000, Closure::fromCallable([$this, 'getAccessToken']));
return Http::withToken($accessToken);
}
protected function getAccessToken(): string
{
$accessResponse = Http::withBasicAuth($this->authConfig['client_id'], $this->authConfig['secret'])->post($this->authConfig['endpoint'], [
"grant_type" => $this->authConfig['grant_type'],
"username" => $this->authConfig['username'],
"password" => $this->authConfig['password'],
])
->onError(Closure::fromCallable([$this, 'handleErrorResponse']))
->object();
return $accessResponse->access_token;
}
}
<?php
$api = new AkenoApi(config('akeneo.connections.rest_api.endpoint'), config('akeneo.authentication'));
try {
$data = $api->getPaginated('/products', [
'pagination_type' => 'search_after',
'limit' => 100
]);
} catch (AkenoApiException $e) {
// Handle error
dump($e->getMessage());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment