Completed
Push — master ( 240c2a...797df5 )
by Nikola
02:38
created

VersionsCollection::getIterator()   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 3
Bugs 0 Features 0
Metric Value
c 3
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
 * This file is part of the Version package.
5
 *
6
 * Copyright (c) Nikola Posa <[email protected]>
7
 *
8
 * For full copyright and license information, please refer to the LICENSE file,
9
 * located at the package root folder.
10
 */
11
12
namespace Version;
13
14
use Countable;
15
use IteratorAggregate;
16
use ArrayIterator;
17
use Version\Exception\InvalidArgumentException;
18
19
/**
20
 * @author Nikola Posa <[email protected]>
21
 */
22
final class VersionsCollection implements Countable, IteratorAggregate
23
{
24
    const SORT_ASC = 'ASC';
25
    const SORT_DESC = 'DESC';
26
27
    /**
28
     * @var Version[]
29
     */
30
    private $versions = [];
31
32
    /**
33
     * @param array $versions
34
     */
35 9
    public function __construct(array $versions)
36
    {
37 9
        foreach ($versions as $version) {
38 9
            if (is_string($version)) {
39 9
                $version = Version::fromString($version);
40 9
            } elseif (!$version instanceof Version) {
41 1
                throw new InvalidArgumentException(sprintf(
42 1
                    'Item in the versions array should be either string or Version instance, %s given',
43 1
                    gettype($version)
44 1
                ));
45
            }
46
47 9
            $this->versions[] = $version;
48 9
        }
49 8
    }
50
51
    /**
52
     * @param array $versions
53
     * @return self
54
     */
55 8
    public static function fromArray(array $versions)
56
    {
57 8
        return new self($versions);
58
    }
59
60
    /**
61
     * @return int
62
     */
63 1
    public function count()
64
    {
65 1
        return count($this->versions);
66
    }
67
68
    /**
69
     * @return \Iterator
70
     */
71 5
    public function getIterator()
72
    {
73 5
        return new ArrayIterator($this->versions);
74
    }
75
76
    /**
77
     * @param string|bool $direction OPTIONAL
78
     * @return void
79
     */
80 4
    public function sort($direction = self::SORT_ASC)
81
    {
82 4
        if (is_bool($direction)) {
83
            //backwards-compatibility
84 2
            $direction = (true === $direction) ? self::SORT_DESC : self::SORT_ASC;
85 2
        }
86
87 4
        usort($this->versions, function (Version $a, Version $b) use ($direction) {
88 4
            $result = $a->compareTo($b);
89
90 4
            if ($direction == self::SORT_DESC) {
91 2
                $result *= -1;
92 2
            }
93
94 4
            return $result;
95 4
        });
96 4
    }
97
}
98