Passed
Push — master ( 3ec415...9f2f47 )
by Daniel
16:25
created

RouteVoter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
dl 0
loc 29
ccs 0
cts 12
cp 0
rs 10
c 1
b 0
f 0
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A voteOnAttribute() 0 10 4
A supports() 0 3 2
A __construct() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Components Bundle Project
5
 *
6
 * (c) Daniel West <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace Silverback\ApiComponentsBundle\Security\Voter;
15
16
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
17
use Silverback\ApiComponentsBundle\Entity\Core\Route;
18
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
19
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
20
21
/**
22
 * @author Daniel West <[email protected]>
23
 */
24
class RouteVoter extends Voter
25
{
26
    private ?array $config;
27
    private ResourceAccessCheckerInterface $resourceAccessChecker;
28
29
    public function __construct(?array $config, ResourceAccessCheckerInterface $resourceAccessChecker)
30
    {
31
        $this->config = $config;
32
        $this->resourceAccessChecker = $resourceAccessChecker;
33
    }
34
35
    protected function supports($subject, $notRequired): bool
36
    {
37
        return $subject instanceof Route && $this->config;
38
    }
39
40
    /**
41
     * @param Route $route
42
     */
43
    protected function voteOnAttribute($route, $notRequired, TokenInterface $token): bool
44
    {
45
        foreach ($this->config as $index => $routeConfig) {
46
            $routeRegex = str_replace('\*', '(.*)', preg_quote($routeConfig['route'], '#'));
47
            if (!$this->resourceAccessChecker->isGranted(\get_class($route), $routeConfig['security']) && preg_match(sprintf('#%s#', $routeRegex), $route->getPath())) {
48
                return false;
49
            }
50
        }
51
52
        return true;
53
    }
54
}
55