Merge pull request #5855 from tanuck/2.7-custom-flash-message

Backport of 3.x flash messages #5823
This commit is contained in:
Mark Story 2015-02-14 22:07:30 -05:00
commit 9f1f158cc0
9 changed files with 548 additions and 0 deletions

View file

@ -0,0 +1,120 @@
<?php
/**
* Flash Component
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Controller.Component
* @since CakePHP(tm) v 2.7.0-dev
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Component', 'Controller');
App::uses('Inflector', 'Utility');
App::uses('CakeSession', 'Model/Datasource');
/**
* The CakePHP FlashComponent provides a way for you to write a flash variable
* to the session from your controllers, to be rendered in a view with the
* FlashHelper.
*
* @package Cake.Controller.Component
*/
class FlashComponent extends Component {
/**
* Default configuration
*
* @var array
*/
protected $_defaultConfig = array(
'key' => 'flash',
'element' => 'default',
'params' => array(),
);
/**
* Constructor
*
* @param ComponentCollection $collection The ComponentCollection object
* @param array $settings Settings passed via controller
*/
public function __construct(ComponentCollection $collection, $settings = array()) {
$this->_defaultConfig = Hash::merge($this->_defaultConfig, $settings);
}
/**
* Used to set a session variable that can be used to output messages in the view.
*
* In your controller: $this->Flash->set('This has been saved');
*
* ### Options:
*
* - `key` The key to set under the session's Flash key
* - `element` The element used to render the flash message. Default to 'default'.
* - `params` An array of variables to make available when using an element
*
* @param string $message Message to be flashed. If an instance
* of Exception the exception message will be used and code will be set
* in params.
* @param array $options An array of options.
* @return void
*/
public function set($message, $options = array()) {
$options += $this->_defaultConfig;
if ($message instanceof Exception) {
$options['params'] += array('code' => $message->getCode());
$message = $message->getMessage();
}
list($plugin, $element) = pluginSplit($options['element']);
if ($plugin) {
$options['element'] = $plugin . '.Flash/' . $element;
} else {
$options['element'] = 'Flash/' . $element;
}
CakeSession::write('Flash.' . $options['key'], array(
'message' => $message,
'key' => $options['key'],
'element' => $options['element'],
'params' => $options['params']
));
}
/**
* Magic method for verbose flash methods based on element names.
*
* For example: $this->Flash->success('My message') would use the
* success.ctp element under `app/View/Element/Flash` for rendering the
* flash message.
*
* @param string $name Element name to use.
* @param array $args Parameters to pass when calling `FlashComponent::set()`.
* @return void
* @throws InternalErrorException If missing the flash message.
*/
public function __call($name, $args) {
$options = array('element' => Inflector::underscore($name));
if (count($args) < 1) {
throw new InternalErrorException('Flash message missing.');
}
if (!empty($args[1])) {
$options += (array)$args[1];
}
$this->set($args[0], $options);
}
}

View file

