From dc82bd3462e32e56f2030289e3597142ad54a7c8 Mon Sep 17 00:00:00 2001 From: Rob Allen Date: Sun, 22 Oct 2017 11:19:20 +0100 Subject: [PATCH] Implement clearMessage & clearMessages() Based on MrSam's code in #30. --- src/Messages.php | 36 ++++++++++++++++++++++++++++++++++++ tests/MessagesTest.php | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/src/Messages.php b/src/Messages.php index 49fa9dd..58f12c3 100644 --- a/src/Messages.php +++ b/src/Messages.php @@ -171,4 +171,40 @@ public function hasMessage($key) $messages = $this->getMessages(); return isset($messages[$key]); } + + /** + * Clear all messages + * + * @return void + */ + public function clearMessages() + { + if (isset($this->storage[$this->storageKey])) { + $this->storage[$this->storageKey] = []; + } + + $this->fromPrevious = []; + $this->forNow = []; + } + + /** + * Clear specific message + * + * @param String $key The key to clear + * @return void + */ + public function clearMessage($key) + { + if (isset($this->storage[$this->storageKey][$key])) { + unset($this->storage[$this->storageKey][$key]); + } + + if (isset($this->fromPrevious[$key])) { + unset($this->fromPrevious[$key]); + } + + if (isset($this->forNow[$key])) { + unset($this->forNow[$key]); + } + } } diff --git a/tests/MessagesTest.php b/tests/MessagesTest.php index 78682f4..46e800a 100644 --- a/tests/MessagesTest.php +++ b/tests/MessagesTest.php @@ -234,4 +234,39 @@ public function testHasMessage() $flash = new Messages($storage); $this->assertTrue($flash->hasMessage('Test')); } + + public function testClearMessages() + { + $storage = ['slimFlash' => []]; + $flash = new Messages($storage); + + $storage = ['slimFlash' => [ 'Test' => ['Test']]]; + $flash = new Messages($storage); + $flash->addMessageNow('Now', 'hear this'); + $this->assertTrue($flash->hasMessage('Test')); + $this->assertTrue($flash->hasMessage('Now')); + + $flash->clearMessages(); + $this->assertFalse($flash->hasMessage('Test')); + $this->assertFalse($flash->hasMessage('Now')); + } + + public function testClearMessage() + { + $storage = ['slimFlash' => []]; + $flash = new Messages($storage); + + $storage = ['slimFlash' => [ 'Test' => ['Test'], 'Foo' => ['Bar']]]; + $flash = new Messages($storage); + $flash->addMessageNow('Now', 'hear this'); + $this->assertTrue($flash->hasMessage('Test')); + $this->assertTrue($flash->hasMessage('Foo')); + $this->assertTrue($flash->hasMessage('Now')); + + $flash->clearMessage('Test'); + $flash->clearMessage('Now'); + $this->assertFalse($flash->hasMessage('Test')); + $this->assertFalse($flash->hasMessage('Now')); + $this->assertTrue($flash->hasMessage('Foo')); + } }