ResponseHasCookie.php 1.6 KB

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