1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (http://nette.org)
5: *
6: * Copyright (c) 2004 David Grudl (http://davidgrudl.com)
7: *
8: * For the full copyright and license information, please view
9: * the file license.txt that was distributed with this source code.
10: * @package Nette
11: */
12:
13:
14:
15: /**
16: * Provides objects to work as array.
17: *
18: * @author David Grudl
19: * @package Nette
20: */
21: class NArrayHash extends stdClass implements ArrayAccess, Countable, IteratorAggregate
22: {
23:
24: /**
25: * @param array to wrap
26: * @param bool
27: * @return NArrayHash
28: */
29: public static function from($arr, $recursive = TRUE)
30: {
31: $obj = new self;
32: foreach ($arr as $key => $value) {
33: if ($recursive && is_array($value)) {
34: $obj->$key = self::from($value, TRUE);
35: } else {
36: $obj->$key = $value;
37: }
38: }
39: return $obj;
40: }
41:
42:
43:
44: /**
45: * Returns an iterator over all items.
46: * @return RecursiveArrayIterator
47: */
48: public function getIterator()
49: {
50: return new RecursiveArrayIterator($this);
51: }
52:
53:
54:
55: /**
56: * Returns items count.
57: * @return int
58: */
59: public function count()
60: {
61: return count((array) $this);
62: }
63:
64:
65:
66: /**
67: * Replaces or appends a item.
68: * @param mixed
69: * @param mixed
70: * @return void
71: */
72: public function offsetSet($key, $value)
73: {
74: if (!is_scalar($key)) { // prevents NULL
75: throw new InvalidArgumentException("Key must be either a string or an integer, " . gettype($key) ." given.");
76: }
77: $this->$key = $value;
78: }
79:
80:
81:
82: /**
83: * Returns a item.
84: * @param mixed
85: * @return mixed
86: */
87: public function offsetGet($key)
88: {
89: return $this->$key;
90: }
91:
92:
93:
94: /**
95: * Determines whether a item exists.
96: * @param mixed
97: * @return bool
98: */
99: public function offsetExists($key)
100: {
101: return isset($this->$key);
102: }
103:
104:
105:
106: /**
107: * Removes the element from this list.
108: * @param mixed
109: * @return void
110: */
111: public function offsetUnset($key)
112: {
113: unset($this->$key);
114: }
115:
116: }
117: