Completed
Pull Request — master (#24)
by
unknown
03:21
created

SecurityMiddleware::execute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
ccs 8
cts 8
cp 1
rs 9.4285
cc 3
eloc 6
nc 3
nop 2
crap 3
1
<?php
2
3
namespace League\Tactician\Bundle\Middleware;
4
5
use League\Tactician\Exception\InvalidMiddlewareException;
6
use League\Tactician\Middleware;
7
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
8
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
9
10
11
class SecurityMiddleware implements Middleware
12
{
13
    /**
14
     * Access denied behavior to drop the command if not allowed.
15
     */
16
    const DROP_COMMAND = 1;
17
18
    /**
19
     * Access denied behavior to throw an AccessDenied exception if not allowed.
20
     * Default behavior.
21
     */
22
    const THROW_ACCESS_DENIED_EXCEPTION = 2;
23
24
    /**
25
     * @var int
26
     */
27
    private $accessDeniedBehavior;
28
29
    /**
30
     * @var AuthorizationCheckerInterface
31
     */
32
    private $authorizationChecker;
33
34
    /**
35
     * @param AuthorizationCheckerInterface $authorizationChecker
36
     */
37 12
    public function __construct(AuthorizationCheckerInterface $authorizationChecker, $accessDeniedBehavior = self::THROW_ACCESS_DENIED_EXCEPTION) {
38 12
        $this->authorizationChecker = $authorizationChecker;
39 12
        $this->accessDeniedBehavior = $accessDeniedBehavior;
40
41 12
        if ($this->accessDeniedBehavior !== static::DROP_COMMAND && $this->accessDeniedBehavior !== static::THROW_ACCESS_DENIED_EXCEPTION) {
42 3
            throw new InvalidMiddlewareException(
43 3
                sprintf('The security middleware requires a valid accessDeniedBehavior, \'%s\' is not valid.', $this->accessDeniedBehavior)
44 3
            );
45
        }
46 9
    }
47
48
    /**
49
     * @param object $command
50
     * @param callable $next
51
     * @return mixed
52
     */
53 9
    public function execute($command, callable $next)
54
    {
55 9
        if ($this->authorizationChecker->isGranted('handle', $command)) {
56 3
            return $next($command);
57 6
        } elseif ($this->accessDeniedBehavior === static::THROW_ACCESS_DENIED_EXCEPTION) {
58 3
            throw new AccessDeniedException(
59 3
                sprintf('The current user is not allowed to handle command of type \'%s\'', get_class($command))
60 3
            );
61
        }
62 3
    }
63
}
64
65