FlexibleHttpClient.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. declare(strict_types=1);
  3. namespace Http\Client\Common;
  4. use Http\Client\HttpAsyncClient;
  5. use Http\Client\HttpClient;
  6. use Psr\Http\Client\ClientInterface;
  7. /**
  8. * A flexible http client, which implements both interface and will emulate
  9. * one contract, the other, or none at all depending on the injected client contract.
  10. *
  11. * @author Joel Wurtz <joel.wurtz@gmail.com>
  12. */
  13. final class FlexibleHttpClient implements HttpClient, HttpAsyncClient
  14. {
  15. use HttpClientDecorator;
  16. use HttpAsyncClientDecorator;
  17. /**
  18. * @param ClientInterface|HttpAsyncClient $client
  19. */
  20. public function __construct($client)
  21. {
  22. if (!$client instanceof ClientInterface && !$client instanceof HttpAsyncClient) {
  23. throw new \TypeError(
  24. sprintf('%s::__construct(): Argument #1 ($client) must be of type %s|%s, %s given', self::class, ClientInterface::class, HttpAsyncClient::class, get_debug_type($client))
  25. );
  26. }
  27. $this->httpClient = $client instanceof ClientInterface ? $client : new EmulatedHttpClient($client);
  28. $this->httpAsyncClient = $client instanceof HttpAsyncClient ? $client : new EmulatedHttpAsyncClient($client);
  29. }
  30. }