1: <?php
2:
3: namespace InfoContact\IcFwk\Library;
4:
5: 6: 7: 8: 9:
10: class Collection implements \IteratorAggregate, \ArrayAccess {
11:
12:
13: private $items;
14:
15: 16: 17: 18:
19: public function __construct(array $items) {
20: $this->items = $items;
21: }
22:
23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35:
36: public function get($key) {
37: $index = explode(".", $key);
38: return $this->getValue($index, $this->items);
39: }
40:
41: 42: 43: 44: 45: 46:
47: private function getValue(array $indexes, $value) {
48: $key = array_shift($indexes);
49: if(empty($indexes)) {
50: if(!array_key_exists($key, $value)) {
51: return NULL;
52: }
53: $result = $value[$key];
54: if(is_array($result)) {
55: return new \InfoContact\IcFwk\Library\Collection($result);
56: }
57: return $result;
58: }
59: return $this->getValue($indexes, $value[$key]);
60: }
61:
62: 63: 64: 65: 66:
67: public function set($key, $value) {
68: $this->items[$key] = $value;
69: }
70:
71: 72: 73: 74: 75:
76: public function has($key) {
77: return array_key_exists($key, $this->items);
78: }
79:
80: 81: 82: 83: 84: 85:
86: public function lists($key, $value) {
87: $results = [];
88: foreach ($this->items as $item) {
89: $results[$item[$key]] = $item[$value];
90: }
91: return new \InfoContact\IcFwk\Library\Collection($results);
92: }
93:
94: 95: 96: 97: 98:
99: public function extract($key) {
100: $results = [];
101: foreach ($this->items as $item) {
102: $results[] = $item[$key];
103: }
104: return new \InfoContact\IcFwk\Library\Collection($results);
105: }
106:
107: 108: 109: 110: 111:
112: public function join($glue) {
113: return implode($glue, $this->items);
114: }
115:
116: 117: 118: 119: 120:
121: public function max($key = false) {
122: if($key) {
123: return $this->extract($key)->max();
124: }
125: return max($this->items);
126: }
127:
128: 129: 130: 131: 132:
133: public function offsetExists($offset) {
134: return $this->has($offset);
135: }
136:
137: 138: 139: 140: 141:
142: public function offsetGet($offset) {
143: return $this->get($offset);
144: }
145:
146: 147: 148: 149: 150:
151: public function offsetSet($offset, $value) {
152: $this->set($offset, $value);
153: }
154:
155: 156: 157: 158:
159: public function offsetUnset($offset) {
160: if($this->has($offset)) {
161: unset($this->items[$offset]);
162: }
163: }
164:
165: 166: 167: 168:
169: public function getIterator() {
170: return new \ArrayIterator($this->items);
171: }
172:
173: }
174: