Skip to content

Commit

Permalink
Add remember helper to session store
Browse files Browse the repository at this point in the history
  • Loading branch information
Ricky-rick committed Oct 21, 2016
1 parent b431c97 commit 3436c85
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Illuminate/Session/Store.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Session;

use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use SessionHandlerInterface;
Expand Down Expand Up @@ -748,4 +749,24 @@ public function setRequestOnHandler(Request $request)
$this->handler->setRequest($request);
}
}

/**
* Get an item from the sessuib, or store the default value.
*
* @param string $key
* @param \Closure $callback
* @return mixed
*/
public function remember($key, Closure $callback)
{
// If the item exists in the session we will just return this immediately
// otherwise we will execute the given Closure and store the result
if (!is_null($value = $this->get($key))) {
return $value;
}

$this->put($key, $value = $callback());

return $value;
}
}
11 changes: 11 additions & 0 deletions tests/Session/SessionStoreTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,17 @@ public function testKeyExists()
$this->assertFalse($session->exists(['foo', 'baz', 'bogus']));
}

public function testRememberMethodCallsPutAndReturnsDefault()
{
$session = $this->getSession();
$session->getHandler()->shouldReceive('get')->andReturn(null);
$result = $session->remember('foo', function () {
return 'bar';
});
$this->assertEquals('bar', $session->get('foo'));
$this->assertEquals('bar', $result);
}

public function getSession()
{
$reflection = new ReflectionClass('Illuminate\Session\Store');
Expand Down

0 comments on commit 3436c85

Please sign in to comment.