HummingBirdAnimeClient/src/API/ParallelAPIRequest.php

85 lines
1.7 KiB
PHP
Raw Normal View History

2017-02-17 08:25:19 -05:00
<?php declare(strict_types=1);
/**
* Hummingbird Anime List Client
*
* An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
*
* PHP version 7
*
* @package HummingbirdAnimeClient
* @author Timothy J. Warren <tim@timshomepage.net>
2018-01-15 14:43:15 -05:00
* @copyright 2015 - 2018 Timothy J. Warren
2017-02-17 08:25:19 -05:00
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version 4.0
* @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
2017-02-17 08:25:19 -05:00
*/
namespace Aviat\AnimeClient\API;
use function Amp\call;
use function Amp\Promise\{all, wait};
2017-02-17 08:25:19 -05:00
/**
* Class to simplify making and validating simultaneous requests
*/
final class ParallelAPIRequest {
2017-02-17 08:25:19 -05:00
/**
* Set of requests to make in parallel
*
* @var array
*/
private $requests = [];
2017-02-17 08:25:19 -05:00
/**
* Add a request
*
2018-01-16 14:58:07 -05:00
* @param string|\Amp\Artax\Request $request
2017-02-17 08:25:19 -05:00
* @param string|number $key
* @return self
*/
2017-02-17 10:55:17 -05:00
public function addRequest($request, $key = NULL): self
2017-02-17 08:25:19 -05:00
{
2018-02-02 09:50:58 -05:00
if ($key !== NULL)
2017-02-17 08:25:19 -05:00
{
$this->requests[$key] = $request;
return $this;
}
2017-02-17 08:25:19 -05:00
$this->requests[] = $request;
return $this;
}
2017-02-17 08:25:19 -05:00
/**
* Add multiple requests
*
2018-01-16 14:58:07 -05:00
* @param string[]|\Amp\Artax\Request[] $requests
2017-02-17 08:25:19 -05:00
* @return self
*/
public function addRequests(array $requests): self
{
array_walk($requests, [$this, 'addRequest']);
return $this;
}
2017-02-17 08:25:19 -05:00
/**
* Actually make the requests
*
* @return array
2017-02-17 08:25:19 -05:00
*/
public function makeRequests(): array
2017-02-17 08:25:19 -05:00
{
$client = new HummingbirdClient();
$promises = [];
foreach ($this->requests as $key => $url)
{
$promises[$key] = call(function () use ($client, $url) {
$response = yield $client->request($url);
return yield $response->getBody();
});
}
return wait(all($promises));
2017-02-17 08:25:19 -05:00
}
}