Skip to content

Commit

Permalink
Flash messages stack and in cases can result in duplicate messages wh…
Browse files Browse the repository at this point in the history
…en a message is set in AppController::beforeFilter

then a controller receives a post and has to redirect. The message will be set twice.
If a duplicate => false is set, and the message is already in the array, it will not be added.
  • Loading branch information
visualex committed Dec 6, 2016
1 parent f8ea642 commit 08e17ed
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/Controller/Component/FlashComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ class FlashComponent extends Component
'key' => 'flash',
'element' => 'default',
'params' => [],
'clear' => false
'clear' => false,
'duplicate' => true
];

/**
Expand Down Expand Up @@ -111,6 +112,14 @@ public function set($message, array $options = [])
$messages = (array)$this->_session->read('Flash.' . $options['key']);
}

if ($options['duplicate'] === false) {
foreach ($messages as $existingMessage) {
if ($existingMessage['message'] == $message) {
return;
}
}
}

$messages[] = [
'message' => $message,
'key' => $options['key'],
Expand Down
7 changes: 7 additions & 0 deletions tests/TestCase/Controller/Component/FlashComponentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,13 @@ public function testSet()
];
$result = $this->Session->read('Flash.foobar');
$this->assertEquals($expected, $result);


$this->Flash->config('duplicate', false);
$this->Flash->set('This test message should appear once only');
$this->Flash->set('This test message should appear once only');
$result = array_slice($this->Session->read('Flash.flash'), -2);
$this->assertNotEquals($result[0], $result[1]);
}

/**
Expand Down

0 comments on commit 08e17ed

Please sign in to comment.