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: * @param mixed
71: * @param mixed
72: * @return void
73: */
74: public function offsetSet($key, $value)
75: {
76: if (!is_scalar($key)) { // prevents NULL
77: throw new InvalidArgumentException("Key must be either a string or an integer, " . gettype($key) ." given.");
78: }
79: $this->$key = $value;
80: }
81:
82:
83:
84: /**
85: * Returns a item.
86: * @param mixed
87: * @return mixed
88: */
89: public function offsetGet($key)
90: {
91: return $this->$key;
92: }
93:
94:
95:
96: /**
97: * Determines whether a item exists.
98: * @param mixed
99: * @return bool
100: */
101: public function offsetExists($key)
102: {
103: return isset($this->$key);
104: }
105:
106:
107:
108: /**
109: * Removes the element from this list.
110: * @param mixed
111: * @return void
112: */
113: public function offsetUnset($key)
114: {
115: unset($this->$key);
116: }
117:
118: }
119: