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: */
11:
12: namespace Nette;
13:
14: use Nette;
15:
16:
17:
18: /**
19: * Provides objects to work as array.
20: *
21: * @author David Grudl
22: */
23: class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate
24: {
25:
26: /**
27: * @param array to wrap
28: * @param bool
29: * @return ArrayHash
30: */
31: public static function from($arr, $recursive = TRUE)
32: {
33: $obj = new static;
34: foreach ($arr as $key => $value) {
35: if ($recursive && is_array($value)) {
36: $obj->$key = static::from($value, TRUE);
37: } else {
38: $obj->$key = $value;
39: }
40: }
41: return $obj;
42: }
43:
44:
45:
46: /**
47: * Returns an iterator over all items.
48: * @return \RecursiveArrayIterator
49: */
50: public function getIterator()
51: {
52: return new \RecursiveArrayIterator($this);
53: }
54:
55:
56:
57: /**
58: * Returns items count.
59: * @return int
60: */
61: public function count()
62: {
63: return count((array) $this);
64: }
65:
66:
67:
68: /**
69: * Replaces or appends a item.
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: * @return mixed
85: */
86: public function offsetGet($key)
87: {
88: return $this->$key;
89: }
90:
91:
92:
93: /**
94: * Determines whether a item exists.
95: * @return bool
96: */
97: public function offsetExists($key)
98: {
99: return isset($this->$key);
100: }
101:
102:
103:
104: /**
105: * Removes the element from this list.
106: * @return void
107: */
108: public function offsetUnset($key)
109: {
110: unset($this->$key);
111: }
112:
113: }
114: