Ei kuvausta

ResponseHasCookie.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. }