Skip to content

[HttpFoundation] add a handler to store sessions in a PSR-6 cache #19193

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

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;

use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException;

/**
* Stores PHP sessions in a {@see CacheItemPoolInterface PSR-6 cache item pool}.
*
* @author Christian Flothmann <christian.flothmann@xabbuh.de>
*/
class CachePoolSessionHandler implements \SessionHandlerInterface
{
private $cachePool;
private $expiresAfter;

/**
* Creates a session handler that wraps a cache item pool using the given options.
*
* Available options are:
* * expires_after: The maximum lifetime of a session in seconds
*
* @param CacheItemPoolInterface $cachePool
* @param array $options
*/
public function __construct(CacheItemPoolInterface $cachePool, array $options = array())
{
if (count($diff = array_diff(array_keys($options), array('expires_after'))) > 0) {
throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode('", "', $diff)));
}

$this->cachePool = $cachePool;
$this->expiresAfter = isset($options['expires_after']) ? (int) $options['expires_after'] : (int) ini_get('session.gc_maxlifetime');
}

/**
* {@inheritdoc}
*/
public function open($savePath, $sessionId)
{
try {
$this->cachePool->getItem($sessionId);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure if this is necessary. this mean every session reads the cache twice

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's debatable. I am not sure either. The thing is that read() cannot indicate that it failed. Another possible solution is to keep the read cache item in memory here and thus be able to avoid the second call to getItem() in read().

Copy link
Contributor

@Tobion Tobion Jun 27, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean it can only fail for invalid session id chars. And since there is no fallback solution like encoding chars, I don't see the point of indicating failure. So it would be the same as non-existing session.


return true;
} catch (InvalidArgumentException $e) {
return false;
}
}

/**
* {@inheritdoc}
*/
public function close()
{
// there is nothing like a close operation for PSR-6 cache pools
return true;
}

/**
* {@inheritdoc}
*/
public function read($sessionId)
{
try {
$item = $this->cachePool->getItem($sessionId);

return $item->isHit() ? $item->get() : '';
} catch (InvalidArgumentException $e) {
return '';
}
}

/**
* {@inheritdoc}
*/
public function write($sessionId, $sessionData)
{
try {
$item = $this->cachePool->getItem($sessionId);
$item->set($sessionData);
$item->expiresAfter($this->expiresAfter);

return $this->cachePool->save($item);
} catch (InvalidArgumentException $e) {
return false;
}
}

/**
* {@inheritdoc}
*/
public function destroy($sessionId)
{
try {
return $this->cachePool->deleteItem($sessionId);
} catch (InvalidArgumentException $e) {
return false;
}
}

