FlashComponent.php 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Controller\Component;
  16. use Cake\Controller\Component;
  17. use Cake\Controller\ComponentRegistry;
  18. use Cake\Http\Exception\InternalErrorException;
  19. use Cake\Utility\Inflector;
  20. use Exception;
  21. /**
  22. * The CakePHP FlashComponent provides a way for you to write a flash variable
  23. * to the session from your controllers, to be rendered in a view with the
  24. * FlashHelper.
  25. *
  26. * @method void success(string $message, array $options = []) Set a message using "success" element
  27. * @method void error(string $message, array $options = []) Set a message using "error" element
  28. */
  29. class FlashComponent extends Component
  30. {
  31. /**
  32. * The Session object instance
  33. *
  34. * @var \Cake\Http\Session
  35. */
  36. protected $_session;
  37. /**
  38. * Default configuration
  39. *
  40. * @var array
  41. */
  42. protected $_defaultConfig = [
  43. 'key' => 'flash',
  44. 'element' => 'default',
  45. 'params' => [],
  46. 'clear' => false,
  47. 'duplicate' => true
  48. ];
  49. /**
  50. * Constructor
  51. *
  52. * @param \Cake\Controller\ComponentRegistry $registry A ComponentRegistry for this component
  53. * @param array $config Array of config.
  54. */
  55. public function __construct(ComponentRegistry $registry, array $config = [])
  56. {
  57. parent::__construct($registry, $config);
  58. $this->_session = $registry->getController()->getRequest()->getSession();
  59. }
  60. /**
  61. * Used to set a session variable that can be used to output messages in the view.
  62. * If you make consecutive calls to this method, the messages will stack (if they are
  63. * set with the same flash key)
  64. *
  65. * In your controller: $this->Flash->set('This has been saved');
  66. *
  67. * ### Options:
  68. *
  69. * - `key` The key to set under the session's Flash key
  70. * - `element` The element used to render the flash message. Default to 'default'.
  71. * - `params` An array of variables to make available when using an element
  72. * - `clear` A bool stating if the current stack should be cleared to start a new one
  73. * - `escape` Set to false to allow templates to print out HTML content
  74. *
  75. * @param string|\Exception $message Message to be flashed. If an instance
  76. * of \Exception the exception message will be used and code will be set
  77. * in params.
  78. * @param array $options An array of options
  79. * @return void
  80. */
  81. public function set($message, array $options = [])
  82. {
  83. $options += (array)$this->getConfig();
  84. if ($message instanceof Exception) {
  85. if (!isset($options['params']['code'])) {
  86. $options['params']['code'] = $message->getCode();
  87. }
  88. $message = $message->getMessage();
  89. }
  90. if (isset($options['escape']) && !isset($options['params']['escape'])) {
  91. $options['params']['escape'] = $options['escape'];
  92. }
  93. list($plugin, $element) = pluginSplit($options['element']);
  94. if ($plugin) {
  95. $options['element'] = $plugin . '.Flash/' . $element;
  96. } else {
  97. $options['element'] = 'Flash/' . $element;
  98. }
  99. $messages = [];
  100. if (!$options['clear']) {
  101. $messages = (array)$this->_session->read('Flash.' . $options['key']);
  102. }
  103. if (!$options['duplicate']) {
  104. foreach ($messages as $existingMessage) {
  105. if ($existingMessage['message'] === $message) {
  106. return;
  107. }
  108. }
  109. }
  110. $messages[] = [
  111. 'message' => $message,
  112. 'key' => $options['key'],
  113. 'element' => $options['element'],
  114. 'params' => $options['params']
  115. ];
  116. $this->_session->write('Flash.' . $options['key'], $messages);
  117. }
  118. /**
  119. * Magic method for verbose flash methods based on element names.
  120. *
  121. * For example: $this->Flash->success('My message') would use the
  122. * success.ctp element under `src/Template/Element/Flash` for rendering the
  123. * flash message.
  124. *
  125. * If you make consecutive calls to this method, the messages will stack (if they are
  126. * set with the same flash key)
  127. *
  128. * Note that the parameter `element` will be always overridden. In order to call a
  129. * specific element from a plugin, you should set the `plugin` option in $args.
  130. *
  131. * For example: `$this->Flash->warning('My message', ['plugin' => 'PluginName'])` would
  132. * use the warning.ctp element under `plugins/PluginName/src/Template/Element/Flash` for
  133. * rendering the flash message.
  134. *
  135. * @param string $name Element name to use.
  136. * @param array $args Parameters to pass when calling `FlashComponent::set()`.
  137. * @return void
  138. * @throws \Cake\Http\Exception\InternalErrorException If missing the flash message.
  139. */
  140. public function __call($name, $args)
  141. {
  142. $element = Inflector::underscore($name);
  143. if (count($args) < 1) {
  144. throw new InternalErrorException('Flash message missing.');
  145. }
  146. $options = ['element' => $element];
  147. if (!empty($args[1])) {
  148. if (!empty($args[1]['plugin'])) {
  149. $options = ['element' => $args[1]['plugin'] . '.' . $element];
  150. unset($args[1]['plugin']);
  151. }
  152. $options += (array)$args[1];
  153. }
  154. $this->set($args[0], $options);
  155. }
  156. }