FlashComponent.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. <?php
  2. App::uses('Component', 'Controller');
  3. /**
  4. * A flash component to enhance flash message support with stackable messages, both
  5. * persistent and transient.
  6. *
  7. * @author Mark Scherer
  8. * @copyright 2012 Mark Scherer
  9. * @license http://opensource.org/licenses/mit-license.php MIT
  10. */
  11. class FlashComponent extends Component {
  12. public $components = array('Session');
  13. protected $_defaultConfig = array(
  14. 'headerOnAjax' => true,
  15. 'transformCore' => true,
  16. 'useElements' => false, // Set to true to use 3.x flash message rendering via Elements
  17. 'type' => 'info',
  18. 'typeToElement' => false, // Set to true to have a single type to Element matching
  19. 'plugin' => null, // Only for typeToElement
  20. 'element' => 'Tools.default',
  21. 'params' => array(),
  22. 'escape' => false
  23. );
  24. /**
  25. * Constructor.
  26. *
  27. * @param ComponentCollection $collection
  28. * @param array $config
  29. */
  30. public function __construct(ComponentCollection $collection, $config = array()) {
  31. $defaults = (array)Configure::read('Flash') + $this->_defaultConfig;
  32. //BC
  33. if (Configure::read('Common.messages') !== null) {
  34. $defaults['transformCore'] = Configure::read('Common.messages');
  35. }
  36. $config += $defaults;
  37. parent::__construct($collection, $config);
  38. }
  39. /**
  40. * For automatic startup
  41. * for this helper the controller has to be passed as reference
  42. *
  43. * @return void
  44. */
  45. public function initialize(Controller $Controller) {
  46. parent::initialize($Controller);
  47. $this->Controller = $Controller;
  48. }
  49. /**
  50. * Called after the Controller::beforeRender(), after the view class is loaded, and before the
  51. * Controller::render()
  52. *
  53. * Unless Configure::read('Ajax.transformCore') is false, it will also transform any core ones to this plugin.
  54. * Unless Configure::read('Ajax.headerOnAjax') is false, it will pass the messages as header to AJAX requests.
  55. * Set it to false if other components are handling the message return in AJAX use cases already.
  56. *
  57. * @param object $Controller Controller with components to beforeRender
  58. * @return void
  59. */
  60. public function beforeRender(Controller $Controller) {
  61. if ($this->settings['transformCore'] && $messages = $this->Session->read('Message')) {
  62. foreach ($messages as $message) {
  63. $this->message($message['message'], 'error');
  64. }
  65. $this->Session->delete('Message');
  66. }
  67. if ($this->settings['headerOnAjax'] && $this->Controller->request->is('ajax')) {
  68. $ajaxMessages = array_merge(
  69. (array)$this->Session->read('messages'),
  70. (array)Configure::read('messages')
  71. );
  72. // The header can be read with JavaScript and a custom Message can be displayed
  73. $this->Controller->response->header('X-Ajax-Flashmessage', json_encode($ajaxMessages));
  74. $this->Session->delete('messages');
  75. }
  76. }
  77. /**
  78. * Adds a flash message.
  79. * Updates "messages" session content (to enable multiple messages of one type).
  80. *
  81. * ### Options:
  82. *
  83. * - `element` The element used to render the flash message. Default to 'default'.
  84. * - `params` An array of variables to make available when using an element.
  85. * - `escape` If content should be escaped or not in the element itself or if elements are not used in the component.
  86. * - `typeToElement`
  87. * - `plugin`
  88. *
  89. * @param string $message Message to output.
  90. * @param array|string $options Options or Type ('error', 'warning', 'success', 'info' or custom class).
  91. * @return void
  92. */
  93. public function message($message, $options = array()) {
  94. $message = $this->_prepMessage($message, $options, $this->settings);
  95. $old = (array)$this->Session->read('messages');
  96. $type = $options['type'];
  97. if (isset($old[$type]) && count($old[$type]) > 99) {
  98. array_shift($old[$type]);
  99. }
  100. $old[$type][] = $message;
  101. $this->Session->write('messages', $old);
  102. }
  103. /**
  104. * Adds a transient flash message.
  105. * These flash messages that are not saved (only available for current view),
  106. * will be merged into the session flash ones prior to output.
  107. *
  108. * Since this method can be accessed statically, it only works with Configure configuration,
  109. * not with runtime config as the normal message() method.
  110. *
  111. * ### Options:
  112. *
  113. * - `element` The element used to render the flash message. Default to 'default'.
  114. * - `params` An array of variables to make available when using an element.
  115. * - `escape` If content should be escaped or not in the element itself or if elements are not used in the component.
  116. * - `typeToElement`
  117. * - `plugin`
  118. * - `useElements`
  119. *
  120. * @param string $message Message to output.
  121. * @param array|string $options Options or Type ('error', 'warning', 'success', 'info' or custom class).
  122. * @return void
  123. */
  124. public static function transientMessage($message, $options = array()) {
  125. $defaults = (array)Configure::read('Flash') + array(
  126. 'type' => 'info',
  127. 'escape' => false,
  128. 'params' => array(),
  129. 'element' => 'Tools.default',
  130. 'typeToElement' => false,
  131. 'useElements' => false,
  132. 'plugin' => null,
  133. );
  134. $message = static::_prepMessage($message, $options, $defaults);
  135. $old = (array)Configure::read('messages');
  136. $type = $options['type'];
  137. if (isset($old[$type]) && count($old[$type]) > 99) {
  138. array_shift($old[$type]);
  139. }
  140. $old[$type][] = $message;
  141. Configure::write('messages', $old);
  142. }
  143. /**
  144. * FlashComponent::_prepMessage()
  145. *
  146. * @param string $message
  147. * @param array $options
  148. * @return array
  149. */
  150. protected static function _prepMessage($message, &$options, $defaults) {
  151. if (!is_array($options)) {
  152. $type = $options ?: $defaults['type'];
  153. $options = array('type' => $type);
  154. }
  155. $options += $defaults;
  156. $message = array(
  157. 'message' => $options['escape'] ? h($message) : $message,
  158. 'params' => $options['params'],
  159. 'escape' => $options['escape']
  160. );
  161. if ($options['useElements']) {
  162. if ($options['typeToElement'] && $options['element'] === $defaults['element']) {
  163. $options['element'] = ($options['plugin'] ? $options['plugin'] . '.' : '') . $options['type'];
  164. }
  165. list($plugin, $element) = pluginSplit($options['element']);
  166. if ($plugin) {
  167. $message['element'] = $plugin . '.Flash/' . $element;
  168. } else {
  169. $message['element'] = 'Flash/' . $element;
  170. }
  171. } else {
  172. // Simplify?
  173. if (!$message['escape'] && !$message['params']) {
  174. $message = $message['message'];
  175. }
  176. }
  177. return $message;
  178. }
  179. /**
  180. * Magic method for verbose flash methods based on types.
  181. *
  182. * For example: $this->Flash->success('My message')
  183. *
  184. * @param string $name Element name to use.
  185. * @param array $args Parameters to pass when calling `FlashComponent::set()`.
  186. * @return void
  187. * @throws InternalErrorException If missing the flash message.
  188. */
  189. public function __call($name, $args) {
  190. if (count($args) < 1) {
  191. throw new InternalErrorException('Flash message missing.');
  192. }
  193. $options = ['type' => Inflector::underscore($name)];
  194. if (!empty($args[1])) {
  195. $options += (array)$args[1];
  196. }
  197. $this->message($args[0], $options);
  198. }
  199. }