|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace LaraCrafts\UrlShortener\Tests\Unit\Http; |
| 4 | + |
| 5 | +use GuzzleHttp\Client; |
| 6 | +use GuzzleHttp\Handler\MockHandler; |
| 7 | +use GuzzleHttp\HandlerStack; |
| 8 | +use GuzzleHttp\Middleware; |
| 9 | +use Psr\Http\Message\ResponseInterface; |
| 10 | +use function GuzzleHttp\choose_handler; |
| 11 | + |
| 12 | +class MockClient extends Client |
| 13 | +{ |
| 14 | + protected $handler; |
| 15 | + protected $history; |
| 16 | + |
| 17 | + /** |
| 18 | + * Create a new test client. |
| 19 | + * |
| 20 | + * @param array $config |
| 21 | + * @return void |
| 22 | + */ |
| 23 | + public function __construct(array $config = []) |
| 24 | + { |
| 25 | + $this->handler = new MockHandler(); |
| 26 | + $this->history = []; |
| 27 | + |
| 28 | + parent::__construct($config + ['handler' => $this->newHandlerStack($this->handler)]); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Get the client history. |
| 33 | + * |
| 34 | + * @param int|null $at |
| 35 | + * @return mixed |
| 36 | + */ |
| 37 | + public function getHistory(int $at = null) |
| 38 | + { |
| 39 | + if (is_null($at)) { |
| 40 | + return $this->history; |
| 41 | + } |
| 42 | + |
| 43 | + return $this->history[$at] ?? null; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Get a previously made request. |
| 48 | + * |
| 49 | + * @param int $at |
| 50 | + * @return \Psr\Http\Message\RequestInterface|null |
| 51 | + */ |
| 52 | + public function getRequest(int $at) |
| 53 | + { |
| 54 | + return $this->getHistory($at)['request'] ?? null; |
| 55 | + } |
| 56 | + |
| 57 | + /** |
| 58 | + * Get the amount of messages waiting in the queue. |
| 59 | + * |
| 60 | + * @return int |
| 61 | + */ |
| 62 | + public function getQueueSize() |
| 63 | + { |
| 64 | + return $this->handler->count(); |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Determine if there are queued messages. |
| 69 | + * |
| 70 | + * @return bool |
| 71 | + */ |
| 72 | + public function hasQueuedMessages() |
| 73 | + { |
| 74 | + return $this->getQueueSize() > 0; |
| 75 | + } |
| 76 | + |
| 77 | + /** |
| 78 | + * Get a fresh handler stack. |
| 79 | + * |
| 80 | + * @param callable|null $handler |
| 81 | + * @return \GuzzleHttp\HandlerStack |
| 82 | + */ |
| 83 | + protected function newHandlerStack($handler = null) |
| 84 | + { |
| 85 | + $stack = new HandlerStack($handler ?: choose_handler()); |
| 86 | + $stack->push(Middleware::history($this->history)); |
| 87 | + $stack->push(Middleware::httpErrors()); |
| 88 | + |
| 89 | + return $stack; |
| 90 | + } |
| 91 | + |
| 92 | + /** |
| 93 | + * Queue the given response. |
| 94 | + * |
| 95 | + * @param \Psr\Http\Message\ResponseInterface ...$responses |
| 96 | + * @return $this |
| 97 | + */ |
| 98 | + public function queue(ResponseInterface ...$responses) |
| 99 | + { |
| 100 | + $this->handler->append(...$responses); |
| 101 | + |
| 102 | + return $this; |
| 103 | + } |
| 104 | +} |
0 commit comments