Completed
Pull Request — master (#76)
by Marco
08:32
created

PickLastMinorVersionFromCollection   A

Complexity

Total Complexity 1

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Importance

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

1 Method

Rating   Name   Duplication   Size   Complexity  
B forVersions() 0 25 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::that($versions->count())
27
            ->greaterThan(0, 'Cannot determine latest minor version from an empty collection');
28
29
        $versions->sort(VersionsCollection::SORT_DESC);
30
31
        /** @var Version $lastVersion */
32
        $lastVersion = array_values(iterator_to_array($versions))[0];
33
34
        $matchingMinorVersions = $versions->matching(new CompositeConstraint(
35
            CompositeConstraint::OPERATOR_AND,
36
            new ComparisonConstraint(ComparisonConstraint::OPERATOR_LTE, $lastVersion),
37
            new ComparisonConstraint(
38
                ComparisonConstraint::OPERATOR_GTE,
39
                Version::fromString($lastVersion->getMajor() . '.' . $lastVersion->getMinor() . '.0')
40
            )
41
        ));
42
43
        $matchingMinorVersions->sort(VersionsCollection::SORT_ASC);
44
45
        /** @var Version[] $matchingMinorVersionsAsArray */
46
        $matchingMinorVersionsAsArray = array_values(iterator_to_array($matchingMinorVersions));
47
48
        return $matchingMinorVersionsAsArray[0];
49
    }
50
}
51