ClientFactory.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Guzzle;
  12. use GuzzleHttp\Client;
  13. use GuzzleHttp\HandlerStack;
  14. use Hyperf\Coroutine\Coroutine;
  15. use Hyperf\Di\Container;
  16. use Psr\Container\ContainerInterface;
  17. use Swoole\Runtime;
  18. /**
  19. * @property Container $container
  20. */
  21. class ClientFactory
  22. {
  23. protected bool $runInSwoole = false;
  24. protected int $nativeCurlHook = 0;
  25. public function __construct(private ContainerInterface $container)
  26. {
  27. $this->runInSwoole = extension_loaded('swoole');
  28. if (defined('SWOOLE_HOOK_NATIVE_CURL')) {
  29. $this->nativeCurlHook = SWOOLE_HOOK_NATIVE_CURL;
  30. }
  31. }
  32. public function create(array $options = []): Client
  33. {
  34. $stack = null;
  35. if (
  36. $this->runInSwoole
  37. && Coroutine::inCoroutine()
  38. && (Runtime::getHookFlags() & $this->nativeCurlHook) == 0
  39. ) {
  40. $stack = HandlerStack::create(new CoroutineHandler());
  41. }
  42. $config = array_replace(['handler' => $stack], $options);
  43. if (method_exists($this->container, 'make')) {
  44. // Create by DI for AOP.
  45. return $this->container->make(Client::class, ['config' => $config]);
  46. }
  47. return new Client($config);
  48. }
  49. }