NavigationHelper::isAncestor()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Everlution\NavigationBundle\Twig;
6
7
use Everlution\Navigation\Builder\MatcherInterface;
8
use Everlution\Navigation\Builder\NavigationBuilder;
9
use Everlution\Navigation\Builder\NoCurrentItemFoundException;
10
use Everlution\Navigation\ContainerInterface;
11
use Everlution\Navigation\FilteredContainer;
12
use Everlution\Navigation\FilteredContainerInterface;
13
use Everlution\Navigation\Item\ItemInterface;
14
use Everlution\Navigation\Registry;
15
use Everlution\NavigationBundle\Bridge\NavigationAliasContainer;
16
17
/**
18
 * Class NavigationHelper.
19
 *
20
 * @author Ivan Barlog <[email protected]>
21
 */
22
class NavigationHelper
23
{
24
    /** @var Registry */
25
    private $registry;
26
    /** @var NavigationAliasContainer */
27
    private $aliasContainer;
28
    /** @var MatcherInterface */
29
    private $matcher;
30
    /** @var NavigationBuilder[] */
31
    private $container = [];
32
33
    public function __construct(
34
        Registry $registry,
35
        NavigationAliasContainer $aliasContainer,
36
        MatcherInterface $matcher
37
    ) {
38
        $this->registry = $registry;
39
        $this->aliasContainer = $aliasContainer;
40
        $this->matcher = $matcher;
41
    }
42
43
    public function isCurrent(string $identifier, ItemInterface $item): bool
44
    {
45
        try {
46
            return $this->getNavigation($identifier)->getCurrent() === $item;
47
        } catch (NoCurrentItemFoundException $exception) {
48
            return false;
49
        }
50
    }
51
52
    public function isAncestor(string $identifier, ItemInterface $item): bool
53
    {
54
        try {
55
            return $this->getNavigation($identifier)->isAncestor($item);
56
        } catch (NoCurrentItemFoundException $e) {
57
            return false;
58
        }
59
    }
60
61
    public function getNavigation(string $navigation): NavigationBuilder
62
    {
63
        if (false === array_key_exists($navigation, $this->container)) {
64
            $container = $this->getContainer($navigation);
65
            $this->container[$navigation] = new NavigationBuilder($container, $this->matcher);
66
        }
67
68
        return $this->container[$navigation];
69
    }
70
71
    private function getContainer(string $navigation): ContainerInterface
72
    {
73
        $container = $this->registry->getContainer($this->aliasContainer->get($navigation));
74
75
        if ($container instanceof FilteredContainerInterface) {
76
            return new FilteredContainer($container);
77
        }
78
79
        return $container;
80
    }
81
}
82