ResponseHasCookie.php 1.8 KB

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