@ -133,6 +133,7 @@ class SessionComponent extends Component {
* @param string $key Message key, default is 'flash'
* @return void
* @link http://book.cakephp.org/2.0/en/core-libraries/components/sessions.html#creating-notification-messages
* @deprecated 3.0.0 Since 2.7, use the FlashComponent instead.
*/
public function setFlash($message, $element = 'default', $params = array(), $key = 'flash') {
CakeSession::write('Message.' . $key, compact('message', 'element', 'params'));

View file

@ -0,0 +1,171 @@
<?php
/**
* FlashComponentTest file
*
* Series of tests for flash component.
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 2.7.0-dev
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('FlashComponent', 'Controller/Component');
App::uses('ComponentCollection', 'Controller');
/**
* FlashComponentTest class
*
* @package Cake.Test.Case.Controller.Component
*/
class FlashComponentTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Components = new ComponentCollection();
$this->Flash = new FlashComponent($this->Components);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
CakeSession::destroy();
}
/**
* testSet method
*
* @return void
*/
public function testSet() {
$this->assertNull(CakeSession::read('Flash.flash'));
$this->Flash->set('This is a test message');
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/default',
'params' => array()
);
$result = CakeSession::read('Flash.flash');
$this->assertEquals($expected, $result);
$this->Flash->set('This is a test message', array(
'element' => 'test',
'params' => array('foo' => 'bar')
));
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/test',
'params' => array('foo' => 'bar')
);
$result = CakeSession::read('Flash.flash');
$this->assertEquals($expected, $result);
$this->Flash->set('This is a test message', array('element' => 'MyPlugin.alert'));
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'MyPlugin.Flash/alert',
'params' => array()
);
$result = CakeSession::read('Flash.flash');
$this->assertEquals($expected, $result);
$this->Flash->set('This is a test message', array('key' => 'foobar'));
$expected = array(
'message' => 'This is a test message',
'key' => 'foobar',
'element' => 'Flash/default',
'params' => array()
);
$result = CakeSession::read('Flash.foobar');
$this->assertEquals($expected, $result);
}
/**
* testSetWithException method
*
* @return void
*/
public function testSetWithException() {
$this->assertNull(CakeSession::read('Flash.flash'));
$this->Flash->set(new Exception('This is a test message', 404));
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/default',
'params' => array('code' => 404)
);
$result = CakeSession::read('Flash.flash');
$this->assertEquals($expected, $result);
}
/**
* testSetWithComponentConfiguration method
*
* @return void
*/
public function testSetWithComponentConfiguration() {
$this->assertNull(CakeSession::read('Flash.flash'));
$FlashWithSettings = $this->Components->load('Flash', array('element' => 'test'));
$FlashWithSettings->set('This is a test message');
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/test',
'params' => array()
);
$result = CakeSession::read('Flash.flash');
$this->assertEquals($expected, $result);
}
/**
* Test magic call method.
*
* @return void
*/
public function testCall() {
$this->assertNull(CakeSession::read('Flash.flash'));
$this->Flash->success('It worked');
$expected = array(
'message' => 'It worked',
'key' => 'flash',
'element' => 'Flash/success',
'params' => array()
);
$result = CakeSession::read('Flash.flash');
$this->assertEquals($expected, $result);
$this->Flash->error('It did not work', array('element' => 'error_thing'));
$expected = array(
'message' => 'It did not work',
'key' => 'flash',
'element' => 'Flash/error',
'params' => array()
);
$result = CakeSession::read('Flash.flash');
$this->assertEquals($expected, $result, 'Element is ignored in magic call.');
}
}

View file

@ -0,0 +1,158 @@
<?php
/**
* FlashHelperTest file
*
* Series of tests for flash helper.
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 2.7.0-dev
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('FlashHelper', 'View/Helper');
App::uses('View', 'View');
App::uses('CakePlugin', 'Core');
/**
* FlashHelperTest class
*
* @package Cake.Test.Case.View.Helper
*/
class FlashHelperTest extends CakeTestCase {
/**
* setupBeforeClass method
*
* @return void
*/
public static function setupBeforeClass() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
}
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = new View($controller);
$this->Flash = new FlashHelper($this->View);
if (!CakeSession::started()) {
CakeSession::start();
}
CakeSession::write(array(
'Flash' => array(
'flash' => array(
'key' => 'flash',
'message' => 'This is a calling',
'element' => 'Flash/default',
'params' => array()
),
'notification' => array(
'key' => 'notification',
'message' => 'Broadcast message testing',
'element' => 'flash_helper',
'params' => array(
'title' => 'Notice!',
'name' => 'Alert!'
)
),
'classy' => array(
'key' => 'classy',
'message' => 'Recorded',
'element' => 'flash_classy',
'params' => array()
)
)
));
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->View, $this->Flash);
CakeSession::destroy();
}
/**
* testFlash method
*
* @return void
*/
public function testFlash() {
$result = $this->Flash->render();
$expected = '<div class="message">This is a calling</div>';
$this->assertContains($expected, $result);
$expected = '<div id="classy-message">Recorded</div>';
$result = $this->Flash->render('classy');
$this->assertContains($expected, $result);
$result = $this->Flash->render('notification');
$expected = "<div id=\"notificationLayout\">\n\t<h1>Alert!</h1>\n\t<h3>Notice!</h3>\n\t<p>Broadcast message testing</p>\n</div>";
$this->assertContains($expected, $result);
$this->assertNull($this->Flash->render('non-existent'));
}
/**
* testFlashThrowsException
*
* @expectedException UnexpectedValueException
*/
public function testFlashThrowsException() {
CakeSession::write('Flash.foo', 'bar');
$this->Flash->render('foo');
}
/**
* test setting the element from the attrs.
*
* @return void
*/
public function testFlashElementInAttrs() {
$result = $this->Flash->render('notification', array(
'element' => 'flash_helper',
'params' => array('title' => 'Alert!', 'name' => 'Notice!')
));
$expected = "<div id=\"notificationLayout\">\n\t<h1>Notice!</h1>\n\t<h3>Alert!</h3>\n\t<p>Broadcast message testing</p>\n</div>";
$this->assertContains($expected, $result);
}
/**
* test using elements in plugins.
*
* @return void
*/
public function testFlashWithPluginElement() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$result = $this->Flash->render('flash', array('element' => 'TestPlugin.plugin_element'));
$expected = 'this is the plugin element';
$this->assertContains($expected, $result);
}
}

