|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace LaraCrafts\UrlShortener\Tests\Constraints; |
| 4 | + |
| 5 | +use GuzzleHttp\Client; |
| 6 | +use GuzzleHttp\TransferStats; |
| 7 | +use PHPUnit\Framework\Constraint\Constraint; |
| 8 | + |
| 9 | +class RedirectsTo extends Constraint |
| 10 | +{ |
| 11 | + protected $client; |
| 12 | + protected $destination; |
| 13 | + protected $redirects; |
| 14 | + |
| 15 | + /** |
| 16 | + * Create a new RedirectsTo constraint. |
| 17 | + * |
| 18 | + * @param \Psr\Http\Message\UriInterface|string $destination |
| 19 | + * @param int $redirects |
| 20 | + * @return void |
| 21 | + */ |
| 22 | + public function __construct($destination, int $redirects = 1) |
| 23 | + { |
| 24 | + $this->client = new Client(); |
| 25 | + $this->destination = rtrim($destination, '/'); |
| 26 | + $this->redirects = $redirects; |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * {@inheritDoc} |
| 31 | + */ |
| 32 | + public function evaluate($other, $description = '', $returnResult = false) |
| 33 | + { |
| 34 | + $stack = []; |
| 35 | + |
| 36 | + $this->client->get($other, [ |
| 37 | + 'allow_redirects' => [ |
| 38 | + 'max' => max($this->redirects, 5), |
| 39 | + ], |
| 40 | + 'on_stats' => function (TransferStats $stats) use (&$stack) { |
| 41 | + $stack[] = (string)$stats->getEffectiveUri(); |
| 42 | + }, |
| 43 | + ]); |
| 44 | + |
| 45 | + if (($actualRedirects = count($stack) - 1) < $this->redirects) { |
| 46 | + $this->fail($other, "Expected $this->redirects redirects, received $actualRedirects"); |
| 47 | + } |
| 48 | + |
| 49 | + if (!$this->matches($actual = $stack[$this->redirects])) { |
| 50 | + $this->fail($actual, "Expected $this->destination, received $actual"); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * {@inheritDoc} |
| 56 | + */ |
| 57 | + public function matches($other): bool |
| 58 | + { |
| 59 | + return rtrim($other, '/') === $this->destination; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * {@inheritDoc} |
| 64 | + */ |
| 65 | + public function toString(): string |
| 66 | + { |
| 67 | + return 'redirects to ' . $this->destination; |
| 68 | + } |
| 69 | +} |
0 commit comments