Passed
Pull Request — master (#76)
by Marco
02:48
created

PickLastMinorVersionFromCollection   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 10
c 0
b 0
f 0
wmc 1

1 Method

Rating   Name   Duplication   Size   Complexity  
B forVersions() 0 30 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Roave\BackwardCompatibility\Git;
6
7
use Assert\Assert;
8
use Symfony\Component\Process\Exception\LogicException;
9
use Symfony\Component\Process\Exception\RuntimeException;
10
use Version\Constraint\ComparisonConstraint;
11
use Version\Constraint\CompositeConstraint;
12
use Version\Version;
13
use Version\VersionsCollection;
14
use function array_values;
15
use function iterator_to_array;
16
17
final class PickLastMinorVersionFromCollection implements PickVersionFromVersionCollection
18
{
19
    /**
20
     * {@inheritDoc}
21
     * @throws LogicException
22
     * @throws RuntimeException
23
     */
24
    public function forVersions(VersionsCollection $versions) : Version
25
    {
26
        Assert
27
            ::that($versions->count())
28
            ->greaterThan(0, 'Cannot determine latest minor version from an empty collection');
29
30
        $versions->sort(VersionsCollection::SORT_DESC);
31
32
        /** @var Version[] $versionsAsArray */
33
        $versionsAsArray = array_values(iterator_to_array($versions));
34
35
        /** @var Version $lastVersion */
36
        $lastVersion = $versionsAsArray[0];
37
38
        $matchingMinorVersions = $versions->matching(new CompositeConstraint(
39
            CompositeConstraint::OPERATOR_AND,
40
            new ComparisonConstraint(ComparisonConstraint::OPERATOR_LTE, $lastVersion),
41
            new ComparisonConstraint(
42
                ComparisonConstraint::OPERATOR_GTE,
43
                Version::fromString($lastVersion->getMajor() . '.' . $lastVersion->getMinor() . '.0')
44
            )
45
        ));
46
47
        $matchingMinorVersions->sort(VersionsCollection::SORT_ASC);
48
49
        /** @var Version[] $matchingMinorVersionsAsArray */
50
        $matchingMinorVersionsAsArray = array_values(iterator_to_array($matchingMinorVersions));
51
52
        // Note: since the collection is never empty, we can assume that the first element exists
53
        return $matchingMinorVersionsAsArray[0];
54
    }
55
}
56