Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.3] Add remember helper to session store #16041

Merged
merged 1 commit into from
Oct 22, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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