FilterByRoleNonStrictly   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 17
c 1
b 0
f 0
dl 0
loc 40
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A filter() 0 14 4
A __construct() 0 3 1
A filterItems() 0 14 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Everlution\Navigation\Filter;
6
7
use Everlution\Navigation\Item\HasSupportedRolesInterface;
8
use Everlution\Navigation\Item\ItemInterface;
9
use Everlution\Navigation\MutableContainerInterface;
10
11
/**
12
 * Class RoleFilter.
13
 *
14
 * @author Ivan Barlog <[email protected]>
15
 */
16
class FilterByRoleNonStrictly implements NavigationFilterInterface
17
{
18
    /** @var string[] */
19
    private $roles;
20
21
    public function __construct(RolesProviderInterface $roleProvider)
22
    {
23
        $this->roles = $roleProvider->getRoles();
24
    }
25
26
    public function filterItems(MutableContainerInterface $container): MutableContainerInterface
27
    {
28
        $filtered = clone $container;
29
        $filtered->reset();
30
31
        array_map(
32
            [$filtered, 'add'],
33
            array_filter(
34
                $container->getItems(),
35
                [$this, 'filter']
36
            )
37
        );
38
39
        return $filtered;
40
    }
41
42
    private function filter(ItemInterface $item): bool
43
    {
44
        if (false === $item instanceof HasSupportedRolesInterface) {
45
            return true;
46
        }
47
48
        /** @var HasSupportedRolesInterface $item */
49
        foreach ($item->getSupportedRoles() as $role) {
50
            if (in_array($role, $this->roles)) {
51
                return true;
52
            }
53
        }
54
55
        return false;
56
    }
57
}
58