ResponseCookieValueSame.php 2.0 KB

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