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