4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation\Session\Storage;
15 * MockFileSessionStorage is used to mock sessions for
16 * functional testing when done in a single PHP process.
18 * No PHP session is actually started since a session can be initialized
19 * and shutdown only once per PHP execution cycle and this class does
20 * not pollute any session related globals, including session_*() functions
21 * or session.* PHP ini directives.
23 * @author Drak <drak@zikula.org>
25 class MockFileSessionStorage extends MockArraySessionStorage
35 * @param string $savePath Path of directory to save session files
36 * @param string $name Session name
37 * @param MetadataBag $metaBag MetadataBag instance
39 public function __construct($savePath = null, $name = 'MOCKSESSID', MetadataBag $metaBag = null)
41 if (null === $savePath) {
42 $savePath = sys_get_temp_dir();
45 if (!is_dir($savePath) && !@mkdir($savePath, 0777, true) && !is_dir($savePath)) {
46 throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $savePath));
49 $this->savePath = $savePath;
51 parent::__construct($name, $metaBag);
57 public function start()
64 $this->id = $this->generateId();
69 $this->started = true;
77 public function regenerate($destroy = false, $lifetime = null)
79 if (!$this->started) {
87 return parent::regenerate($destroy, $lifetime);
93 public function save()
95 if (!$this->started) {
96 throw new \RuntimeException('Trying to save a session that was not started yet or was already closed');
99 file_put_contents($this->getFilePath(), serialize($this->data));
101 // this is needed for Silex, where the session object is re-used across requests
102 // in functional tests. In Symfony, the container is rebooted, so we don't have
104 $this->started = false;
108 * Deletes a session from persistent storage.
109 * Deliberately leaves session data in memory intact.
111 private function destroy()
113 if (is_file($this->getFilePath())) {
114 unlink($this->getFilePath());
119 * Calculate path to file.
121 * @return string File path
123 private function getFilePath()
125 return $this->savePath.'/'.$this->id.'.mocksess';
129 * Reads session from storage and loads session.
131 private function read()
133 $filePath = $this->getFilePath();
134 $this->data = is_readable($filePath) && is_file($filePath) ? unserialize(file_get_contents($filePath)) : array();
136 $this->loadSession();