Parser   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 50
rs 10
c 0
b 0
f 0
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 15 3
A isValid() 0 3 1
A parseJwt() 0 3 1
A addConstraint() 0 5 1
A parse() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Damax\Bundle\ApiAuthBundle\Jwt\Lcobucci;
6
7
use Damax\Bundle\ApiAuthBundle\Jwt\Token;
8
use Damax\Bundle\ApiAuthBundle\Jwt\TokenParser;
9
use Lcobucci\Clock\Clock;
10
use Lcobucci\JWT\Configuration as JwtConfiguration;
11
use Lcobucci\JWT\Token as JwtToken;
12
use Lcobucci\JWT\Validation\Constraint;
13
14
final class Parser implements TokenParser
15
{
16
    /**
17
     * @var JwtConfiguration
18
     */
19
    private $config;
20
21
    /**
22
     * @var Constraint[]
23
     */
24
    private $constraints;
25
26
    public function __construct(JwtConfiguration $config, Clock $clock, array $issuers = null, string $audience = null)
27
    {
28
        $this->config = $config;
29
30
        $this
31
            ->addConstraint(new Constraint\ValidAt($clock))
32
            ->addConstraint(new Constraint\SignedWith($this->config->getSigner(), $this->config->getVerificationKey()))
33
        ;
34
35
        if ($issuers) {
36
            $this->addConstraint(new Constraint\IssuedBy(...$issuers));
37
        }
38
39
        if ($audience) {
40
            $this->addConstraint(new Constraint\PermittedFor($audience));
41
        }
42
    }
43
44
    public function isValid(string $jwt): bool
45
    {
46
        return $this->config->getValidator()->validate($this->parseJwt($jwt), ...$this->constraints);
47
    }
48
49
    public function parse(string $jwt): Token
50
    {
51
        return Token::fromClaims($this->parseJwt($jwt)->claims()->all());
52
    }
53
54
    private function addConstraint(Constraint $constraint): self
55
    {
56
        $this->constraints[] = $constraint;
57
58
        return $this;
59
    }
60
61
    private function parseJwt(string $jwt): JwtToken
62
    {
63
        return $this->config->getParser()->parse($jwt);
64
    }
65
}
66