RouteVoter::voteOnAttribute()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 5
nc 3
nop 3
dl 0
loc 10
ccs 0
cts 6
cp 0
crap 20
rs 10
c 1
b 0
f 0
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\Symfony\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
    public const READ_ROUTE = 'read_route';
27
    private ?array $config;
28
    private ResourceAccessCheckerInterface $resourceAccessChecker;
29
30
    public function __construct(?array $config, ResourceAccessCheckerInterface $resourceAccessChecker)
31
    {
32
        $this->config = $config;
33
        $this->resourceAccessChecker = $resourceAccessChecker;
34
    }
35
36
    protected function supports($attribute, $subject): bool
37
    {
38
        return self::READ_ROUTE === $attribute && $subject instanceof Route && $this->config;
39
    }
40
41
    /**
42
     * @param Route $subject
43
     */
44
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool
45
    {
46
        foreach ($this->config as $routeConfig) {
47
            $routeRegex = str_replace('\*', '(.*)', preg_quote($routeConfig['route'], '#'));
48
            if (!$this->resourceAccessChecker->isGranted($subject::class, $routeConfig['security']) && preg_match(sprintf('#%s#', $routeRegex), $subject->getPath())) {
49
                return false;
50
            }
51
        }
52
53
        return true;
54
    }
55
}
56