ResponseHasCookie.php 1.9 KB

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