FlashComponent.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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' => [],
  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. *
  87. * @param string $message Message to output.
  88. * @param array|string $options Options or Type ('error', 'warning', 'success', 'info' or custom class).
  89. * @return void
  90. */
  91. public function message($message, $options = array()) {
  92. $message = $this->_prepMessage($message, $options);
  93. $old = (array)$this->Session->read('messages');
  94. $type = $options['type'];
  95. if (isset($old[$type]) && count($old[$type]) > 99) {
  96. array_shift($old[$type]);
  97. }
  98. $old[$type][] = $message;
  99. $this->Session->write('messages', $old);
  100. }
  101. /**
  102. * FlashComponent::_prepMessage()
  103. *
  104. * @param string $message
  105. * @param array $options
  106. * @return array
  107. */
  108. protected function _prepMessage($message, &$options) {
  109. if (!is_array($options)) {
  110. $type = $options ?: $this->settings['type'];
  111. $options = array('type' => $type);
  112. }
  113. $defaults = $this->settings;
  114. $options += $defaults;
  115. $message = array(
  116. 'message' => $options['escape'] ? h($message) : $message,
  117. 'params' => $options['params'],
  118. 'escape' => $options['escape']
  119. );
  120. if ($this->settings['useElements']) {
  121. if ($options['typeToElement'] && $options['element'] === $defaults['element']) {
  122. $options['element'] = ($options['plugin'] ? $options['plugin'] . '.' : '') . $options['type'];
  123. }
  124. list($plugin, $element) = pluginSplit($options['element']);
  125. if ($plugin) {
  126. $message['element'] = $plugin . '.Flash/' . $element;
  127. } else {
  128. $message['element'] = 'Flash/' . $element;
  129. }
  130. } else {
  131. // Simplify?
  132. if (!$message['escape'] && !$message['params']) {
  133. $message = $message['message'];
  134. }
  135. }
  136. return $message;
  137. }
  138. /**
  139. * Adds a transient flash message.
  140. * These flash messages that are not saved (only available for current view),
  141. * will be merged into the session flash ones prior to output.
  142. *
  143. * Since this method can be accessed statically, it only works with Configure configuration,
  144. * not with runtime config as the normal message() method.
  145. *
  146. * ### Options:
  147. *
  148. * - `element` The element used to render the flash message. Default to 'default'.
  149. * - `params` An array of variables to make available when using an element.
  150. * - `escape` If content should be escaped or not in the element itself or if elements are not used in the component.
  151. *
  152. * @param string $message Message to output.
  153. * @param array|string $options Options or Type ('error', 'warning', 'success', 'info' or custom class).
  154. * @return void
  155. */
  156. public static function transientMessage($message, $options = array()) {
  157. $defaults = (array)Configure::read('Flash') + array(
  158. 'type' => 'info',
  159. 'escape' => false,
  160. 'params' => array(),
  161. 'element' => 'Tools.default',
  162. 'typeToElement' => false,
  163. 'useElements' => false,
  164. 'plugin' => null,
  165. );
  166. if (!is_array($options)) {
  167. $type = $options ?: $defaults['type'];
  168. $options = array('type' => $type);
  169. }
  170. $options += $defaults;
  171. $message = array(
  172. 'message' => $message, // $options['escape'] ? h($message) : $message,
  173. 'params' => $options['params'],
  174. 'escape' => $options['escape']
  175. );
  176. if ($options['useElements']) {
  177. if ($options['typeToElement'] && $options['element'] === $defaults['element']) {
  178. $options['element'] = ($options['plugin'] ? $options['plugin'] . '.' : '') . $options['type'];
  179. }
  180. list($plugin, $element) = pluginSplit($options['element']);
  181. if ($plugin) {
  182. $message['element'] = $plugin . '.Flash/' . $element;
  183. } else {
  184. $message['element'] = 'Flash/' . $element;
  185. }
  186. } else {
  187. // Simplify?
  188. if (!$message['escape'] && !$message['params']) {
  189. $message = $message['message'];
  190. }
  191. }
  192. $old = (array)Configure::read('messages');
  193. $type = $options['type'];
  194. if (isset($old[$type]) && count($old[$type]) > 99) {
  195. array_shift($old[$type]);
  196. }
  197. $old[$type][] = $message;
  198. Configure::write('messages', $old);
  199. }
  200. /**
  201. * Magic method for verbose flash methods based on types.
  202. *
  203. * For example: $this->Flash->success('My message')
  204. *
  205. * @param string $name Element name to use.
  206. * @param array $args Parameters to pass when calling `FlashComponent::set()`.
  207. * @return void
  208. * @throws InternalErrorException If missing the flash message.
  209. */
  210. public function __call($name, $args) {
  211. if (count($args) < 1) {
  212. throw new InternalErrorException('Flash message missing.');
  213. }
  214. $options = ['type' => Inflector::underscore($name)];
  215. if (!empty($args[1])) {
  216. $options += (array)$args[1];
  217. }
  218. $this->message($args[0], $options);
  219. }
  220. }