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: * Provides objects to work as array.
19: *
20: * @author David Grudl
21: */
22: class ArrayHash extends \stdClass implements \ArrayAccess, \Countable, \IteratorAggregate
23: {
24:
25: /**
26: * @param array to wrap
27: * @param bool
28: * @return ArrayHash
29: */
30: public static function from($arr, $recursive = TRUE)
31: {
32: $obj = new static;
33: foreach ($arr as $key => $value) {
34: if ($recursive && is_array($value)) {
35: $obj->$key = static::from($value, TRUE);
36: } else {
37: $obj->$key = $value;
38: }
39: }
40: return $obj;
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: * Returns items count.
56: * @return int
57: */
58: public function count()
59: {
60: return count((array) $this);
61: }
62:
63:
64: /**
65: * Replaces or appends a item.
66: * @return void
67: */
68: public function offsetSet($key, $value)
69: {
70: if (!is_scalar($key)) { // prevents NULL
71: throw new InvalidArgumentException("Key must be either a string or an integer, " . gettype($key) ." given.");
72: }
73: $this->$key = $value;
74: }
75:
76:
77: /**
78: * Returns a item.
79: * @return mixed
80: */
81: public function offsetGet($key)
82: {
83: return $this->$key;
84: }
85:
86:
87: /**
88: * Determines whether a item exists.
89: * @return bool
90: */
91: public function offsetExists($key)
92: {
93: return isset($this->$key);
94: }
95:
96:
97: /**
98: * Removes the element from this list.
99: * @return void
100: */
101: public function offsetUnset($key)
102: {
103: unset($this->$key);
104: }
105:
106: }
107: