From da706aaf43ef3ccfa465b57c2db9e986bc2cc595 Mon Sep 17 00:00:00 2001 From: ADmad Date: Thu, 28 May 2015 23:07:11 +0530 Subject: [PATCH] Avoid hitting session each time --- src/Auth/Storage/SessionStorage.php | 20 ++++++++++++---- .../Auth/Storage/SessionStorageTest.php | 23 ++++++++++++++----- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/src/Auth/Storage/SessionStorage.php b/src/Auth/Storage/SessionStorage.php index 245c23ca1c3..03fd5ba58d5 100644 --- a/src/Auth/Storage/SessionStorage.php +++ b/src/Auth/Storage/SessionStorage.php @@ -25,6 +25,13 @@ class SessionStorage implements StorageInterface use InstanceConfigTrait; + /** + * User record. + * + * @var array + */ + protected $_user; + /** * Session object. * @@ -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; } /** @@ -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); } @@ -90,6 +100,8 @@ public function set(array $user) */ public function remove() { + unset($this->_user); + $this->_session->delete($this->_config['key']); $this->_session->renew(); } diff --git a/tests/TestCase/Auth/Storage/SessionStorageTest.php b/tests/TestCase/Auth/Storage/SessionStorageTest.php index 66b5279a5d1..e90b50f75ba 100644 --- a/tests/TestCase/Auth/Storage/SessionStorageTest.php +++ b/tests/TestCase/Auth/Storage/SessionStorageTest.php @@ -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; @@ -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') @@ -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 *