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
30 * @param string $savePath Path of directory to save session files
31 * @param string $name Session name
32 * @param MetadataBag $metaBag MetadataBag instance
34 public function __construct($savePath = null, $name = 'MOCKSESSID', MetadataBag $metaBag = null)
36 if (null === $savePath) {
37 $savePath = sys_get_temp_dir();
40 if (!is_dir($savePath) && !@mkdir($savePath, 0777, true) && !is_dir($savePath)) {
41 throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $savePath));
44 $this->savePath = $savePath;
46 parent::__construct($name, $metaBag);
52 public function start()
59 $this->id = $this->generateId();
64 $this->started = true;
72 public function regenerate($destroy = false, $lifetime = null)
74 if (!$this->started) {
82 return parent::regenerate($destroy, $lifetime);
88 public function save()
90 if (!$this->started) {
91 throw new \RuntimeException('Trying to save a session that was not started yet or was already closed');
96 foreach ($this->bags as $bag) {
97 if (empty($data[$key = $bag->getStorageKey()])) {
101 if (array($key = $this->metadataBag->getStorageKey()) === array_keys($data)) {
107 file_put_contents($this->getFilePath(), serialize($data));
115 // this is needed for Silex, where the session object is re-used across requests
116 // in functional tests. In Symfony, the container is rebooted, so we don't have
118 $this->started = false;
122 * Deletes a session from persistent storage.
123 * Deliberately leaves session data in memory intact.
125 private function destroy()
127 if (is_file($this->getFilePath())) {
128 unlink($this->getFilePath());
133 * Calculate path to file.
135 * @return string File path
137 private function getFilePath()
139 return $this->savePath.'/'.$this->id.'.mocksess';
143 * Reads session from storage and loads session.
145 private function read()
147 $filePath = $this->getFilePath();
148 $this->data = is_readable($filePath) && is_file($filePath) ? unserialize(file_get_contents($filePath)) : array();
150 $this->loadSession();