Skip to content

Commit e2860de

Browse files
derecksontaylorotwell
authored andcommitted
New methods: SessionStore::increment and SessionStore::decrement (#14196)
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. } ```
1 parent 917dfbc commit e2860de

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

src/Illuminate/Session/Store.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,34 @@ public function push($key, $value)
413413
$this->put($key, $array);
414414
}
415415

416+
/**
417+
* Increment the value of an item in the session.
418+
*
419+
* @param string $key
420+
* @param mixed $amount
421+
* @return mixed
422+
*/
423+
public function increment($key, $amount = 1)
424+
{
425+
$value = $this->get($key, 0) + $amount;
426+
427+
$this->put($key, $value);
428+
429+
return $value;
430+
}
431+
432+
/**
433+
* Decrement the value of an item in the session.
434+
*
435+
* @param string $key
436+
* @param mixed $amount
437+
* @return int
438+
*/
439+
public function decrement($key, $amount = 1)
440+
{
441+
return $this->increment($key, $amount * -1);
442+
}
443+
416444
/**
417445
* Flash a key / value pair to the session.
418446
*

tests/Session/SessionStoreTest.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,40 @@ public function testClear()
251251
$this->assertFalse($session->getBag('bagged')->has('qu'));
252252
}
253253

254+
public function testIncrement()
255+
{
256+
$session = $this->getSession();
257+
258+
$session->set('foo', 5);
259+
$foo = $session->increment('foo');
260+
$this->assertEquals(6, $foo);
261+
$this->assertEquals(6, $session->get('foo'));
262+
263+
$foo = $session->increment('foo', 4);
264+
$this->assertEquals(10, $foo);
265+
$this->assertEquals(10, $session->get('foo'));
266+
267+
$session->increment('bar');
268+
$this->assertEquals(1, $session->get('bar'));
269+
}
270+
271+
public function testDecrement()
272+
{
273+
$session = $this->getSession();
274+
275+
$session->set('foo', 5);
276+
$foo = $session->decrement('foo');
277+
$this->assertEquals(4, $foo);
278+
$this->assertEquals(4, $session->get('foo'));
279+
280+
$foo = $session->decrement('foo', 4);
281+
$this->assertEquals(0, $foo);
282+
$this->assertEquals(0, $session->get('foo'));
283+
284+
$session->decrement('bar');
285+
$this->assertEquals(-1, $session->get('bar'));
286+
}
287+
254288
public function testHasOldInputWithoutKey()
255289
{
256290
$session = $this->getSession();

0 commit comments

Comments
 (0)