Passed
Pull Request — master (#76)
by Marco
03:06
created

PickLastMinorVersionFromCollection   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B forVersions() 0 26 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 $lastVersion */
33
        $lastVersion = array_values(iterator_to_array($versions))[0];
34
35
        $matchingMinorVersions = $versions->matching(new CompositeConstraint(
36
            CompositeConstraint::OPERATOR_AND,
37
            new ComparisonConstraint(ComparisonConstraint::OPERATOR_LTE, $lastVersion),
38
            new ComparisonConstraint(
39
                ComparisonConstraint::OPERATOR_GTE,
40
                Version::fromString($lastVersion->getMajor() . '.' . $lastVersion->getMinor() . '.0')
41
            )
42
        ));
43
44
        $matchingMinorVersions->sort(VersionsCollection::SORT_ASC);
45
46
        /** @var Version[] $matchingMinorVersionsAsArray */
47
        $matchingMinorVersionsAsArray = array_values(iterator_to_array($matchingMinorVersions));
48
49
        return $matchingMinorVersionsAsArray[0];
50
    }
51
}
52