Completed
Push — master ( 81f90a...fb71af )
by Joschi
03:44
created

Collection::valid()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 * apparat-object
5
 *
6
 * @category    Apparat
7
 * @package     Apparat\Object\Domain
8
 * @author      Joschi Kuphal <[email protected]> / @jkphl
9
 * @copyright   Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
10
 * @license     http://opensource.org/licenses/MIT The MIT License (MIT)
11
 */
12
13
/***********************************************************************************
14
 *  The MIT License (MIT)
15
 *
16
 *  Copyright © 2016 Joschi Kuphal <[email protected]> / @jkphl
17
 *
18
 *  Permission is hereby granted, free of charge, to any person obtaining a copy of
19
 *  this software and associated documentation files (the "Software"), to deal in
20
 *  the Software without restriction, including without limitation the rights to
21
 *  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
22
 *  the Software, and to permit persons to whom the Software is furnished to do so,
23
 *  subject to the following conditions:
24
 *
25
 *  The above copyright notice and this permission notice shall be included in all
26
 *  copies or substantial portions of the Software.
27
 *
28
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
29
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
30
 *  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
31
 *  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
32
 *  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
33
 *  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34
 ***********************************************************************************/
35
36
namespace Apparat\Object\Domain\Model\Object;
37
38
use Apparat\Object\Domain\Model\Path\RepositoryPath;
39
40
/**
41
 * Lazy loading object collection
42
 *
43
 * @package Apparat\Object
44
 * @subpackage Apparat\Object\Domain
45
 */
