FlashBag.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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. private string $storageKey;
  21. /**
  22. * @param string $storageKey The key used to store flashes in the session
  23. */
  24. public function __construct(string $storageKey = '_symfony_flashes')
  25. {
  26. $this->storageKey = $storageKey;
  27. }
  28. public function getName(): string
  29. {
  30. return $this->name;
  31. }
  32. /**
  33. * @return void
  34. */
  35. public function setName(string $name)
  36. {
  37. $this->name = $name;
  38. }
  39. /**
  40. * @return void
  41. */
  42. public function initialize(array &$flashes)
  43. {
  44. $this->flashes = &$flashes;
  45. }
  46. /**
  47. * @return void
  48. */
  49. public function add(string $type, mixed $message)
  50. {
  51. $this->flashes[$type][] = $message;
  52. }
  53. public function peek(string $type, array $default = []): array
  54. {
  55. return $this->has($type) ? $this->flashes[$type] : $default;
  56. }
  57. public function peekAll(): array
  58. {
  59. return $this->flashes;
  60. }
  61. public function get(string $type, array $default = []): array
  62. {
  63. if (!$this->has($type)) {
  64. return $default;
  65. }
  66. $return = $this->flashes[$type];
  67. unset($this->flashes[$type]);
  68. return $return;
  69. }
  70. public function all(): array
  71. {
  72. $return = $this->peekAll();
  73. $this->flashes = [];
  74. return $return;
  75. }
  76. /**
  77. * @return void
  78. */
  79. public function set(string $type, string|array $messages)
  80. {
  81. $this->flashes[$type] = (array) $messages;
  82. }
  83. /**
  84. * @return void
  85. */
  86. public function setAll(array $messages)
  87. {
  88. $this->flashes = $messages;
  89. }
  90. public function has(string $type): bool
  91. {
  92. return \array_key_exists($type, $this->flashes) && $this->flashes[$type];
  93. }
  94. public function keys(): array
  95. {
  96. return array_keys($this->flashes);
  97. }
  98. public function getStorageKey(): string
  99. {
  100. return $this->storageKey;
  101. }
  102. public function clear(): mixed
  103. {
  104. return $this->all();
  105. }
  106. }