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