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\Attribute;
15 * This class provides structured storage of session attributes using
16 * a name spacing character in the key.
18 * @author Drak <drak@zikula.org>
20 class NamespacedAttributeBag extends AttributeBag
22 private $namespaceCharacter;
25 * @param string $storageKey Session storage key
26 * @param string $namespaceCharacter Namespace character to use in keys
28 public function __construct($storageKey = '_sf2_attributes', $namespaceCharacter = '/')
30 $this->namespaceCharacter = $namespaceCharacter;
31 parent::__construct($storageKey);
37 public function has($name)
39 // reference mismatch: if fixed, re-introduced in array_key_exists; keep as it is
40 $attributes = $this->resolveAttributePath($name);
41 $name = $this->resolveKey($name);
43 if (null === $attributes) {
47 return array_key_exists($name, $attributes);
53 public function get($name, $default = null)
55 // reference mismatch: if fixed, re-introduced in array_key_exists; keep as it is
56 $attributes = $this->resolveAttributePath($name);
57 $name = $this->resolveKey($name);
59 if (null === $attributes) {
63 return array_key_exists($name, $attributes) ? $attributes[$name] : $default;
69 public function set($name, $value)
71 $attributes = &$this->resolveAttributePath($name, true);
72 $name = $this->resolveKey($name);
73 $attributes[$name] = $value;
79 public function remove($name)
82 $attributes = &$this->resolveAttributePath($name);
83 $name = $this->resolveKey($name);
84 if (null !== $attributes && array_key_exists($name, $attributes)) {
85 $retval = $attributes[$name];
86 unset($attributes[$name]);
93 * Resolves a path in attributes property and returns it as a reference.
95 * This method allows structured namespacing of session attributes.
97 * @param string $name Key name
98 * @param bool $writeContext Write context, default false
102 protected function &resolveAttributePath($name, $writeContext = false)
104 $array = &$this->attributes;
105 $name = (0 === strpos($name, $this->namespaceCharacter)) ? substr($name, 1) : $name;
107 // Check if there is anything to do, else return
112 $parts = explode($this->namespaceCharacter, $name);
113 if (count($parts) < 2) {
114 if (!$writeContext) {
118 $array[$parts[0]] = array();
123 unset($parts[count($parts) - 1]);
125 foreach ($parts as $part) {
126 if (null !== $array && !array_key_exists($part, $array)) {
127 $array[$part] = $writeContext ? array() : null;
130 $array = &$array[$part];
137 * Resolves the key from the name.
139 * This is the last part in a dot separated string.
141 * @param string $name
145 protected function resolveKey($name)
147 if (false !== $pos = strrpos($name, $this->namespaceCharacter)) {
148 $name = substr($name, $pos + 1);