Completed
Push — develop ( 64da83...d844ac )
by Mathieu
01:46
created

Collection::offsetGet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Suricate;
3
4
class Collection implements \IteratorAggregate, \Countable, \ArrayAccess, Interfaces\ICollection
5
{
6
    protected $items   = [];
7
    public $pagination = [
8
        'nbPages'   => 0,
9
        'page'      => 1,
10
        'nbItems'   => 0,
11
    ];
12
13 29
    public function __construct($items = [])
14
    {
15 29
        $this->items = $items;
16 29
    }
17
18 1
    public function paginate($nbItemPerPage, $currentPage = 1)
19
    {
20 1
        $this->pagination['page']       = $currentPage;
21 1
        $this->pagination['nbItems']    = count($this->items);
22 1
        $this->pagination['nbPages']    = ceil($this->pagination['nbItems'] / $nbItemPerPage);
23
24 1
        $this->items = array_slice($this->items, ($currentPage - 1) * $nbItemPerPage, $nbItemPerPage);
25
26 1
        return $this;
27
    }
28
29
    public function getPossibleValuesFor($args, $key = null)
30
    {
31
        if (!is_array($args)) {
32
            $args = [
33
                'format' => '%s',
34
                'data' => [$args]
35
            ];
36
        }
37
38
        $values = [];
39
        foreach ($this->items as $item) {
40
            $itemValues = [];
41
            foreach ($args['data'] as $arg) {
42
                $itemValues[] = dataGet($item, $arg);
43
            }
44
            $arrayKey = ($key !== null) ? dataGet($item, $key) : null;
45
            $values[$arrayKey] = vsprintf($args['format'], $itemValues);
46
        }
47
48
        return $values;
49
    }
50
51 1
    public function getValuesFor($name)
52
    {
53 1
        $values = [];
54 1
        foreach ($this->items as $item) {
55 1
            $values[] = dataGet($item, $name);
56
        }
57
58 1
        return $values;
59
    }
60
61 12
    public function getItems()
62
    {
63 12
        return $this->items;
64
    }
65
66
    /*
67
68
    
69
70
    public function getItemFromKey($key)
71
    {
72
        $invertedMapping = array_flip($this->mapping);
73
        if (isset($invertedMapping[$key])) {
74
            return $this->items[$invertedMapping[$key]];
75
        }
76
    }
77
*/
78
    /**
79
     * Implementation of countable interface
80
     *
81
     * @return int
82
     */
83 1
    public function count(): int
84
    {
85 1
        return count($this->items);
86
    }
87
88
    /**
89
     * Implementation of IteratorAggregate Interface
90
     *
91
     * @return \ArrayIterator
92
     */
93 1
    public function getIterator(): \ArrayIterator
94
    {
95 1
        return new \ArrayIterator($this->items);
96
    }
97
98
    /**
99
     * Implementation of ArrayAccess interface
100
     *
101
     * @param  mixed $offset Offset to verify
102
     * @return bool
103
     */
104 2
    public function offsetExists($offset): bool
105
    {
106 2
        return \array_key_exists($offset, $this->items);
107
    }
108
109
    /**
110
     * Implementation of ArrayAccess Interface
111
     *
112
     * @param  mixed $offset Offset to get
113
     * @return mixed
114
     */
115 1
    public function offsetGet($offset)
116
    {
117 1
        if (array_key_exists($offset, $this->items)) {
118 1
            return $this->items[$offset];
119
        }
120 1
        return null;
121
        /*
122
        $item = isset($this->items[$offset]) ? $this->items[$offset] : null;
123
        if (gettype($item) == 'object' || $item == null) {
124
            return $item;
125
        }
126
       // Lazy load
127
        $itemType = $this::ITEM_TYPE;
128
        $itemToLoad = new $itemType;
129
        $itemToLoad->load($this->items[$offset]);
130
131
        $this->items[$offset] = $itemToLoad;
132
133
        return $this->items[$offset];*/
134
    }
135
136
    /**
137
     * Implementation of ArrayAccess Interface
138
     *
139
     * @param mixed $offset Offset to set
140
     * @param mixed $value  Value to set
141
     * @return void
142
     */
143
    public function offsetSet($offset, $value): void
144
    {
145
        if (is_null($offset)) {
146
            $this->items[] = $value;
147
        } else {
148
            $this->items[$offset] = $value;
149
        }
150
    }
151
152
    /**
153
     * Implementation of ArrayAccess Interface
154
     *
155
     * @param mixed $offset Offset to unset
156
     * @return void
157
     */
158
    public function offsetUnset($offset): void
159
    {
160
        unset($this->items[$offset]);
161
    }
162
163
    // Helpers
164
165
    /**
166
     * Get first item of the collection
167
     *
168
     * @return mixed
169
     */
170 1
    public function first()
171
    {
172 1
        foreach ($this->items as $currentItem) {
173 1
            return $currentItem;
174
        }
175 1
    }
176
177
    /**
178
     * Get last item of the collection
179
     *
180
     * @return mixed
181
     */
182 1
    public function last()
183
    {
184 1
        if (count($this->items)) {
185 1
            return end($this->items);
186
        }
187
        
188 1
        return null;
189
    }
190
191
    /**
192
     * Check if collection is empty
193
     *
194
     * @return bool
195
     */
196 1
    public function isEmpty(): bool
197
    {
198 1
        return empty($this->items);
199
    }
200
201
    /**
202
     * Return the sum of the collection
203
     *
204
     * @param mixed $field Field to use for sum
205
     * @return double|integer
206
     */
207 1
    public function sum($field = null)
208
    {
209 1
        if ($field === null) {
210 1
            return array_sum($this->items);
211
        }
212 1
        $result = 0;
213 1
        foreach ($this->items as $item) {
214 1
            $result += dataGet($item, $field);
215
        }
216 1
        return $result;
217
    }
218
219
    public function random($nbItems = 1)
220
    {
221
        if ($this->isEmpty()) {
222
            return null;
223
        }
224
225
        $keys = array_rand($this->items, $nbItems);
226
227
        if (is_array($keys)) {
228
            return array_intersect_key($this->items, array_flip($keys));
229
        }
230
        
231
        return $this->items[$keys];
232
    }
233
234
    public function shuffle()
235
    {
236
        shuffle($this->items);
237
238
        return $this;
239
    }
240
241 1
    public function unique()
242
    {
243 1
        return new static(array_unique($this->items));
244
    }
245
246
    /**
247
     * Apply a closure to each element of the collection
248
     *
249
     * @param \Closure $callback Closure to apply
250
     * @return Collection
251
     */
252
    public function each(\Closure $callback): Collection
253
    {
254
        array_map($callback, $this->items);
255
        return $this;
256
    }
257
258
    /**
259
     * Sort a collection using a closure
260
     *
261
     * @param \Closure $closure Closure to apply for sorting, similar to uasort() closure
262
     * @return Collection
263
     */
264
    public function sort(\Closure $closure): Collection
265
    {
266
        uasort($this->items, $closure);
267
268
        return $this;
269
    }
270
271
    public function sortBy($field, $reverse = false)
272
    {
273
        if ($reverse) {
274
            $sortFunction = function ($a, $b) use ($field) {
275
                $first = dataGet($a, $field);
276
                $second = dataGet($b, $field);
277
                if ($first == $second) {
278
                    return 0;
279
                }
280
                return ($first > $second) ? -1 : 1;
281
            };
282
        } else {
283
            $sortFunction = function ($a, $b) use ($field) {
284
                $first = dataGet($a, $field);
285
                $second = dataGet($b, $field);
286
                if ($first == $second) {
287
                    return 0;
288
                }
289
                return ($first < $second) ? -1 : 1;
290
            };
291
        }
292
293
294
        usort($this->items, $sortFunction);
295
296
        return $this;
297
    }
298
299 1
    public function filter(\Closure $closure)
300
    {
301 1
        return new static(array_filter($this->items, $closure));
302
    }
303
304 1
    public function search($value, $strict = false)
305
    {
306 1
        return array_search($value, $this->items, $strict);
307
    }
308
309 1
    public function has($key)
310
    {
311 1
        return $this->offsetExists($key);
312
    }
313
314 1
    public function keys()
315
    {
316 1
        return array_keys($this->items);
317
    }
318
319 1
    public function prepend($item)
320
    {
321 1
        array_unshift($this->items, $item);
322
323 1
        return $this;
324
    }
325
326 1
    public function push($item)
327
    {
328 1
        $this->items[] = $item;
329
330 1
        return $this;
331
    }
332
333 1
    public function put($key, $val)
334
    {
335 1
        $this->items[$key] = $val;
336
337 1
        return $this;
338
    }
339 1
    public function shift()
340
    {
341 1
        return array_shift($this->items);
342
    }
343
    
344 1
    public function pop()
345
    {
346 1
        return array_pop($this->items);
347
    }
348
349 1
    public function reverse()
350
    {
351 1
        return new static(array_reverse($this->items));
352
    }
353
354 1
    public function reduce(callable $callback, $initial = null)
355
    {
356 1
        return array_reduce($this->items, $callback, $initial);
357
    }
358
359 2
    public function slice($offset, $length = null, $preserveKeys = false)
360
    {
361 2
        return new static(array_slice($this->items, $offset, $length, $preserveKeys));
362
    }
363
364 1
    public function take($limit = null)
365
    {
366 1
        if ($limit < 0) {
367
            return $this->slice(abs($limit), $limit);
368
        }
369
370 1
        return $this->slice(0, $limit);
371
    }
372
373
    public function splice($offset, $length = null, $replacement = [])
374
    {
375
        return new static(array_splice($this->items, $offset, $length, $replacement));
376
    }
377
378
    public function chunk($size, $preserveKeys = false)
379
    {
380
        $result = new static;
381
        foreach (array_chunk($this->items, $size, $preserveKeys) as $chunk) {
382
            $result->push(new static($chunk));
383
        }
384
        return $result;
385
    }
386
}
387