Completed
Push — master ( a1e07d...4890bb )
by Sébastien
03:40
created

JwtServiceFactory::__invoke()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 42
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 42
ccs 27
cts 27
cp 1
rs 8.439
c 0
b 0
f 0
cc 6
eloc 27
nc 8
nop 1
crap 6
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Soluble\Wallit\Service;
6
7
use Psr\Container\ContainerInterface;
8
use Soluble\Wallit\Config\ConfigProvider;
9
use Soluble\Wallit\Exception\ConfigException;
10
use Soluble\Wallit\Token\Jwt\SignatureAlgos;
11
12
class JwtServiceFactory
13
{
14
    public const CONFIG_KEY = 'token-service';
15
16
    /**
17
     * Map signature algorithms.
18
     *
19
     * @var array
20
     */
21
    public static $algosMap = [
22
        SignatureAlgos::HS256 => \Lcobucci\JWT\Signer\Hmac\Sha256::class,
23
        SignatureAlgos::HS384 => \Lcobucci\JWT\Signer\Hmac\Sha384::class,
24
        SignatureAlgos::HS512 => \Lcobucci\JWT\Signer\Hmac\Sha512::class
25
    ];
26
27
    /**
28
     * @param ContainerInterface $container
29
     *
30
     * @return JwtService
31
     *
32
     * @throws ConfigException
33
     */
34 6
    public function __invoke(ContainerInterface $container): JwtService
35
    {
36 6
        $config = $container->has('config') ? $container->get('config') : [];
37
38 6
        $options = $config[ConfigProvider::CONFIG_PREFIX][self::CONFIG_KEY] ?? null;
39
40 6
        if (!is_array($options)) {
41 1
            throw new ConfigException(sprintf(
42 1
                    "Missing or invalid entry ['%s']['%s'] in container configuration.",
43 1
                    ConfigProvider::CONFIG_PREFIX,
44 1
                    self::CONFIG_KEY)
45
            );
46
        }
47
48 5
        $verificationKey = $options['secret'] ?? null;
49 5
        if ($verificationKey === null) {
50 1
            throw new ConfigException(sprintf(
51 1
                "Missing secret key in config (['%s']['%s']['%s'] = '%s')",
52 1
                ConfigProvider::CONFIG_PREFIX,
53 1
                self::CONFIG_KEY,
54 1
                'secret',
55 1
                $verificationKey ?? 'NULL'
56
            ));
57
        }
58
59 4
        $algo = $options['algo'] ?? null;
60 4
        $algoClass = self::$algosMap[$algo] ?? null;
61
62 4
        if ($algoClass === null || !class_exists($algoClass)) {
63 2
            throw new ConfigException(sprintf(
64 2
                "Missing or invalid algorithm in config (['%s']['%s']['%s'] = '%s')",
65 2
                ConfigProvider::CONFIG_PREFIX,
66 2
                self::CONFIG_KEY,
67 2
                'algo',
68 2
                $algo ?? 'NULL'
69
            ));
70
        }
71
72 2
        $jwtService = new JwtService(new $algoClass(), $verificationKey);
73
74 1
        return $jwtService;
75
    }
76
}
77