Skip to content

Commit

Permalink
Avoid hitting session each time
Browse files Browse the repository at this point in the history
  • Loading branch information
ADmad committed May 28, 2015
1 parent 5abc4ed commit da706aa
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
20 changes: 16 additions & 4 deletions src/Auth/Storage/SessionStorage.php
Expand Up @@ -25,6 +25,13 @@ class SessionStorage implements StorageInterface

use InstanceConfigTrait;

/**
* User record.
*
* @var array
*/
protected $_user;

/**
* Session object.
*
Expand Down Expand Up @@ -56,15 +63,16 @@ public function __construct(Request $request, array $config = [])
/**
* Get user record from session.
*
* @return array|null
* @return array|null User record if available else null.
*/
public function get()
{
if (!$this->_session->check($this->_config['key'])) {
return;
if ($this->_user) {
return $this->_user;
}

return $this->_session->read($this->_config['key']);
$this->_user = $this->_session->read($this->_config['key']);
return $this->_user;
}

/**
Expand All @@ -77,6 +85,8 @@ public function get()
*/
public function set(array $user)
{
$this->_user = $user;

$this->_session->renew();
$this->_session->write($this->_config['key'], $user);
}
Expand All @@ -90,6 +100,8 @@ public function set(array $user)
*/
public function remove()
{
unset($this->_user);

$this->_session->delete($this->_config['key']);
$this->_session->renew();
}
Expand Down
23 changes: 17 additions & 6 deletions tests/TestCase/Auth/Storage/SessionStorageTest.php
Expand Up @@ -9,7 +9,7 @@
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 2.0.0
* @since 3.1.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Test\TestCase\Auth;
Expand Down Expand Up @@ -62,11 +62,6 @@ public function testSet()
*/
public function testGet()
{
$this->session->expects($this->once())
->method('check')
->with('Auth.AuthUser')
->will($this->returnValue(true));

$this->session->expects($this->once())
->method('read')
->with('Auth.AuthUser')
Expand All @@ -76,6 +71,22 @@ public function testGet()
$this->assertSame($this->user, $result);
}

/**
* Test get from local var
*
* @return void
*/
public function testGetFromLocalVar()
{
$this->storage->set($this->user);

$this->session->expects($this->never())
->method('read');

$result = $this->storage->get();
$this->assertSame($this->user, $result);
}

/**
* Test remove
*
Expand Down

0 comments on commit da706aa

Please sign in to comment.