Failed Conditions
Push — master ( 2b3108...14c169 )
by Florent
07:02
created

ExpressionLanguageProvider   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 25
c 1
b 0
f 0
dl 0
loc 54
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A hasScope() 0 13 3
A getSecurityToken() 0 8 2
A getAccessToken() 0 8 2
A getFunctions() 0 12 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2019 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace OAuth2Framework\SecurityBundle\Security;
15
16
use OAuth2Framework\Component\Core\AccessToken\AccessToken;
17
use OAuth2Framework\SecurityBundle\Security\Authentication\Token\OAuth2Token;
18
use Symfony\Component\ExpressionLanguage\ExpressionFunction;
19
use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface;
20
21
final class ExpressionLanguageProvider implements ExpressionFunctionProviderInterface
22
{
23
    /**
24
     * @return ExpressionFunction[]
25
     */
26
    public function getFunctions(): array
27
    {
28
        return [
29
            new ExpressionFunction('has_oauth2_scope', static function ($scope) {
30
                return sprintf('in_array(%s, $scopes)', $scope);
31
            }, static function (array $variables, $scope) {
32
                $accessToken = self::getAccessToken($variables);
33
                if (null === $accessToken) {
34
                    return false;
35
                }
36
37
                return self::hasScope($accessToken, $scope);
38
            }),
39
        ];
40
    }
41
42
    private static function hasScope(AccessToken $accessToken, string $scope): bool
43
    {
44
        $parameters = $accessToken->getParameter();
45
        if (!$parameters->has('scope')) {
46
            return false;
47
        }
48
        $availableScope = $parameters->get('scope');
49
        if (!\is_string($availableScope)) {
50
            return false;
51
        }
52
        $availableScopes = explode(' ', $availableScope);
53
54
        return \in_array($scope, $availableScopes, true);
55
    }
56
57
    private static function getSecurityToken(array $variables): ?OAuth2Token
58
    {
59
        $securityToken = $variables['token'] ?? null;
60
        if (!$securityToken instanceof OAuth2Token) {
61
            return null;
62
        }
63
64
        return $securityToken;
65
    }
66
67
    private static function getAccessToken(array $variables): ?AccessToken
68
    {
69
        $securityToken = self::getSecurityToken($variables);
70
        if (null === $securityToken) {
71
            return null;
72
        }
73
74
        return $securityToken->getAccessToken();
75
    }
76
}
77