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