Passed
Pull Request — master (#3)
by Sébastien
03:32 queued 01:03
created

RequiredScopeValidator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 6
c 3
b 0
f 0
dl 0
loc 10
rs 10
cc 4
nc 4
nop 1
1
<?php
2
3
namespace Parroauth2\Client\Extension;
4
5
use Parroauth2\Client\EndPoint\EndPointTransformerTrait;
6
use Parroauth2\Client\EndPoint\Introspection\IntrospectionEndPoint;
7
use Parroauth2\Client\EndPoint\Introspection\IntrospectionResponse;
8
use Parroauth2\Client\Exception\AccessDeniedException;
9
10
/**
11
 * Perform validation on the returned introspection response to check the associated scopes.
12
 * All scope of this validator have to be present in the introspection scopes.
13
 */
14
final class RequiredScopeValidator extends AbstractEndPointTransformerExtension
15
{
16
    use EndPointTransformerTrait;
17
18
    /**
19
     * @var string[]
20
     */
21
    private $scopes;
22
23
24
    /**
25
     * @param string[] $scopes
26
     */
27
    public function __construct(array $scopes)
28
    {
29
        $this->scopes = $scopes;
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function onIntrospection(IntrospectionEndPoint $endPoint): IntrospectionEndPoint
36
    {
37
        return $endPoint->onResponse([$this, 'validate']);
38
    }
39
40
    /**
41
     * Validate the all scopes are in the introspection response
42
     *
43
     * @param IntrospectionResponse $response
44
     *
45
     * @internal
46
     */
47
    public function validate(IntrospectionResponse $response): void
48
    {
49
        if (empty($scopes = $response->scopes())) {
50
            throw new AccessDeniedException("The introspection response has no scopes.");
51
        }
52
53
        foreach ($this->scopes as $scope) {
54
            if (!in_array($scope, $scopes)) {
55
                throw new AccessDeniedException(
56
                    "The scope '$scope' is not present in introspection response. Available scopes are " . implode(', ', $scopes)
57
                );
58
            }
59
        }
60
    }
61
}
62