46
class Collection implements CollectionInterface
47
{
48
    /**
49
     * Objects
50
     *
51
     * @var ObjectInterface[]|RepositoryPath[]
52
     */
53
    protected $_objects = array();
54
    /**
55
     * Object IDs
56
     *
57
     * @var array
58
     */
59
    protected $_objectIds = array();
60
    /**
61
     * Internal object pointer
62
     *
63
     * @var int
64
     */
65
    protected $_pointer = 0;
66
67
    /*******************************************************************************
68
     * PUBLIC METHODS
69
     *******************************************************************************/
70
71
    /**
72
     * Collection constructor
73
     *
74
     * @param array $objects Collection objects
75
     * @throws InvalidArgumentException If the an invalid object or path is provided
76
     */
77 7
    public function __construct(array $objects = [])
78
    {
79 7
        foreach ($objects as $object) {
80
            // If it's an object
81 7
            if ($object instanceof ObjectInterface) {
82 3
                $this->_objects[$object->getId()->getId()] = $object;
83
84
                // Else if it's an object path
85
            } elseif ($object instanceof RepositoryPath) {
86 7
                $this->_objects[$object->getId()->getId()] = $object;
0 ignored issues
show
Bug introduced by
The method getId cannot be called on $object->getId() (of type integer).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
87
88
                // Else: Error
89
            } else {
90 1
                throw new InvalidArgumentException(
91 1
                    'Invalid collection object or path',
92 7
                    InvalidArgumentException::INVALID_COLLECTION_OBJECT_OR_PATH
93
                );
94
            }
95
        }
96
97 7
        $this->_objectIds = array_keys($this->_objects);
98 7
    }
99
100
    /**
101
     * Return the current object
102
     *
103
     * @return ObjectInterface Current object
104
     */
105 3
    public function current()
106
    {
107 3
        return $this->_loadObject($this->_objectIds[$this->_pointer]);
108
    }
109
110
    /**
111
     * Load and return an object by ID
112
     *
113
     * @param int $objectId Object ID
114
     * @return ObjectInterface Object
115
     */
116 3
    protected function _loadObject($objectId)
117
    {
118
        // Lazy-load the object once
119 3
        if ($this->_objects[$objectId] instanceof RepositoryPath) {
120 3
            $this->_objects[$objectId] = $this->_objects[$objectId]->getRepository()->loadObject(
0 ignored issues
show
Bug introduced by
The method getRepository does only exist in Apparat\Object\Domain\Model\Path\RepositoryPath, but not in Apparat\Object\Domain\Model\Object\ObjectInterface.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
121 3
                $this->_objects[$objectId]
122
            );
123
        }
124
125 3
        return $this->_objects[$objectId];
126
    }
127
128
    /**
129
     * Move forward to next object
130
     *
131
     * @return void
132
     */
133 1
    public function next()
134
    {
135 1
        ++$this->_pointer;
136 1
    }
137
138
    /**
139
     * Return the ID of the current object
140
     *
141
     * @return int Object ID
142
     */
143 1
    public function key()
144
    {
145 1
        return $this->_objectIds[$this->_pointer];
146
    }
147
148
    /**
149
     * Checks if current position is valid
150
     *
151
     * @return boolean The current position is valid
152
     */
153 3
    public function valid()
154
    {
155 3
        return isset($this->_objectIds[$this->_pointer]);
156
    }
157
158
    /**
159
     * Rewind the Iterator to the first object
160
     *
161
     * @return void
162
     */
163 3
    public function rewind()
164
    {
165 3
        $this->_pointer = 0;
166 3
    }
167
168
    /**
169
     * Whether an object ID exists
170
     *
171
     * @param int $offset Object ID
172
     * @return boolean Whether the object ID exists
173
     */
174 1
    public function offsetExists($offset)
175
    {
176 1
        return isset($this->_objects[$offset]);
177
    }
178
179
    /**
180
     * Get an object with a particular ID
181
     *
182
     * @param int $offset Object ID
183
     * @return ObjectInterface Object
184
     */
185 2
    public function offsetGet($offset)
186
    {
187 2
        return $this->_objects[$offset];
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->_objects[$offset]; of type Apparat\Object\Domain\Mo...del\Path\RepositoryPath adds the type Apparat\Object\Domain\Model\Path\RepositoryPath to the return on line 187 which is incompatible with the return type documented by Apparat\Object\Domain\Mo...t\Collection::offsetGet of type Apparat\Object\Domain\Model\Object\ObjectInterface.
Loading history...
188
    }
189
190
    /**
191
     * Set an object by ID
192
     *
193
     * @param int $offset Object ID
194
     * @param ObjectInterface $value Object
195
     * @throws RuntimeException When an object should be set by ID
196
     */
197 1
    public function offsetSet($offset, $value)
198
    {
199 1
        throw new RuntimeException('Cannot modify collection by index. Use add() / remove() instead', RuntimeException::CANNOT_MODIFY_COLLECTION_BY_INDEX);
200
    }
201
202
    /**
203
     * Unset an object by ID
204
     *
205
     * @param int $offset Object ID
206
     * @throws RuntimeException When an object should be set by ID
207
     */
208 1
    public function offsetUnset($offset)
209
    {
210 1
        throw new RuntimeException('Cannot modify collection by index. Use add() / remove() instead', RuntimeException::CANNOT_MODIFY_COLLECTION_BY_INDEX);
211
    }
212
213
    /**
214
     * Add an object to the collection
215
     *
216
     * @param string|ObjectInterface $object Object or object URL
217
     * @return Collection Modified object collection
218
     */
219 2
    public function add($object)
220
    {
221 2
        $objects = $this->_objects;
222 2
        $objects[] = $object;
223 2
        return new self(array_values($objects));
224
    }
225
226
    /**
227
     * Remove an object out of this collection
228
     *
229
     * @param string|ObjectInterface $object Object or object ID
230
     * @return Collection Modified object collection
231
     */
232 1
    public function remove($object)
233
    {
234 1
        if ($object instanceof ObjectInterface) {
235 1
            $object = $object->getId()->getId();
236
        } else {
237 1
            $object = intval($object);
238
        }
239 1
        if (empty($this->_objects[$object])) {
240 1
            throw new InvalidArgumentException(
241 1
                sprintf('Unknown object ID "%s"', $object),
242 1
                InvalidArgumentException::UNKNOWN_OBJECT_ID
243
            );
244
        }
245
246 1
        $objects = $this->_objects;
247 1
        unset($objects[$object]);
248 1
        return new self(array_values($objects));
249
    }
250
251
    /**
252
     * Count objects in this collection
253
     *
254
     * @return int The number of objects in this collection
255
     */
256 6
    public function count()
257
    {
258 6
        return count($this->_objects);
259
    }
260
261
    /*******************************************************************************
262
     * PRIVATE METHODS
263
     *******************************************************************************/
264
265
    /**
266
     * Append another collection
267
     *
268
     * @param Collection $collection Collection
269
     * @return Collection Combined collections
270
     */
271 1
    public function append(Collection $collection)
272
    {
273 1
        $objects = array_merge($this->_objects, $collection->_objects);
274 1
        return new self(array_values($objects));
275
    }
276
}
277