AsyncDecoratorTrait.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpClient;
  11. use Symfony\Component\HttpClient\Response\AsyncResponse;
  12. use Symfony\Component\HttpClient\Response\ResponseStream;
  13. use Symfony\Contracts\HttpClient\HttpClientInterface;
  14. use Symfony\Contracts\HttpClient\ResponseInterface;
  15. use Symfony\Contracts\HttpClient\ResponseStreamInterface;
  16. /**
  17. * Eases with processing responses while streaming them.
  18. *
  19. * @author Nicolas Grekas <p@tchwork.com>
  20. */
  21. trait AsyncDecoratorTrait
  22. {
  23. private $client;
  24. public function __construct(HttpClientInterface $client = null)
  25. {
  26. $this->client = $client ?? HttpClient::create();
  27. }
  28. /**
  29. * {@inheritdoc}
  30. *
  31. * @return AsyncResponse
  32. */
  33. abstract public function request(string $method, string $url, array $options = []): ResponseInterface;
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function stream($responses, float $timeout = null): ResponseStreamInterface
  38. {
  39. if ($responses instanceof AsyncResponse) {
  40. $responses = [$responses];
  41. } elseif (!is_iterable($responses)) {
  42. throw new \TypeError(sprintf('"%s()" expects parameter 1 to be an iterable of AsyncResponse objects, "%s" given.', __METHOD__, get_debug_type($responses)));
  43. }
  44. return new ResponseStream(AsyncResponse::stream($responses, $timeout, static::class));
  45. }
  46. }