vendor/sylius/resource-bundle/src/Bundle/Storage/CookieStorage.php line 55

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Sylius package.
  4. *
  5. * (c) Paweł Jędrzejewski
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. declare(strict_types=1);
  11. namespace Sylius\Bundle\ResourceBundle\Storage;
  12. use Sylius\Component\Resource\Storage\StorageInterface;
  13. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  14. use Symfony\Component\HttpFoundation\Cookie;
  15. use Symfony\Component\HttpFoundation\ParameterBag;
  16. use Symfony\Component\HttpKernel\Event\RequestEvent;
  17. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  18. use Symfony\Component\HttpKernel\KernelEvents;
  19. use Webmozart\Assert\Assert;
  20. final class CookieStorage implements StorageInterface, EventSubscriberInterface
  21. {
  22. private ParameterBag $requestCookies;
  23. private ParameterBag $responseCookies;
  24. public function __construct()
  25. {
  26. $this->requestCookies = new ParameterBag();
  27. $this->responseCookies = new ParameterBag();
  28. }
  29. public static function getSubscribedEvents(): array
  30. {
  31. return [
  32. KernelEvents::REQUEST => [['onKernelRequest', 1024]],
  33. KernelEvents::RESPONSE => [['onKernelResponse', -1024]],
  34. ];
  35. }
  36. public function onKernelRequest(RequestEvent $event): void
  37. {
  38. if (!$event->isMainRequest()) {
  39. return;
  40. }
  41. $this->requestCookies = new ParameterBag($event->getRequest()->cookies->all());
  42. $this->responseCookies = new ParameterBag();
  43. }
  44. public function onKernelResponse(ResponseEvent $event): void
  45. {
  46. if (!$event->isMainRequest()) {
  47. return;
  48. }
  49. $response = $event->getResponse();
  50. /** @var string|null $value */
  51. foreach ($this->responseCookies as $name => $value) {
  52. Assert::nullOrString($value);
  53. $response->headers->setCookie(new Cookie($name, $value));
  54. }
  55. $this->requestCookies = new ParameterBag();
  56. $this->responseCookies = new ParameterBag();
  57. }
  58. public function has(string $name): bool
  59. {
  60. return !in_array($this->get($name), ['', null], true);
  61. }
  62. public function get(string $name, $default = null)
  63. {
  64. return $this->responseCookies->get($name, $this->requestCookies->get($name, $default));
  65. }
  66. public function set(string $name, $value): void
  67. {
  68. $this->responseCookies->set($name, $value);
  69. }
  70. public function remove(string $name): void
  71. {
  72. $this->set($name, null);
  73. }
  74. public function all(): array
  75. {
  76. return array_merge($this->responseCookies->all(), $this->requestCookies->all());
  77. }
  78. }