FilesystemSessionStorage.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\SessionStorage;
  11. /**
  12. * FilesystemSessionStorage simulates sessions for functional tests.
  13. *
  14. * This storage does not start the session (session_start())
  15. * as it is not "available" when running tests on the command line.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class FilesystemSessionStorage extends NativeSessionStorage
  20. {
  21. private $path;
  22. private $data;
  23. private $started;
  24. public function __construct($path, array $options = array())
  25. {
  26. $this->path = $path;
  27. $this->started = false;
  28. parent::__construct($options);
  29. }
  30. public function start()
  31. {
  32. if ($this->started) {
  33. return;
  34. }
  35. session_set_cookie_params(
  36. $this->options['lifetime'],
  37. $this->options['path'],
  38. $this->options['domain'],
  39. $this->options['secure'],
  40. $this->options['httponly']
  41. );
  42. if (!ini_get('session.use_cookies') && isset($this->options['id']) && $this->options['id'] && $this->options['id'] != session_id()) {
  43. session_id($this->options['id']);
  44. }
  45. if (!session_id()) {
  46. session_id(hash('md5', uniqid(mt_rand(), true)));
  47. }
  48. $file = $this->path.'/'.session_id().'.session';
  49. $this->data = file_exists($file) ? unserialize(file_get_contents($file)) : array();
  50. $this->started = true;
  51. }
  52. public function getId()
  53. {
  54. if (!$this->started) {
  55. throw new \RuntimeException('The session must be started before reading its ID');
  56. }
  57. return session_id();
  58. }
  59. public function read($key, $default = null)
  60. {
  61. return array_key_exists($key, $this->data) ? $this->data[$key] : $default;
  62. }
  63. public function remove($key)
  64. {
  65. $retval = $this->data[$key];
  66. unset($this->data[$key]);
  67. return $retval;
  68. }
  69. public function write($key, $data)
  70. {
  71. $this->data[$key] = $data;
  72. if (!is_dir($this->path)) {
  73. mkdir($this->path, 0777, true);
  74. }
  75. file_put_contents($this->path.'/'.session_id().'.session', serialize($this->data));
  76. }
  77. public function regenerate($destroy = false)
  78. {
  79. if ($destroy) {
  80. $this->data = array();
  81. }
  82. return true;
  83. }
  84. }