Passed
Branch master (117216)
by Pavel
08:06
created

ContainerLinkResolver   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 3
dl 0
loc 59
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A addResolver() 0 4 1
A resolve() 0 14 3
A supports() 0 4 1
A matchResolver() 0 9 3
1
<?php
2
3
namespace Bankiru\Seo\Generator;
4
5
use Bankiru\Seo\Entity\ContainerLinkInterface;
6
use Bankiru\Seo\Exception\LinkGeneratorException;
7
use Bankiru\Seo\Exception\LinkResolutionException;
8
9
final class ContainerLinkResolver implements LinkResolver
10
{
11
    /** @var LinkResolver[] */
12
    private $resolvers = [];
13
14
    /**
15
     * ContainerLinkResolver constructor.
16
     *
17
     * @param LinkResolver[] $resolvers
18
     */
19
    public function __construct(array $resolvers = [])
20
    {
21
        $this->resolvers = $resolvers;
22
        $this->resolvers[] = $this;
23
    }
24
25
    public function addResolver(LinkResolver $resolver)
26
    {
27
        $this->resolvers[] = $resolver;
28
    }
29
30
    /** {@inheritdoc} */
31
    public function resolve($container)
32
    {
33
        if (!$this->supports($container)) {
34
            throw new LinkResolutionException('Link type not supported');
35
        }
36
37
        /** @var ContainerLinkInterface $container */
38
        $result = [];
39
        foreach ($container as $link) {
40
            $result = array_merge($result, $this->matchResolver($link)->resolve($link));
41
        }
42
43
        return $result;
44
    }
45
46
    /** {@inheritdoc} */
47
    public function supports($link)
48
    {
49
        return $link instanceof ContainerLinkInterface;
50
    }
51
52
    /**
53
     * @param $link
54
     *
55
     * @return LinkResolver
56
     * @throws LinkGeneratorException
57
     */
58
    private function matchResolver($link)
59
    {
60
        foreach ($this->resolvers as $resolver) {
61
            if ($resolver->supports($link)) {
62
                return $resolver;
63
            }
64
        }
65
        throw new LinkGeneratorException('Cannot find link resolver for link: ' . get_class($link));
66
    }
67
}
68