ソースを参照

Allow magic setter.

euromark 11 年 前
コミット
67a62199e8

+ 19 - 1
Controller/Component/FlashComponent.php

@@ -36,7 +36,7 @@ class FlashComponent extends Component {
 	public function beforeRender(Controller $Controller) {
 		if (Configure::read('Common.messages') !== false && $messages = $this->Session->read('Message')) {
 			foreach ($messages as $message) {
-				$this->flashMessage($message['message'], 'error');
+				$this->message($message['message'], 'error');
 			}
 			$this->Session->delete('Message');
 		}
@@ -96,4 +96,22 @@ class FlashComponent extends Component {
 		Configure::write('messages', $old);
 	}
 
+	/**
+	 * Magic method for verbose flash methods based on types.
+	 *
+	 * For example: $this->Flash->success('My 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) {
+		if (count($args) < 1) {
+			throw new InternalErrorException('Flash message missing.');
+		}
+
+		$this->message($args[0], $name);
+	}
+
 }

+ 17 - 4
Test/Case/Controller/Component/FlashComponentTest.php

@@ -22,6 +22,8 @@ class FlashComponentTest extends CakeTestCase {
 		$this->Controller = new FlashComponentTestController(new CakeRequest, new CakeResponse);
 		$this->Controller->constructClasses();
 		$this->Controller->startupProcess();
+
+		$this->Controller->Session->delete('messages');
 	}
 
 	public function tearDown() {
@@ -36,8 +38,7 @@ class FlashComponentTest extends CakeTestCase {
 	 * @return void
 	 */
 	public function testTransientMessage() {
-		$is = $this->Controller->Flash->transientMessage('xyz', 'success');
-		//$this->assertTrue($is);
+		$this->Controller->Flash->transientMessage('xyz', 'success');
 
 		$res = Configure::read('messages');
 		//debug($res);
@@ -51,14 +52,26 @@ class FlashComponentTest extends CakeTestCase {
 	 * @return void
 	 */
 	public function testFlashMessage() {
-		$this->Controller->Session->delete('messages');
-		$is = $this->Controller->Flash->message('efg');
+		$this->Controller->Flash->message('efg');
 
 		$res = $this->Controller->Session->read('messages');
 		$this->assertTrue(!empty($res));
 		$this->assertTrue(isset($res['info'][0]) && $res['info'][0] === 'efg');
 	}
 
+	public function testMagicMessage() {
+		$this->Controller->Flash->success('s');
+		$this->Controller->Flash->error('e');
+		$this->Controller->Flash->warning('w');
+
+		$res = $this->Controller->Session->read('messages');
+		$expected = array(
+			'success' => array('s'),
+			'error' => array('e'),
+			'warning' => array('w'));
+		$this->assertSame($expected, $res);
+	}
+
 }
 
 // Use Controller instead of AppController to avoid conflicts