FlashBag.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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\Session\Flash;
  11. /**
  12. * FlashBag flash message container.
  13. *
  14. * @author Drak <drak@zikula.org>
  15. */
  16. class FlashBag implements FlashBagInterface
  17. {
  18. private string $name = 'flashes';
  19. private array $flashes = [];
  20. /**
  21. * @param string $storageKey The key used to store flashes in the session
  22. */
  23. public function __construct(
  24. private string $storageKey = '_symfony_flashes',
  25. ) {
  26. }
  27. public function getName(): string
  28. {
  29. return $this->name;
  30. }
  31. public function setName(string $name): void
  32. {
  33. $this->name = $name;
  34. }
  35. public function initialize(array &$flashes): void
  36. {
  37. $this->flashes = &$flashes;
  38. }
  39. public function add(string $type, mixed $message): void
  40. {
  41. $this->flashes[$type][] = $message;
  42. }
  43. public function peek(string $type, array $default = []): array
  44. {
  45. return $this->has($type) ? $this->flashes[$type] : $default;
  46. }
  47. public function peekAll(): array
  48. {
  49. return $this->flashes;
  50. }
  51. public function get(string $type, array $default = []): array
  52. {
  53. if (!$this->has($type)) {
  54. return $default;
  55. }
  56. $return = $this->flashes[$type];
  57. unset($this->flashes[$type]);
  58. return $return;
  59. }
  60. public function all(): array
  61. {
  62. $return = $this->peekAll();
  63. $this->flashes = [];
  64. return $return;
  65. }
  66. public function set(string $type, string|array $messages): void
  67. {
  68. $this->flashes[$type] = (array) $messages;
  69. }
  70. public function setAll(array $messages): void
  71. {
  72. $this->flashes = $messages;
  73. }
  74. public function has(string $type): bool
  75. {
  76. return \array_key_exists($type, $this->flashes) && $this->flashes[$type];
  77. }
  78. public function keys(): array
  79. {
  80. return array_keys($this->flashes);
  81. }
  82. public function getStorageKey(): string
  83. {
  84. return $this->storageKey;
  85. }
  86. public function clear(): mixed
  87. {
  88. return $this->all();
  89. }
  90. }