HummingBirdAnimeClient/src/AnimeClient/API/Anilist/AnilistTrait.php

293 lines
6.5 KiB
PHP
Raw Normal View History

<?php declare(strict_types=1);
/**
* Hummingbird Anime List Client
*
2018-08-22 13:48:27 -04:00
* An API client for Kitsu to manage anime and manga watch lists
*
* PHP version 7.4
*
* @package HummingbirdAnimeClient
* @author Timothy J. Warren <tim@timshomepage.net>
2020-01-08 15:39:49 -05:00
* @copyright 2015 - 2020 Timothy J. Warren
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 5
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
*/
2018-08-15 08:51:37 -04:00
namespace Aviat\AnimeClient\API\Anilist;
use const Aviat\AnimeClient\USER_AGENT;
use function Amp\Promise\wait;
2018-11-29 11:00:50 -05:00
use function Aviat\AnimeClient\getResponse;
2020-03-11 16:26:17 -04:00
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
2018-11-29 11:00:50 -05:00
use Aviat\AnimeClient\API\Anilist;
2018-08-15 14:05:28 -04:00
use Aviat\Ion\Json;
use Aviat\Ion\Di\ContainerAware;
2019-12-09 14:34:23 -05:00
use LogicException;
use Throwable;
trait AnilistTrait {
2018-08-15 14:05:28 -04:00
use ContainerAware;
/**
2018-08-22 13:48:27 -04:00
* The request builder for the Anilist API
* @var AnilistRequestBuilder
*/
protected $requestBuilder;
/**
* The base url for api requests
* @var string $base_url
*/
protected $baseUrl = Anilist::BASE_URL;
/**
* HTTP headers to send with every request
*
* @var array
*/
protected $defaultHeaders = [
'Accept' => 'application/json',
'Accept-Encoding' => 'gzip',
'Content-type' => 'application/json',
'User-Agent' => USER_AGENT,
];
/**
* Set the request builder object
*
2018-08-15 08:51:37 -04:00
* @param AnilistRequestBuilder $requestBuilder
* @return self
*/
public function setRequestBuilder($requestBuilder): self
{
$this->requestBuilder = $requestBuilder;
return $this;
}
/**
* Create a request object
* @param string $url
* @param array $options
2018-08-15 14:05:28 -04:00
* @return Request
2019-12-09 14:34:23 -05:00
* @throws Throwable
*/
2018-08-15 14:05:28 -04:00
public function setUpRequest(string $url, array $options = []): Request
{
2018-08-15 14:05:28 -04:00
$config = $this->getContainer()->get('config');
$anilistConfig = $config->get('anilist');
$request = $this->requestBuilder->newRequest('POST', $url);
// You can only authenticate the request if you
// actually have an access_token saved
if ($config->has(['anilist', 'access_token']))
2018-08-15 14:05:28 -04:00
{
$request = $request->setAuth('bearer', $anilistConfig['access_token']);
}
2018-09-26 22:31:04 -04:00
if (array_key_exists('form_params', $options))
{
2018-08-15 14:05:28 -04:00
$request = $request->setFormFields($options['form_params']);
}
2018-09-26 22:31:04 -04:00
if (array_key_exists('query', $options))
{
2018-08-15 14:05:28 -04:00
$request = $request->setQuery($options['query']);
}
2018-09-26 22:31:04 -04:00
if (array_key_exists('body', $options))
{
2018-08-15 14:05:28 -04:00
$request = $request->setJsonBody($options['body']);
}
2018-09-26 22:31:04 -04:00
if (array_key_exists('headers', $options))
{
2018-08-15 14:05:28 -04:00
$request = $request->setHeaders($options['headers']);
}
return $request->getFullRequest();
}
/**
2018-08-15 14:05:28 -04:00
* Run a GraphQL API query
*
2018-08-15 14:05:28 -04:00
* @param string $name
* @param array $variables
* @return array
*/
2018-08-15 14:05:28 -04:00
public function runQuery(string $name, array $variables = []): array
{
2018-08-15 14:05:28 -04:00
$file = realpath(__DIR__ . "/GraphQL/Queries/{$name}.graphql");
if ( ! file_exists($file))
{
2019-12-09 14:34:23 -05:00
throw new LogicException('GraphQL query file does not exist.');
}
2018-08-15 14:05:28 -04:00
// $query = str_replace(["\t", "\n"], ' ', file_get_contents($file));
$query = file_get_contents($file);
$body = [
'query' => $query
];
2018-08-15 14:05:28 -04:00
if ( ! empty($variables))
{
$body['variables'] = [];
foreach($variables as $key => $val)
{
$body['variables'][$key] = $val;
}
}
2018-08-15 14:05:28 -04:00
return $this->postRequest([
'body' => $body
]);
}
2019-12-09 14:34:23 -05:00
/**
* @param string $name
* @param array $variables
* @return Request
* @throws Throwable
*/
public function mutateRequest (string $name, array $variables = []): Request
{
$file = realpath(__DIR__ . "/GraphQL/Mutations/{$name}.graphql");
2018-09-26 22:31:04 -04:00
if (!file_exists($file))
{
2019-12-09 14:34:23 -05:00
throw new LogicException('GraphQL mutation file does not exist.');
}
// $query = str_replace(["\t", "\n"], ' ', file_get_contents($file));
$query = file_get_contents($file);
$body = [
'query' => $query
];
if (!empty($variables)) {
$body['variables'] = [];
2018-09-26 22:31:04 -04:00
foreach ($variables as $key => $val)
{
$body['variables'][$key] = $val;
}
}
return $this->setUpRequest(Anilist::BASE_URL, [
'body' => $body,
]);
}
2019-12-09 14:34:23 -05:00
/**
* @param string $name
* @param array $variables
* @return array
* @throws Throwable
*/
public function mutate (string $name, array $variables = []): array
{
$request = $this->mutateRequest($name, $variables);
$response = $this->getResponseFromRequest($request);
2020-03-11 16:26:17 -04:00
return Json::decode(wait($response->getBody()->buffer()));
}
/**
* Make a request
*
* @param string $url
* @param array $options
2018-08-15 14:05:28 -04:00
* @return Response
2019-12-09 14:34:23 -05:00
* @throws Throwable
*/
2018-08-15 14:05:28 -04:00
private function getResponse(string $url, array $options = []): Response
{
$logger = NULL;
if ($this->getContainer())
{
$logger = $this->container->getLogger('anilist-request');
}
2018-08-15 14:05:28 -04:00
$request = $this->setUpRequest($url, $options);
2018-11-29 11:00:50 -05:00
$response = getResponse($request);
2018-08-15 14:05:28 -04:00
$logger->debug('Anilist response', [
'status' => $response->getStatus(),
'reason' => $response->getReason(),
'body' => $response->getBody(),
'headers' => $response->getHeaders(),
'requestHeaders' => $request->getHeaders(),
]);
2018-08-15 14:05:28 -04:00
return $response;
}
2019-12-09 14:34:23 -05:00
/**
* @param Request $request
* @return Response
* @throws Throwable
*/
private function getResponseFromRequest(Request $request): Response
{
$logger = NULL;
2018-09-26 22:31:04 -04:00
if ($this->getContainer())
{
$logger = $this->container->getLogger('anilist-request');
}
2018-11-29 11:00:50 -05:00
$response = getResponse($request);
$logger->debug('Anilist response', [
'status' => $response->getStatus(),
'reason' => $response->getReason(),
'body' => $response->getBody(),
'headers' => $response->getHeaders(),
'requestHeaders' => $request->getHeaders(),
]);
return $response;
}
/**
* Remove some boilerplate for post requests
*
2018-08-15 14:05:28 -04:00
* @param array $options
* @return array
2019-12-09 14:34:23 -05:00
* @throws Throwable
*/
2018-08-15 14:05:28 -04:00
protected function postRequest(array $options = []): array
{
2018-09-26 22:31:04 -04:00
$response = $this->getResponse(Anilist::BASE_URL, $options);
$validResponseCodes = [200, 201];
$logger = NULL;
if ($this->getContainer())
{
$logger = $this->container->getLogger('anilist-request');
2018-09-26 22:31:04 -04:00
$logger->debug('Anilist response', [
'status' => $response->getStatus(),
'reason' => $response->getReason(),
'body' => $response->getBody(),
'headers' => $response->getHeaders(),
//'requestHeaders' => $request->getHeaders(),
]);
}
2018-08-15 14:05:28 -04:00
if ( ! \in_array($response->getStatus(), $validResponseCodes, TRUE))
{
2019-12-09 14:34:23 -05:00
if ($logger !== NULL)
{
2018-08-15 14:05:28 -04:00
$logger->warning('Non 200 response for POST api call', (array)$response->getBody());
}
}
2020-03-11 16:26:17 -04:00
// dump(wait($response->getBody()->buffer()));
2018-08-15 14:05:28 -04:00
2020-03-11 16:26:17 -04:00
return Json::decode(wait($response->getBody()->buffer()));
}
}