/**
* {@inheritdoc}
*/
public function gc($maxLifetime)
{
// cache pools must implement garbage collection on their own
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;

use Psr\Cache\CacheItemInterface;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Cache\InvalidArgumentException as BaseInvalidArgumentException;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\CachePoolSessionHandler;

class CachePoolSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $cachePool;

/**
* @var CachePoolSessionHandler
*/
private $sessionHandler;

protected function setUp()
{
$this->cachePool = $this->getMock(CacheItemPoolInterface::class);
$this->sessionHandler = new CachePoolSessionHandler($this->cachePool, array());
}

public function testOpenSucceeds()
{
$this->assertTrue($this->sessionHandler->open('save-path', 'id'));
}

public function testOpenReturnsFalseIfTheCacheItemCannotBeRead()
{
$this->cachePoolThrowsException('getItem');

$this->assertFalse($this->sessionHandler->open('save-path', 'id'));
}

public function testClose()
{
$this->assertTrue($this->sessionHandler->close());
}

public function testReadReturnsCachedDataOnSuccess()
{
$this->cachePoolReturnsItemWithHit();

$this->assertSame('data', $this->sessionHandler->read('id'));
}

public function testReadReturnsEmptyStringIfNoCacheItemWasFound()
{
$this->cachePoolReturnsItemWithoutHit();

$this->assertSame('', $this->sessionHandler->read('id'));
}

public function testReadReturnsEmptyStringIfTheCacheItemCannotBeRead()
{
$this->cachePoolThrowsException('getItem');

$this->assertSame('', $this->sessionHandler->read('id'));
}

public function testWriteReturnsTrueWhenTheCacheItemCouldBeSaved()
{
$this->cachePoolReturnsItemWithHit();
$this
->cachePool
->expects($this->once())
->method('save')
->willReturn(true)
;

$this->assertTrue($this->sessionHandler->write('id', 'data'));
}

public function testWriteReturnsFalseWhenTheCacheItemCouldNotBeSaved()
{
$this->cachePoolReturnsItemWithHit();
$this
->cachePool
->expects($this->once())
->method('save')
->willReturn(false)
;

$this->assertFalse($this->sessionHandler->write('id', 'data'));
}

public function testWriteReturnsFalseWhenTheCachePoolThrowsAnException()
{
$this->cachePoolThrowsException('getItem');

$this->assertFalse($this->sessionHandler->write('id', 'data'));
}

public function testWriteRespectsCustomMaxLifetime()
{
$this->sessionHandler = new CachePoolSessionHandler($this->cachePool, array('expires_after' => 86400));
$item = $this->cachePoolReturnsItemWithHit();
$item
->expects($this->atLeastOnce())
->method('expiresAfter')
->with(86400)
;
$this
->cachePool
->expects($this->once())
->method('save')
->willReturn(true)
;

$this->assertTrue($this->sessionHandler->write('id', 'data'));
}

public function testDestroyReturnsTrueWhenTheCacheItemWasRemoved()
{
$this
->cachePool
->expects($this->once())
->method('deleteItem')
->willReturn(true)
;

$this->assertTrue($this->sessionHandler->destroy('id'));
}

public function testDestroyReturnsFalseWhenTheCacheItemWasNotRemoved()
{
$this
->cachePool
->expects($this->once())
->method('deleteItem')
->willReturn(false)
;

$this->assertFalse($this->sessionHandler->destroy('id'));
}

public function testDestroyReturnsFalseWhenTheCachePoolThrowsAnException()
{
$this->cachePoolThrowsException('deleteItem');

$this->assertFalse($this->sessionHandler->destroy('id'));
}

public function testGcSucceeds()
{
$this->assertTrue($this->sessionHandler->gc(1000));
}

/**
* @dataProvider getOptionFixtures
*/
public function testSupportedOptions($options, $supported)
{
try {
new CachePoolSessionHandler($this->cachePool, $options);

$this->assertTrue($supported);
} catch (\InvalidArgumentException $e) {
$this->assertFalse($supported);
}
}

public function getOptionFixtures()
{
return array(
array(array('prefix' => 'session'), false),
array(array('expires_after' => 100), true),
array(array('expires_after' => 100, 'foo' => 'bar'), false),
);
}

private function cachePoolReturnsItemWithHit()
{
$item = $this->getMock(CacheItemInterface::class);
$item
->expects($this->any())
->method('isHit')
->willReturn(true)
;
$item
->expects($this->any())
->method('get')
->willReturn('data')
;
$this
->cachePool
->expects($this->any())
->method('getItem')
->with('id')
->willReturn($item)
;

return $item;
}

private function cachePoolReturnsItemWithoutHit()
{
$item = $this->getMock(CacheItemInterface::class);
$item
->expects($this->any())
->method('isHit')
->willReturn(false)
;
$this
->cachePool
->expects($this->any())
->method('getItem')
->with('id')
->willReturn($item)
;
}

private function cachePoolThrowsException($method)
{
$this
->cachePool
->expects($this->any())
->method($method)
->willThrowException($this->getMock(InvalidArgumentException::class))
;
}
}

class InvalidArgumentException extends \Exception implements BaseInvalidArgumentException
{
}
1 change: 1 addition & 0 deletions src/Symfony/Component/HttpFoundation/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"symfony/polyfill-mbstring": "~1.1"
},
"require-dev": {
"psr/cache": "~1.0",
"symfony/expression-language": "~2.8|~3.0"
},
"autoload": {
Expand Down