View file

@ -0,0 +1 @@
<div class="message"><?php echo $message ?></div>

View file

@ -0,0 +1 @@
<div id="<?php echo $key ?>-message"><?php echo $message; ?></div>

View file

@ -0,0 +1,5 @@
<div id="notificationLayout">
<h1><?php echo $params['name']; ?></h1>
<h3><?php echo $params['title']; ?></h3>
<p><?php echo $message; ?></p>
</div>

View file

@ -0,0 +1,90 @@
<?php
/**
* Flash Helper
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.View.Helper
* @since CakePHP(tm) v 2.7.0-dev
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AppHelper', 'View/Helper');
App::uses('CakeSession', 'Model/Datasource');
/**
* FlashHelper class to render flash messages.
*
* After setting messages in your controllers with FlashComponent, you can use
* this class to output your flash messages in your views.
*
* @package Cake.View.Helper
*/
class FlashHelper extends AppHelper {
/**
* Used to render the message set in FlashComponent::set()
*
* In your view: $this->Flash->render('somekey');
* Will default to flash if no param is passed
*
* You can pass additional information into the flash message generation. This allows you
* to consolidate all the parameters for a given type of flash message into the view.
*
* ```
* echo $this->Flash->render('flash', array('params' => array('name' => $user['User']['name'])));
* ```
*
* This would pass the current user's name into the flash message, so you could create personalized
* messages without the controller needing access to that data.
*
* Lastly you can choose the element that is used for rendering the flash message. Using
* custom elements allows you to fully customize how flash messages are generated.
*
* ```
* echo $this->Flash->render('flash', array('element' => 'my_custom_element'));
* ```
*
* If you want to use an element from a plugin for rendering your flash message
* you can use the dot notation for the plugin's element name:
*
* ```
* echo $this->Flash->render('flash', array(
* 'element' => 'MyPlugin.my_custom_element',
* ));
* ```
*
* @param string $key The [Flash.]key you are rendering in the view.
* @param array $options Additional options to use for the creation of this flash message.
* Supports the 'params', and 'element' keys that are used in the helper.
* @return string|null Rendered flash message or null if flash key does not exist
* in session.
* @throws UnexpectedValueException If value for flash settings key is not an array.
*/
public function render($key = 'flash', $options = array()) {
if (!CakeSession::check("Flash.$key")) {
return;
}
$flash = CakeSession::read("Flash.$key");
if (!is_array($flash)) {
throw new UnexpectedValueException(sprintf(
'Value for flash setting key "%s" must be an array.',
$key
));
}
$flash = $options + $flash;
CakeSession::delete("Flash.$key");
return $this->_View->element($flash['element'], $flash);
}
}

View file

@ -126,6 +126,7 @@ class SessionHelper extends AppHelper {
* Supports the 'params', and 'element' keys that are used in the helper.
* @return string
* @link http://book.cakephp.org/2.0/en/core-libraries/helpers/session.html#SessionHelper::flash
* @deprecated 3.0.0 Since 2.7, use FlashHelper::render() instead.
*/
public function flash($key = 'flash', $attrs = array()) {
$out = false;