HummingBirdAnimeClient/src/AnimeClient/API/Kitsu/RequestBuilder.php

284 lines
6.7 KiB
PHP
Raw Normal View History

<?php declare(strict_types=1);
/**
2017-02-15 16:13:32 -05:00
* Hummingbird Anime List Client
*
2018-08-22 13:48:27 -04:00
* An API client for Kitsu to manage anime and manga watch lists
*
2021-02-04 11:57:01 -05:00
* PHP version 8
*
2017-02-15 16:13:32 -05:00
* @package HummingbirdAnimeClient
* @author Timothy J. Warren <tim@timshomepage.net>
2021-01-13 01:52:03 -05:00
* @copyright 2015 - 2021 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
2020-12-10 17:06:50 -05:00
* @version 5.2
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
*/
namespace Aviat\AnimeClient\API\Kitsu;
use const Aviat\AnimeClient\SESSION_SEGMENT;
use const Aviat\AnimeClient\USER_AGENT;
use function Amp\Promise\wait;
use function Aviat\AnimeClient\getResponse;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
2020-08-26 15:22:14 -04:00
use Aviat\AnimeClient\Kitsu as K;
use Aviat\AnimeClient\API\APIRequestBuilder;
use Aviat\AnimeClient\Enum\EventType;
2020-07-28 16:11:13 -04:00
use Aviat\Ion\Di\ContainerAware;
use Aviat\Ion\Di\ContainerInterface;
use Aviat\Ion\Event;
use Aviat\Ion\Json;
use Aviat\Ion\JsonException;
2020-10-21 15:45:30 -04:00
use LogicException;
2020-08-06 09:39:12 -04:00
final class RequestBuilder extends APIRequestBuilder {
2020-05-08 19:18:10 -04:00
use ContainerAware;
/**
* The base url for api requests
*/
protected string $baseUrl = K::GRAPHQL_ENDPOINT;
/**
* Where to look for GraphQL request files
*/
protected string $filePath = __DIR__;
/**
* HTTP headers to send with every request
*/
2020-04-10 16:35:01 -04:00
protected array $defaultHeaders = [
'User-Agent' => USER_AGENT,
'Accept' => 'application/vnd.api+json',
'Content-Type' => 'application/vnd.api+json',
'CLIENT_ID' => 'dd031b32d2f56c990b1425efe6c42ad847e7fe3ab46bf1299f05ecd856bdb7dd',
'CLIENT_SECRET' => '54d7307928f63414defd96399fc31ba847961ceaecef3a5fd93144e960c0e151',
];
2020-05-08 19:18:10 -04:00
public function __construct(ContainerInterface $container)
{
$this->setContainer($container);
}
/**
* Create a request object
*/
public function setUpRequest(string $type, string $url, array $options = []): Request
{
$request = $this->newRequest($type, $url);
2020-07-30 09:58:36 -04:00
$sessionSegment = $this->getContainer()
->get('session')
->getSegment(SESSION_SEGMENT);
$cache = $this->getContainer()->get('cache');
$token = null;
if ($cache->has(K::AUTH_TOKEN_CACHE_KEY))
{
$token = $cache->get(K::AUTH_TOKEN_CACHE_KEY);
}
else if ($url !== K::AUTH_URL && $sessionSegment->get('auth_token') !== NULL)
{
2020-07-30 09:58:36 -04:00
$token = $sessionSegment->get('auth_token');
if ( ! (empty($token) || $cache->has(K::AUTH_TOKEN_CACHE_KEY)))
{
$cache->set(K::AUTH_TOKEN_CACHE_KEY, $token);
}
}
if ($token !== NULL)
{
$request = $request->setAuth('bearer', $token);
}
if (array_key_exists('form_params', $options))
{
$request = $request->setFormFields($options['form_params']);
}
if (array_key_exists('query', $options))
{
$request = $request->setQuery($options['query']);
}
if (array_key_exists('body', $options))
{
$request = $request->setJsonBody($options['body']);
}
if (array_key_exists('headers', $options))
{
$request = $request->setHeaders($options['headers']);
}
return $request->getFullRequest();
}
2020-10-09 16:18:45 -04:00
/**
* Run a GraphQL API query
*
* @return mixed[]
2020-10-09 16:18:45 -04:00
*/
public function runQuery(string $name, array $variables = []): array
{
$request = $this->queryRequest($name, $variables);
$response = getResponse($request);
$validResponseCodes = [200, 201];
if ( ! \in_array($response->getStatus(), $validResponseCodes, TRUE))
{
$logger = $this->container->getLogger('kitsu-graphql');
2021-02-16 14:43:51 -05:00
if ($logger !== NULL)
{
$logger->warning('Non 200 response for GraphQL call', (array)$response->getBody());
}
2020-10-09 16:18:45 -04:00
}
return Json::decode(wait($response->getBody()->buffer()));
}
/**
* Run a GraphQL mutation
*
* @return mixed[]
*/
public function mutate(string $name, array $variables = []): array
{
$request = $this->mutateRequest($name, $variables);
2020-08-24 13:07:47 -04:00
$response = getResponse($request);
2020-10-09 16:18:45 -04:00
$validResponseCodes = [200, 201];
if ( ! \in_array($response->getStatus(), $validResponseCodes, TRUE))
{
$logger = $this->container->getLogger('kitsu-graphql');
2021-02-16 14:43:51 -05:00
if ($logger !== NULL)
{
$logger->warning('Non 200 response for GraphQL call', (array)$response->getBody());
}
2020-10-09 16:18:45 -04:00
}
return Json::decode(wait($response->getBody()->buffer()));
}
/**
* Make a request
*/
public function getResponse(string $type, string $url, array $options = []): Response
{
2020-08-17 10:23:32 -04:00
$logger = $this->container->getLogger('kitsu-request');
$request = $this->setUpRequest($type, $url, $options);
$response = getResponse($request);
2022-01-07 12:33:01 -05:00
$logger?->debug('Kitsu API Response', [
'status' => $response->getStatus(),
'reason' => $response->getReason(),
'body' => $response->getBody(),
'headers' => $response->getHeaders(),
'requestHeaders' => $request->getHeaders(),
]);
return $response;
}
2021-02-10 13:59:37 -05:00
/**
* Create a GraphQL query and return the Request object
*/
public function queryRequest(string $name, array $variables = []): Request
{
$file = realpath("{$this->filePath}/Queries/{$name}.graphql");
2021-02-12 13:09:57 -05:00
if ($file === FALSE || ! file_exists($file))
2021-02-10 13:59:37 -05:00
{
throw new LogicException('GraphQL query file does not exist.');
}
$query = file_get_contents($file);
$body = [
'query' => $query
];
if ( ! empty($variables))
{
$body['variables'] = [];
foreach($variables as $key => $val)
{
$body['variables'][$key] = $val;
}
}
return $this->setUpRequest('POST', $this->baseUrl, [
'body' => $body,
]);
}
/**
* Create a GraphQL mutation request, and return the Request object
*/
public function mutateRequest (string $name, array $variables = []): Request
{
2021-02-12 13:09:57 -05:00
$file = realpath("{$this->filePath}/Mutations/{$name}.graphql");
if ($file === FALSE || ! file_exists($file))
2021-02-10 13:59:37 -05:00
{
throw new LogicException('GraphQL mutation file does not exist.');
}
$query = file_get_contents($file);
$body = [
'query' => $query
];
if (!empty($variables)) {
$body['variables'] = [];
foreach ($variables as $key => $val)
{
$body['variables'][$key] = $val;
}
}
return $this->setUpRequest('POST', $this->baseUrl, [
'body' => $body,
]);
}
/**
* Make a request
*/
private function request(string $type, string $url, array $options = []): array
{
2020-08-17 10:23:32 -04:00
$logger = $this->container->getLogger('kitsu-request');
$response = $this->getResponse($type, $url, $options);
$statusCode = $response->getStatus();
// Check for requests that are unauthorized
if ($statusCode === 401 || $statusCode === 403)
{
Event::emit(EventType::UNAUTHORIZED);
}
$rawBody = wait($response->getBody()->buffer());
// Any other type of failed request
if ($statusCode > 299 || $statusCode < 200)
{
2021-02-16 14:43:51 -05:00
if ($logger !== NULL)
{
$logger->warning('Non 2xx response for api call', (array)$response);
}
}
2020-08-17 18:08:58 -04:00
try
{
return Json::decode($rawBody);
}
catch (JsonException)
2020-08-17 18:08:58 -04:00
{
// dump($e);
dump($rawBody);
die();
}
}
}