NamshiSymmetric::decode()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 14
ccs 6
cts 7
cp 0.8571
rs 9.4285
cc 3
eloc 8
nc 3
nop 1
crap 3.0261
1
<?php
2
3
/**
4
 * This file is part of the BEAR.JwtAuthModule package.
5
 *
6
 * @license http://opensource.org/licenses/MIT MIT
7
 */
8
namespace BEAR\JwtAuth\Encoder;
9
10
use BEAR\JwtAuth\Annotation\Algo;
11
use BEAR\JwtAuth\Annotation\Secret;
12
use BEAR\JwtAuth\Exception\InvalidTokenException;
13
use BEAR\JwtAuth\Exception\JwtException;
14
use Namshi\JOSE\JWS;
15
16
class NamshiSymmetric implements JwtEncoderInterface
17
{
18
    /**
19
     * @var JWS
20
     */
21
    private $jws;
22
23
    /**
24
     * @var string
25
     */
26
    private $algo;
27
28
    /**
29
     * @var string
30
     */
31
    private $secret;
32
33
    /**
34
     * @Algo("algo")
35
     * @Secret("secret")
36
     */
37 6
    public function __construct(string $algo, string $secret)
38
    {
39 6
        $this->jws = new JWS(['typ' => 'JWT', 'alg' => $algo]);
40 6
        $this->algo = $algo;
41 6
        $this->secret = $secret;
42 6
    }
43
44 2
    public function encode(array $payload) : string
45
    {
46
        try {
47 2
            $this->jws->setPayload($payload)->sign($this->secret);
48
49 2
            return (string) $this->jws->getTokenString();
50
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class BEAR\JwtAuth\Encoder\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
51
            throw new JwtException($e->getMessage());
52
        }
53
    }
54
55 3
    public function decode(string $token) : array
56
    {
57
        try {
58 3
            $jws = $this->jws->load($token, false);
59 1
        } catch (\InvalidArgumentException $e) {
60 1
            throw new InvalidTokenException($e->getMessage());
61
        }
62
63 2
        if (!$jws->verify($this->secret, $this->algo)) {
64
            throw new InvalidTokenException('Invalid Token');
65
        }
66
67 2
        return (array) $jws->getPayload();
68
    }
69
}
70