Completed
Push — master ( 3b667c...fb9863 )
by Owen
02:06
created

Collection::getAtIndex()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 8
rs 9.4285
cc 3
eloc 4
nc 3
nop 1
1
<?php
2
3
namespace Mundanity\Collection;
4
5
6
/**
7
 * Implements a basic collection from an array.
8
 *
9
 */
10
class Collection implements CollectionInterface
11
{
12
    /**
13
     * The data in the collection.
14
     *
15
     * @var array
16
     *
17
     */
18
    protected $data = [];
19
20
21
    /**
22
     * Constructor
23
     *
24
     * @param array $data
25
     *   An array of data to populate the collection with. Note that existing
26
     *   indexes are removed. If indexes are significant, use KeyedCollection
27
     *   instead.
28
     *
29
     */
30
    public function __construct(array $data = [])
31
    {
32
        $this->data = array_values($data);
33
    }
34
35
36
    /**
37
     * {@inheritdoc}
38
     *
39
     */
40
    public function has($item)
41
    {
42
        return in_array($item, $this->data);
43
    }
44
45
46
    /**
47
     * {@inheritdoc}
48
     *
49
     */
50
    public function getWhere(callable $callable)
51
    {
52
        foreach ($this->data as $item) {
53
            if ($callable($item) === true) {
54
                return is_object($item) ? clone $item : $item;
55
            }
56
        }
57
    }
58
59
60
    /**
61
     * {@inheritdoc}
62
     *
63
     */
64
    public function getAtIndex($index)
65
    {
66
        if (!is_numeric($index)) {
67
            return;
68
        }
69
70
        return isset($this->data[$index]) ? $this->data[$index] : null;
71
    }
72
73
74
    /**
75
     * {@inheritdoc}
76
     *
77
     */
78
    public function isEmpty()
79
    {
80
        return empty($this->data);
81
    }
82
83
84
    /**
85
     * Returns the number of items within the collection.
86
     *
87
     * @return int
88
     *
89
     */
90
    public function count()
91
    {
92
        return count($this->data);
93
    }
94
95
96
    /**
97
     * Returns an iterator.
98
     *
99
     * @return \Traversable
100
     *
101
     */
102
    public function getIterator()
103
    {
104
        return new \ArrayIterator($this->data);
105
    }
106
107
108
    /**
109
     * {@inheritdoc}
110
     *
111
     */
112
    public function toArray()
113
    {
114
        return $this->data;
115
    }
116
117
118
    /**
119
     * {@inheritdoc}
120
     *
121
     */
122
    public function filter(callable $callable)
123
    {
124
        $data = array_filter($this->data, $callable, ARRAY_FILTER_USE_BOTH);
125
        return new static($data);
126
    }
127
128
129
    /**
130
     * {@inheritdoc}
131
     *
132
     */
133
    public function map(callable $callable)
134
    {
135
        return array_map($callable, $this->data);
136
    }
137
}
138