Completed
Pull Request — master (#15)
by Gabriel
05:24
created

AbstractCollection   B

Complexity

Total Complexity 49

Size/Duplication

Total Lines 320
Duplicated Lines 6.25 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 49
c 1
b 0
f 0
lcom 1
cbo 5
dl 20
loc 320
ccs 11
cts 11
cp 1
rs 8.5455

29 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 20 6
A toArray() 0 4 1
A first() 0 4 1
A last() 0 4 1
A key() 0 4 1
A next() 0 4 1
A current() 0 4 1
A remove() 0 12 3
A contains() 0 5 2
A containsVersion() 0 5 1
A exists() 10 10 3
A get() 0 5 2
A getKeys() 0 4 1
A getValues() 0 4 1
A count() 0 4 1
A replace() 0 8 2
A add() 0 12 2
A isEmpty() 0 4 1
A getIterator() 0 4 1
A map() 0 4 1
A filter() 0 4 1
A forAll() 10 10 3
A partition() 0 14 3
A __toString() 0 4 1
A clear() 0 4 1
A slice() 0 4 1
A merge() 0 8 2
A getPosition() 0 3 1
A getByPosition() 0 9 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AbstractCollection often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractCollection, and based on these observations, apply Extract Interface, too.

1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Baleen\Migrations\Shared\Collection;
21
22
use ArrayIterator;
23
use Baleen\Migrations\Exception\InvalidArgumentException;
24
use Baleen\Migrations\Exception\Version\Collection\AlreadyExistsException;
25
use Baleen\Migrations\Exception\Version\Collection\CollectionException;
26
use Baleen\Migrations\Version\VersionInterface;
27
use Closure;
28
use Zend\Stdlib\ArrayUtils;
29
30
/**
31
 * Based on the Doctrine\CollectionAbstract project.
32
 *
33
 * @see https://github.com/doctrine/collections
34
 *
35
 * @author Gabriel Somoza <[email protected]>
36
 */
37
abstract class AbstractCollection implements CollectionInterface
38
{
39
    /**
40
     * An array containing the entries of this collection.
41
     *
42
     * @var VersionInterface[]
43
     */
44
    private $elements;
45
46
    /**
47
     * Initializes a new AbstractCollection.
48
     *
49
     * @param VersionInterface[] $elements
50
     *
51
     * @throws AlreadyExistsException
52
     * @throws CollectionException
53
     * @throws InvalidArgumentException
54
     */
55 158
    public function __construct($elements = [])
56
    {
57 158
        if (!is_array($elements)) {
58 4
            if ($elements instanceof \Traversable) {
59 3
                $elements = ArrayUtils::iteratorToArray($elements);
60 3
            } else {
61 1
                throw new InvalidArgumentException(
62
                    "Constructor parameter 'versions' must be an array or Traversable object."
63 1
                );
64
            }
65 3
        }
66
67 157
        $this->elements = [];
68 157
        foreach ($elements as $element) {
69 141
            if (!is_object($element) || !$element instanceof VersionInterface) {
70
                throw CollectionException::invalidObjectException($element, VersionInterface::class);
71
            }
72
            $this->add($element);
73
        }
74
    }
75
76
    /**
77
     * {@inheritDoc}
78
     */
79
    final public function toArray()
80
    {
81
        return $this->elements;
82
    }
83
84
    /**
85
     * {@inheritDoc}
86
     */
87
    final public function first()
88
    {
89
        return reset($this->elements);
90
    }
91
92
    /**
93
     * {@inheritDoc}
94
     */
95
    final public function last()
96
    {
97
        return end($this->elements);
98
    }
99
100
    /**
101
     * {@inheritDoc}
102
     */
103
    final public function key()
104
    {
105
        return key($this->elements);
106
    }
107
108
    /**
109
     * {@inheritDoc}
110
     */
111
    final public function next()
112
    {
113
        return next($this->elements);
114
    }
115
116
    /**
117
     * {@inheritDoc}
118
     */
119
    final public function current()
120
    {
121
        return current($this->elements);
122
    }
123
124
    /**
125
     * {@inheritDoc}
126
     */
127
    public function remove($key)
128
    {
129
        $key = (string) $key;
130
        if ( ! isset($this->elements[$key]) && ! array_key_exists($key, $this->elements)) {
131
            return null;
132
        }
133
134
        $removed = $this->elements[$key];
135
        unset($this->elements[$key]);
136
137
        return $removed;
138
    }
139
140
    /**
141
     * {@inheritDoc}
142
     */
143
    final public function contains($key)
144
    {
145
        $key = (string) $key;
146
        return isset($this->elements[$key]) || array_key_exists($key, $this->elements);
147
    }
148
149
    /**
150
     * {@inheritDoc}
151
     */
152
    final public function containsVersion(VersionInterface $version)
153
    {
154
        $key = (string) $version->getId();
155
        return $this->contains($key);
156
    }
157
158
    /**
159
     * {@inheritDoc}
160
     */
161 View Code Duplication
    final public function exists(Closure $p)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
162
    {
163
        foreach ($this->elements as $key => $element) {
164
            if ($p($key, $element)) {
165
                return true;
166
            }
167
        }
168
169
        return false;
170
    }
171
172
    /**
173
     * {@inheritDoc}
174
     */
175
    final public function get($key)
176
    {
177
        $key = (string) $key;
178
        return isset($this->elements[$key]) ? $this->elements[$key] : null;
179
    }
180
181
    /**
182
     * {@inheritDoc}
183
     */
184
    final public function getKeys()
185
    {
186
        return array_keys($this->elements);
187
    }
188
189
    /**
190
     * {@inheritDoc}
191
     */
192
    final public function getValues()
193
    {
194
        return array_values($this->elements);
195
    }
196
197
    /**
198
     * {@inheritDoc}
199
     */
200
    final public function count()
201
    {
202
        return count($this->elements);
203
    }
204
205
    /**
206
     * {@inheritDoc}
207
     */
208
    public function replace(VersionInterface $version)
209
    {
210
        $key = $version->getId()->toString();
211
        $replacedElement = $this->contains($key) ? $this->get($key) : null;
212
        $this->elements[$key] = $version;
213
214
        return $replacedElement;
215
    }
216
217
    /**
218
     * {@inheritDoc}
219
     */
220
    public function add(VersionInterface $value)
221
    {
222
        $key = $value->getId()->toString();
223
        if ($this->contains($key)) {
224
            throw new AlreadyExistsException(sprintf(
225
                'Element with key "%s" already exists. Remove it first or use replace() if you want to overwrite it.',
226
                $key
227
            ));
228
        }
229
        $this->elements[$key] = $value;
230
        return true;
231
    }
232
233
    /**
234
     * {@inheritDoc}
235
     */
236
    final public function isEmpty()
237
    {
238
        return empty($this->elements);
239
    }
240
241
    /**
242
     * Required by interface IteratorAggregate.
243
     *
244
     * {@inheritDoc}
245
     */
246
    final public function getIterator()
247
    {
248
        return new ArrayIterator($this->elements);
249
    }
250
251
    /**
252
     * {@inheritDoc}
253
     */
254
    final public function map(Closure $func)
255
    {
256
        return array_map($func, $this->elements);
257
    }
258
259
    /**
260
     * {@inheritDoc}
261
     */
262
    final public function filter(Closure $p)
263
    {
264
        return new static(array_filter($this->elements, $p));
265
    }
266
267
    /**
268
     * {@inheritDoc}
269
     */
270 View Code Duplication
    final public function forAll(Closure $p)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
271
    {
272
        foreach ($this->elements as $key => $element) {
273
            if ( ! $p($key, $element)) {
274
                return false;
275
            }
276
        }
277
278
        return true;
279
    }
280
281
    /**
282
     * {@inheritDoc}
283
     */
284
    final public function partition(Closure $p)
285
    {
286
        $matches = $noMatches = array();
287
288
        foreach ($this->elements as $key => $element) {
289
            if ($p($key, $element)) {
290
                $matches[$key] = $element;
291
            } else {
292
                $noMatches[$key] = $element;
293
            }
294
        }
295
296
        return array(new static($matches), new static($noMatches));
297
    }
298
299
    /**
300
     * Returns a string representation of this object.
301
     *
302
     * @return string
303
     */
304
    public function __toString()
305
    {
306
        return __CLASS__ . '@' . spl_object_hash($this);
307
    }
308
309
    /**
310
     * {@inheritDoc}
311
     */
312
    public function clear()
313
    {
314
        $this->elements = [];
315
    }
316
317
    /**
318
     * @inheritDoc
319
     */
320
    final public function slice($offset, $length = null)
321
    {
322
        return array_slice($this->elements, $offset, $length, true);
323
    }
324
325
    /**
326
     * @inheritdoc
327
     */
328
    final public function merge(CollectionInterface $collection)
329
    {
330
        foreach ($collection as $version) {
331
            $this->replace($version);
332
        }
333
334
        return $this;
335
    }
336
337
    /**
338
     * @inheritdoc
339
     */
340
    final public function getPosition($key) {
341
        return array_search($key, $this->getKeys()) + 1;
342
    }
343
344
    /**
345
     * @inheritdoc
346
     */
347
    final public function getByPosition($position)
348
    {
349
        $index = $position - 1;
350
        $keys = $this->getKeys();
351
        if (!isset($keys[$index]) || !array_key_exists($index, $keys)) {
352
            return null;
353
        }
354
        return $this->get($keys[$index]);
355
    }
356
}
357