API client for Kitsu.io, with optional Anime collection, and optional Anilist syncing.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ParallelAPIRequest.php 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php declare(strict_types=1);
  2. /**
  3. * Hummingbird Anime List Client
  4. *
  5. * An API client for Kitsu and MyAnimeList to manage anime and manga watch lists
  6. *
  7. * PHP version 7
  8. *
  9. * @package HummingbirdAnimeClient
  10. * @author Timothy J. Warren <tim@timshomepage.net>
  11. * @copyright 2015 - 2018 Timothy J. Warren
  12. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  13. * @version 4.0
  14. * @link https://git.timshomepage.net/timw4mail/HummingBirdAnimeClient
  15. */
  16. namespace Aviat\AnimeClient\API;
  17. use function Amp\call;
  18. use function Amp\Promise\{all, wait};
  19. /**
  20. * Class to simplify making and validating simultaneous requests
  21. */
  22. class ParallelAPIRequest {
  23. /**
  24. * Set of requests to make in parallel
  25. *
  26. * @var array
  27. */
  28. protected $requests = [];
  29. /**
  30. * Add a request
  31. *
  32. * @param string|Request $request
  33. * @param string|number $key
  34. * @return self
  35. */
  36. public function addRequest($request, $key = NULL): self
  37. {
  38. if ( ! is_null($key))
  39. {
  40. $this->requests[$key] = $request;
  41. return $this;
  42. }
  43. $this->requests[] = $request;
  44. return $this;
  45. }
  46. /**
  47. * Add multiple requests
  48. *
  49. * @param string[]|Request[] $requests
  50. * @return self
  51. */
  52. public function addRequests(array $requests): self
  53. {
  54. array_walk($requests, [$this, 'addRequest']);
  55. return $this;
  56. }
  57. /**
  58. * Actually make the requests
  59. *
  60. * @return array
  61. */
  62. public function makeRequests(): array
  63. {
  64. $client = new HummingbirdClient();
  65. $promises = [];
  66. foreach ($this->requests as $key => $url)
  67. {
  68. $promises[$key] = call(function () use ($client, $url) {
  69. $response = yield $client->request($url);
  70. $body = yield $response->getBody();
  71. return $body;
  72. });
  73. }
  74. return wait(all($promises));
  75. }
  76. }