Helper   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 24
c 4
b 0
f 0
dl 0
loc 48
rs 10
wmc 7

2 Methods

Rating   Name   Duplication   Size   Complexity  
A decode() 0 30 6
A generate() 0 11 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ParcelValue\Api\JWT;
6
7
use Firebase\JWT\JWT;
8
use Firebase\JWT\Key;
9
use ParcelValue\Api\Exceptions\JwtException;
10
11
final class Helper
12
{
13
    protected const ALGORITHM_HS256 = 'HS256';
14
15
    public static function generate(string $clientId, string $clientKey, string $serverKey): string
16
    {
17
        return JWT::encode(
18
            // Do not change array key order here, it is important (unit test fails).
19
            // phpcs:ignore SlevomatCodingStandard.Arrays.AlphabeticallySortedByKeys.IncorrectKeyOrder
20
            [
21
                'sub' => $clientId,
22
                'clientKey' => $clientKey,
23
            ], // payload PHP object or array
24
            $serverKey, // key The secret key.
25
            self::ALGORITHM_HS256, // alg The signing algorithm.
26
        );
27
    }
28
29
    public static function decode(string $jwt, string $serverKey): Payload
30
    {
31
        try {
32
            $payload = JWT::decode(
33
                $jwt, // jwt The JWT
34
                new Key(
35
                    $serverKey,
36
                    self::ALGORITHM_HS256,
37
                ),
38
            );
39
        } catch (\Throwable $e) {
40
            throw new JwtException($e->getMessage(), $e->getCode(), $e);
41
        }
42
43
        if (!\property_exists($payload, 'sub') || !\property_exists($payload, 'clientKey')) {
44
            throw new JwtException('Token is missing required data.');
45
        }
46
47
        $sub = (string) $payload->sub;
48
        $clientKey = (string) $payload->clientKey;
49
50
        if (!$sub) {
51
            throw new JwtException('Invalid token part: "sub".');
52
        }
53
54
        if (!$clientKey) {
55
            throw new JwtException('Invalid token part: "clientKey".');
56
        }
57
58
        return new Payload($sub, $clientKey);
59
    }
60
}
61