1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (http://nette.org)
5: *
6: * Copyright (c) 2004, 2011 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: /**
19: * Provides objects to work as array.
20: *
21: * @author David Grudl
22: */
23: class ArrayHash implements \ArrayAccess, \Countable, \IteratorAggregate
24: {
25:
26: /**
27: * @param array to wrap
28: * @return ArrayHash
29: */
30: public static function from($arr)
31: {
32: $obj = new static;
33: foreach ($arr as $key => $value) {
34: $obj->$key = $value;
35: }
36: return $obj;
37: }
38:
39:
40:
41: /**
42: * Returns an iterator over all items.
43: * @return \ArrayIterator
44: */
45: public function getIterator()
46: {
47: return new \ArrayIterator($this);
48: }
49:
50:
51:
52: /**
53: * Returns items count.
54: * @return int
55: */
56: public function count()
57: {
58: return count((array) $this);
59: }
60:
61:
62:
63: /**
64: * Replaces or appends a item.
65: * @param mixed
66: * @param mixed
67: * @return void
68: */
69: public function offsetSet($key, $value)
70: {
71: if (!is_scalar($key)) { // prevents NULL
72: throw new \InvalidArgumentException("Key must be either a string or an integer, " . gettype($key) ." given.");
73: }
74: $this->$key = $value;
75: }
76:
77:
78:
79: /**
80: * Returns a item.
81: * @param mixed
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: * @param mixed
94: * @return bool
95: */
96: public function offsetExists($key)
97: {
98: return isset($this->$key);
99: }
100:
101:
102:
103: /**
104: * Removes the element from this list.
105: * @param mixed
106: * @return void
107: */
108: public function offsetUnset($key)
109: {
110: unset($this->$key);
111: }
112:
113: }
114: