HandlerStackFactory.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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\HandlerStack;
  13. use Hyperf\Context\ApplicationContext;
  14. use Hyperf\Coroutine\Coroutine;
  15. use Hyperf\Di\Container;
  16. use Hyperf\Pool\SimplePool\PoolFactory;
  17. use function Hyperf\Support\make;
  18. class HandlerStackFactory
  19. {
  20. protected array $option = [
  21. 'min_connections' => 1,
  22. 'max_connections' => 30,
  23. 'wait_timeout' => 3.0,
  24. 'max_idle_time' => 60,
  25. ];
  26. protected array $middlewares = [
  27. 'retry' => [RetryMiddleware::class, [1, 10]],
  28. ];
  29. protected bool $usePoolHandler = false;
  30. public function __construct()
  31. {
  32. if (class_exists(ApplicationContext::class)) {
  33. $this->usePoolHandler = class_exists(PoolFactory::class) && ApplicationContext::getContainer() instanceof Container;
  34. }
  35. }
  36. public function create(array $option = [], array $middlewares = []): HandlerStack
  37. {
  38. $handler = null;
  39. $option = array_merge($this->option, $option);
  40. $middlewares = array_merge($this->middlewares, $middlewares);
  41. if (Coroutine::inCoroutine()) {
  42. $handler = $this->getHandler($option);
  43. }
  44. $stack = HandlerStack::create($handler);
  45. foreach ($middlewares as $key => $middleware) {
  46. if (is_array($middleware)) {
  47. [$class, $arguments] = $middleware;
  48. $middleware = new $class(...$arguments);
  49. }
  50. if ($middleware instanceof MiddlewareInterface) {
  51. $stack->push($middleware->getMiddleware(), $key);
  52. }
  53. }
  54. return $stack;
  55. }
  56. protected function getHandler(array $option)
  57. {
  58. if ($this->usePoolHandler) {
  59. return make(PoolHandler::class, [
  60. 'option' => $option,
  61. ]);
  62. }
  63. if (class_exists(ApplicationContext::class)) {
  64. return make(CoroutineHandler::class);
  65. }
  66. return new CoroutineHandler();
  67. }
  68. }