Skip to content

Commit

Permalink
New methods: SessionStore::increment and SessionStore::decrement (#14196
Browse files Browse the repository at this point in the history
)

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.
        }
```
  • Loading branch information
dereckson authored and taylorotwell committed Jul 1, 2016
1 parent 917dfbc commit e2860de
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/Illuminate/Session/Store.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
34 changes: 34 additions & 0 deletions tests/Session/SessionStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit e2860de

Please sign in to comment.