vendor/guzzlehttp/guzzle/src/Handler/MockHandler.php

211 lines · 6378 bytes

  1<?php
  2
  3namespace GuzzleHttp\Handler;
  4
  5use GuzzleHttp\Exception\RequestException;
  6use GuzzleHttp\HandlerStack;
  7use GuzzleHttp\Promise as P;
  8use GuzzleHttp\Promise\PromiseInterface;
  9use GuzzleHttp\TransferStats;
 10use Psr\Http\Message\RequestInterface;
 11use Psr\Http\Message\ResponseInterface;
 12use Psr\Http\Message\StreamInterface;
 13
 14/**
 15 * Handler that returns responses or throw exceptions from a queue.
 16 *
 17 * @final
 18 */
 19class MockHandler implements \Countable
 20{
 21    /**
 22     * @var array
 23     */
 24    private $queue = [];
 25
 26    /**
 27     * @var RequestInterface|null
 28     */
 29    private $lastRequest;
 30
 31    /**
 32     * @var array
 33     */
 34    private $lastOptions = [];
 35
 36    /**
 37     * @var callable|null
 38     */
 39    private $onFulfilled;
 40
 41    /**
 42     * @var callable|null
 43     */
 44    private $onRejected;
 45
 46    /**
 47     * Creates a new MockHandler that uses the default handler stack list of
 48     * middlewares.
 49     *
 50     * @param array|null    $queue       Array of responses, callables, or exceptions.
 51     * @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
 52     * @param callable|null $onRejected  Callback to invoke when the return value is rejected.
 53     */
 54    public static function createWithMiddleware(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null): HandlerStack
 55    {
 56        return HandlerStack::create(new self($queue, $onFulfilled, $onRejected));
 57    }
 58
 59    /**
 60     * The passed in value must be an array of
 61     * {@see ResponseInterface} objects, Exceptions,
 62     * callables, or Promises.
 63     *
 64     * @param array<int, mixed>|null $queue       The parameters to be passed to the append function, as an indexed array.
 65     * @param callable|null          $onFulfilled Callback to invoke when the return value is fulfilled.
 66     * @param callable|null          $onRejected  Callback to invoke when the return value is rejected.
 67     */
 68    public function __construct(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null)
 69    {
 70        $this->onFulfilled = $onFulfilled;
 71        $this->onRejected = $onRejected;
 72
 73        if ($queue) {
 74            // array_values included for BC
 75            $this->append(...array_values($queue));
 76        }
 77    }
 78
 79    public function __invoke(RequestInterface $request, array $options): PromiseInterface
 80    {
 81        if (!$this->queue) {
 82            throw new \OutOfBoundsException('Mock queue is empty');
 83        }
 84
 85        if (isset($options['delay']) && \is_numeric($options['delay'])) {
 86            \usleep((int) ($options['delay'] * 1000));
 87        }
 88
 89        $this->lastRequest = $request;
 90        $this->lastOptions = $options;
 91        $response = \array_shift($this->queue);
 92
 93        if (isset($options['on_headers'])) {
 94            if (!\is_callable($options['on_headers'])) {
 95                throw new \InvalidArgumentException('on_headers must be callable');
 96            }
 97            try {
 98                $options['on_headers']($response);
 99            } catch (\Exception $e) {
100                $msg = 'An error was encountered during the on_headers event';
101                $response = new RequestException($msg, $request, $response, $e);
102            }
103        }
104
105        if (\is_callable($response)) {
106            $response = $response($request, $options);
107        }
108
109        $response = $response instanceof \Throwable
110            ? P\Create::rejectionFor($response)
111            : P\Create::promiseFor($response);
112
113        return $response->then(
114            function (?ResponseInterface $value) use ($request, $options) {
115                $this->invokeStats($request, $options, $value);
116                if ($this->onFulfilled) {
117                    ($this->onFulfilled)($value);
118                }
119
120                if ($value !== null && isset($options['sink'])) {
121                    $contents = (string) $value->getBody();
122                    $sink = $options['sink'];
123
124                    if (\is_resource($sink)) {
125                        \fwrite($sink, $contents);
126                    } elseif (\is_string($sink)) {
127                        \file_put_contents($sink, $contents);
128                    } elseif ($sink instanceof StreamInterface) {
129                        $sink->write($contents);
130                    }
131                }
132
133                return $value;
134            },
135            function ($reason) use ($request, $options) {
136                $this->invokeStats($request, $options, null, $reason);
137                if ($this->onRejected) {
138                    ($this->onRejected)($reason);
139                }
140
141                return P\Create::rejectionFor($reason);
142            }
143        );
144    }
145
146    /**
147     * Adds one or more variadic requests, exceptions, callables, or promises
148     * to the queue.
149     *
150     * @param mixed ...$values
151     */
152    public function append(...$values): void
153    {
154        foreach ($values as $value) {
155            if ($value instanceof ResponseInterface
156                || $value instanceof \Throwable
157                || $value instanceof PromiseInterface
158                || \is_callable($value)
159            ) {
160                $this->queue[] = $value;
161            } else {
162                throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.\get_debug_type($value));
163            }
164        }
165    }
166
167    /**
168     * Get the last received request.
169     */
170    public function getLastRequest(): ?RequestInterface
171    {
172        return $this->lastRequest;
173    }
174
175    /**
176     * Get the last received request options.
177     */
178    public function getLastOptions(): array
179    {
180        return $this->lastOptions;
181    }
182
183    /**
184     * Returns the number of remaining items in the queue.
185     */
186    public function count(): int
187    {
188        return \count($this->queue);
189    }
190
191    public function reset(): void
192    {
193        $this->queue = [];
194    }
195
196    /**
197     * @param mixed $reason Promise or reason.
198     */
199    private function invokeStats(
200        RequestInterface $request,
201        array $options,
202        ?ResponseInterface $response = null,
203        $reason = null
204    ): void {
205        if (isset($options['on_stats'])) {
206            $transferTime = $options['transfer_time'] ?? 0;
207            $stats = new TransferStats($request, $response, $transferTime, $reason);
208            ($options['on_stats'])($stats);
209        }
210    }
211}