Passed
Push — master ( b15242...753048 )
by Radu
02:16
created

Helper::decode()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 17
rs 9.9332
cc 4
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ParcelValue\Api\JWT;
6
7
use Firebase\JWT\JWT;
8
use ParcelValue\Api\Exceptions\JwtException;
9
10
final class Helper
11
{
12
    protected const ALGORITHM_HS256 = 'HS256';
13
14
    public static function generate(string $clientId, string $clientKey, string $serverKey): string
15
    {
16
        return JWT::encode(
17
            [
18
                'sub' => $clientId,
19
                'clientKey' => $clientKey,
20
            ], // payload PHP object or array
21
            $serverKey, // key The secret key.
22
            self::ALGORITHM_HS256, // alg The signing algorithm.
23
        );
24
    }
25
26
    public static function decode(string $jwt, string $serverKey): Payload
27
    {
28
        try {
29
            $payload = JWT::decode(
30
                $jwt, // jwt The JWT
31
                $serverKey, // key The key, or map of keys.
32
                [self::ALGORITHM_HS256], // allowed_algs List of supported verification algorithms
33
            );
34
        } catch (\Throwable $e) {
35
            throw new JwtException($e->getMessage(), $e);
36
        }
37
38
        if (!\property_exists($payload, 'sub') || !\property_exists($payload, 'clientKey')) {
39
            throw new JwtException('Token is missing required data.');
40
        }
41
42
        return new Payload($payload->sub, $payload->clientKey);
43
    }
44
}
45