You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.1 KiB

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