3 namespace Drupal\Core\Http;
5 use GuzzleHttp\HandlerStack;
6 use Symfony\Component\DependencyInjection\ContainerInterface;
9 * Defines a class for configuring middlewares on the http handler stack.
11 * The http_client service requires a handler stack to perform http requests.
12 * This is provided by the http_handler_stack service. Modules wishing to add
13 * additional middlewares to the handler stack can create services and tag them
14 * as http_client_middleware. Each service must contain an __invoke method that
15 * returns a closure which will serve as the middleware.
17 * @see https://guzzle.readthedocs.org/en/latest/handlers-and-middleware.html
19 * @see \Drupal\Core\Http\Client
20 * @see \Drupal\Core\Test\HttpClientMiddleware\TestHttpClientMiddleware
22 class HandlerStackConfigurator {
25 * Array of middlewares to add to the handler stack.
29 protected $middlewares = NULL;
32 * A list of used middleware service IDs.
36 protected $middlewareIds = [];
39 * The service container.
41 * @var \Symfony\Component\DependencyInjection\ContainerInterface
46 * Constructs a new HandlerStackConfigurator object.
48 * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
49 * The service container.
50 * @param string[] $middleware_ids
53 public function __construct(ContainerInterface $container, array $middleware_ids) {
54 $this->middlewareIds = $middleware_ids;
55 $this->container = $container;
59 * Ensures that the middlewares are initialized.
61 protected function initializeMiddlewares() {
62 if (!isset($this->middlewares)) {
63 $this->middlewares = [];
64 foreach ($this->middlewareIds as $middleware_id) {
65 $middleware = $this->container->get($middleware_id);
66 if (is_callable($middleware)) {
67 $this->middlewares[$middleware_id] = $middleware();
70 throw new \InvalidArgumentException('Middlewares need to implement __invoke, see https://guzzle.readthedocs.org/en/latest/handlers-and-middleware.html for more information about middlewares.');
77 * Configures the stack using services tagged as http_client_middleware.
79 * @param \GuzzleHttp\HandlerStack $handler_stack
82 public function configure(HandlerStack $handler_stack) {
83 $this->initializeMiddlewares();
84 foreach ($this->middlewares as $middleware_id => $middleware) {
85 $handler_stack->push($middleware, $middleware_id);