Completed
Push — master ( b489fc...382b22 )
by Pavel
02:38
created

MatchScoreTargetSorter::getMatchingTarget()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 12
cts 12
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 6
nop 1
crap 4
1
<?php
2
3
namespace Bankiru\Seo\Target;
4
5
use Bankiru\Seo\DestinationInterface;
6
use Bankiru\Seo\Exception\MatchingException;
7
use Bankiru\Seo\TargetRepositoryInterface;
8
9
final class MatchScoreTargetSorter implements TargetSorter
10
{
11
    /** @var TargetRepositoryInterface */
12
    private $targetRepository;
13
14
    /**
15
     * MatchScoreTargetSorter constructor.
16
     *
17
     * @param TargetRepositoryInterface $targetRepository
18
     */
19 5
    public function __construct(TargetRepositoryInterface $targetRepository)
20
    {
21 5
        $this->targetRepository = $targetRepository;
22 5
    }
23
24
    /** {@inheritdoc} */
25 5
    public function getMatchingTarget(DestinationInterface $destination)
26
    {
27 5
        $sorted = [];
28 5
        foreach ($this->targetRepository->findByRoute($destination->getRoute()) as $target) {
29 5
            $score = $target->match($destination);
30 5
            if (null !== $score) {
31 2
                $sorted[$score] = $target;
32 2
            }
33 5
        }
34
35 5
        if (count($sorted) === 0) {
36 3
            throw MatchingException::noTarget();
37
        }
38
39 2
        ksort($sorted, SORT_DESC);
40
41 2
        return array_shift($sorted);
42
    }
43
}
44