From b3743ee635703ef622fd52aef8a85c51c3cc0b82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Santoro?= Date: Fri, 1 Jul 2016 10:03:56 +0000 Subject: [PATCH] New methods: SessionStore::increment and SessionStore::decrement Several stores in the framework offer increment and decrement methods as a convenient helper method for get/set. This change implements such methods in the session store, to ease the tracking of a state into a session. For example you can: ``` $redirectsCount = Session::increment('auth.redirects'); if ($redirectsCount < 3) { // Retry to authenticate user to an external service. } ``` --- src/Illuminate/Session/Store.php | 28 ++++++++++++++++++++++++ tests/Session/SessionStoreTest.php | 34 ++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/src/Illuminate/Session/Store.php b/src/Illuminate/Session/Store.php index 6b7898f5139..b59c8b674e5 100755 --- a/src/Illuminate/Session/Store.php +++ b/src/Illuminate/Session/Store.php @@ -413,6 +413,34 @@ public function push($key, $value) $this->put($key, $array); } + /** + * Increment the value of an item in the session. + * + * @param string $key + * @param mixed $amount + * @return mixed + */ + public function increment($key, $amount = 1) + { + $value = $this->get($key, 0) + $amount; + + $this->put($key, $value); + + return $value; + } + + /** + * Decrement the value of an item in the session. + * + * @param string $key + * @param mixed $amount + * @return int + */ + public function decrement($key, $amount = 1) + { + return $this->increment($key, $amount * -1); + } + /** * Flash a key / value pair to the session. * diff --git a/tests/Session/SessionStoreTest.php b/tests/Session/SessionStoreTest.php index 87ee1a398bb..d410011f687 100644 --- a/tests/Session/SessionStoreTest.php +++ b/tests/Session/SessionStoreTest.php @@ -251,6 +251,40 @@ public function testClear() $this->assertFalse($session->getBag('bagged')->has('qu')); } + public function testIncrement() + { + $session = $this->getSession(); + + $session->set('foo', 5); + $foo = $session->increment('foo'); + $this->assertEquals(6, $foo); + $this->assertEquals(6, $session->get('foo')); + + $foo = $session->increment('foo', 4); + $this->assertEquals(10, $foo); + $this->assertEquals(10, $session->get('foo')); + + $session->increment('bar'); + $this->assertEquals(1, $session->get('bar')); + } + + public function testDecrement() + { + $session = $this->getSession(); + + $session->set('foo', 5); + $foo = $session->decrement('foo'); + $this->assertEquals(4, $foo); + $this->assertEquals(4, $session->get('foo')); + + $foo = $session->decrement('foo', 4); + $this->assertEquals(0, $foo); + $this->assertEquals(0, $session->get('foo')); + + $session->decrement('bar'); + $this->assertEquals(-1, $session->get('bar')); + } + public function testHasOldInputWithoutKey() { $session = $this->getSession();