HttpClientFactory.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Artful;
  4. use GuzzleHttp\Client;
  5. use Psr\Container\ContainerExceptionInterface;
  6. use Psr\Container\ContainerInterface;
  7. use Psr\Container\NotFoundExceptionInterface;
  8. use Psr\Http\Client\ClientInterface;
  9. use Yansongda\Artful\Contract\HttpClientInterface;
  10. use Yansongda\Artful\Exception\ContainerException;
  11. use Yansongda\Artful\Exception\Exception;
  12. use Yansongda\Artful\Exception\InvalidParamsException;
  13. class HttpClientFactory implements Contract\HttpClientFactoryInterface
  14. {
  15. public function __construct(private ContainerInterface $container) {}
  16. /**
  17. * @throws ContainerExceptionInterface
  18. * @throws ContainerException
  19. * @throws InvalidParamsException
  20. * @throws NotFoundExceptionInterface
  21. */
  22. public function create(?array $options = []): ClientInterface
  23. {
  24. if ($this->container->has(HttpClientInterface::class)) {
  25. if (($http = $this->container->get(HttpClientInterface::class)) instanceof ClientInterface) {
  26. return $http;
  27. }
  28. throw new InvalidParamsException(Exception::PARAMS_HTTP_CLIENT_INVALID, '参数异常: `HttpClient` 不符合 PSR 规范');
  29. }
  30. return new Client($options);
  31. }
  32. }