ResponseHeaderLocationSame.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Test\Constraint;
  11. use PHPUnit\Framework\Constraint\Constraint;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. final class ResponseHeaderLocationSame extends Constraint
  15. {
  16. public function __construct(private Request $request, private string $expectedValue)
  17. {
  18. }
  19. public function toString(): string
  20. {
  21. return sprintf('has header "Location" matching "%s"', $this->expectedValue);
  22. }
  23. protected function matches($other): bool
  24. {
  25. if (!$other instanceof Response) {
  26. return false;
  27. }
  28. $location = $other->headers->get('Location');
  29. if (null === $location) {
  30. return false;
  31. }
  32. return $this->toFullUrl($this->expectedValue) === $this->toFullUrl($location);
  33. }
  34. protected function failureDescription($other): string
  35. {
  36. return 'the Response '.$this->toString();
  37. }
  38. private function toFullUrl(string $url): string
  39. {
  40. if (null === parse_url($url, \PHP_URL_PATH)) {
  41. $url .= '/';
  42. }
  43. if (str_starts_with($url, '//')) {
  44. return sprintf('%s:%s', $this->request->getScheme(), $url);
  45. }
  46. if (str_starts_with($url, '/')) {
  47. return $this->request->getSchemeAndHttpHost().$url;
  48. }
  49. return $url;
  50. }
  51. }