[HttpFoundation][Sessions] Add support for extended save_path for native files save handler

This commit is contained in:
Drak 2012-07-23 09:59:09 +01:00
parent c20c1d18dc
commit 9bf3cb4e97
2 changed files with 54 additions and 5 deletions

View File

@ -23,7 +23,13 @@ class NativeFileSessionHandler extends NativeSessionHandler
/**
* Constructor.
*
* @param string $savePath Path of directory to save session files. Default null will leave setting as defined by PHP.
* @param string $savePath Path of directory to save session files.
* Default null will leave setting as defined by PHP.
* '/path', 'N;/path', or 'N;octal-mode;/path
*
* @see http://php.net/session.configuration.php#ini.session.save-path for further details.
*
* @throws \InvalidArgumentException On invalid $savePath
*/
public function __construct($savePath = null)
{
@ -31,11 +37,23 @@ class NativeFileSessionHandler extends NativeSessionHandler
$savePath = ini_get('session.save_path');
}
if ($savePath && !is_dir($savePath)) {
mkdir($savePath, 0777, true);
$baseDir = $savePath;
if (strpos($baseDir, ';') !== false) {
$parts = explode(';', $baseDir);
if (count($parts) > 3) {
throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'', $savePath));
}
// characters after last ';' is the path
$baseDir = substr($baseDir, strrpos($baseDir, ';')+1, strlen($baseDir));
}
if ($baseDir && !is_dir($baseDir)) {
mkdir($baseDir, 0777, true);
}
ini_set('session.save_handler', 'files');
ini_set('session.save_path', $savePath);
ini_set('session.save_handler', 'files');
}
}

View File

@ -23,7 +23,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
*/
class NativeFileSessionHandlerTest extends \PHPUnit_Framework_TestCase
{
public function testConstruct()
public function test__Construct()
{
$storage = new NativeSessionStorage(array('name' => 'TESTING'), new NativeFileSessionHandler(sys_get_temp_dir()));
@ -39,6 +39,37 @@ class NativeFileSessionHandlerTest extends \PHPUnit_Framework_TestCase
$this->assertEquals('TESTING', ini_get('session.name'));
}
/**
* @dataProvider savePathDataProvider
*/
public function test__ConstructSavePath($savePath, $expectedSavePath, $path)
{
$handler = new NativeFileSessionHandler($savePath);
$this->assertEquals($expectedSavePath, ini_get('session.save_path'));
$dir = realpath('/'.$path);
$this->assertTrue(is_dir(realpath($dir)));
rmdir($dir);
}
public function savePathDataProvider()
{
$base = sys_get_temp_dir();
return array(
array("$base/foo", "$base/foo", "$base/foo"),
array("5;$base/foo", "5;$base/foo", "$base/foo"),
array("5;0600;$base/foo", "5;0600;$base/foo", "$base/foo"),
);
}
/**
* @expectedException \InvalidArgumentException
*/
public function test__ConstructException()
{
$handler = new NativeFileSessionHandler('something;invalid;with;too-many-args');
}
public function testConstructDefault()
{
$path = ini_get('session.save_path');