diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php index 31bf55c72dd99..90809bbc2629b 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/NativeSessionStorage.php @@ -264,6 +264,10 @@ public function clear() public function registerBag(SessionBagInterface $bag) { $this->bags[$bag->getName()] = $bag; + + if ($this->isStarted()) { + $this->loadSessionBag($bag); + } } /** @@ -422,12 +426,28 @@ protected function loadSession(array &$session = null) $bags = array_merge($this->bags, array($this->metadataBag)); foreach ($bags as $bag) { - $key = $bag->getStorageKey(); - $session[$key] = isset($session[$key]) ? $session[$key] : array(); - $bag->initialize($session[$key]); + $this->loadSessionBag($bag, $session); } $this->started = true; $this->closed = false; } + + /** + * Load and initialize the session for the given bag and pass the + * session variable into the bag. + * + * @param SessionBagInterface $bag + * @param array|null $session + */ + private function loadSessionBag(SessionBagInterface $bag, array &$session = null) + { + if (null === $session) { + $session = &$_SESSION; + } + + $key = $bag->getStorageKey(); + $session[$key] = isset($session[$key]) ? $session[$key] : array(); + $bag->initialize($session[$key]); + } } diff --git a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php index 4870115caa64c..42974c94a0f0b 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/Session/Storage/NativeSessionStorageTest.php @@ -254,4 +254,34 @@ public function testCanStartOutside54() $this->assertFalse(isset($_SESSION[$key])); $storage->start(); } + + public function testRegisterBagBeforeStarting() + { + $storage = $this->getStorage(); + $bag = new AttributeBag('test_bag'); + $bag->setName('test_bag'); + $storage->registerBag($bag); + + $storage->start(); + + // variable is set after session start, as the session handler overwrites $_SESSION + $_SESSION['test_bag']['some_key'] = 'some_value'; + + $this->assertSame('some_value', $bag->get('some_key')); + } + + public function testRegisterBagAfterStarting() + { + $storage = $this->getStorage(); + $storage->start(); + + // variable is set after session start, as the session handler overwrites $_SESSION + $_SESSION['test_bag']['some_key'] = 'some_value'; + + $bag = new AttributeBag('test_bag'); + $bag->setName('test_bag'); + $storage->registerBag($bag); + + $this->assertSame('some_value', $bag->get('some_key')); + } }