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