ResponseCookieValueSame.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\Cookie;
  13. use Symfony\Component\HttpFoundation\Response;
  14. final class ResponseCookieValueSame extends Constraint
  15. {
  16. public function __construct(
  17. private string $name,
  18. private string $value,
  19. private string $path = '/',
  20. private ?string $domain = null,
  21. ) {
  22. }
  23. public function toString(): string
  24. {
  25. $str = \sprintf('has cookie "%s"', $this->name);
  26. if ('/' !== $this->path) {
  27. $str .= \sprintf(' with path "%s"', $this->path);
  28. }
  29. if ($this->domain) {
  30. $str .= \sprintf(' for domain "%s"', $this->domain);
  31. }
  32. return $str.\sprintf(' with value "%s"', $this->value);
  33. }
  34. /**
  35. * @param Response $response
  36. */
  37. protected function matches($response): bool
  38. {
  39. $cookie = $this->getCookie($response);
  40. if (!$cookie) {
  41. return false;
  42. }
  43. return $this->value === (string) $cookie->getValue();
  44. }
  45. /**
  46. * @param Response $response
  47. */
  48. protected function failureDescription($response): string
  49. {
  50. return 'the Response '.$this->toString();
  51. }
  52. protected function getCookie(Response $response): ?Cookie
  53. {
  54. $cookies = $response->headers->getCookies();
  55. $filteredCookies = array_filter($cookies, fn (Cookie $cookie) => $cookie->getName() === $this->name && $cookie->getPath() === $this->path && $cookie->getDomain() === $this->domain);
  56. return reset($filteredCookies) ?: null;
  57. }
  58. }