Passed
Push — master ( 90db0f...396226 )
by Jafar
03:16
created

AbstractKeyLoader::getKeyPath()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 17
nc 9
nop 1
dl 0
loc 27
rs 8.439
c 0
b 0
f 0
1
<?php
2
/*
3
 * This file is part of the Guarded Authentication package.
4
 *
5
 * (c) Jafar Jabr <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Jafar\Bundle\GuardedAuthenticationBundle\Api\KeyLoader;
12
13
/**
14
 * Class AbstractKeyLoader.
15
 *
16
 * @author Jafar Jabr <[email protected]>
17
 */
18
abstract class AbstractKeyLoader implements KeyLoaderInterface
19
{
20
    const TYPE_PUBLIC = 'public';
21
22
    const TYPE_PRIVATE = 'private';
23
24
    /**
25
     * @var string
26
     */
27
    private $privateKey;
28
29
    /**
30
     * @var string
31
     */
32
    private $publicKey;
33
34
    /**
35
     * @var string
36
     */
37
    private $passPhrase;
38
39
    /**
40
     * AbstractKeyLoader constructor.
41
     *
42
     * @param string $passPhrase
43
     * @param string $keys_dir
44
     */
45
    public function __construct(string $passPhrase, string $keys_dir)
46
    {
47
        $this->privateKey = $keys_dir.'private.pem';
48
        $this->publicKey  = $keys_dir.'public.pem';
49
        $this->passPhrase = $passPhrase;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getPassPhrase()
56
    {
57
        return $this->passPhrase;
58
    }
59
60
    /**
61
     * @param string $type One of "public" or "private"
62
     *
63
     * @return null|string The path of the key
64
     *
65
     * @throws \InvalidArgumentException If the given type is not valid
66
     */
67
    protected function getKeyPath($type)
68
    {
69
        if (!in_array($type, [self::TYPE_PUBLIC, self::TYPE_PRIVATE])) {
70
            throw new \InvalidArgumentException(
71
                sprintf('The key type must be "public" or "private", "%s" given.', $type)
72
            );
73
        }
74
        $path = null;
75
        if (self::TYPE_PUBLIC === $type) {
76
            $path = $this->publicKey;
77
        }
78
        if (self::TYPE_PRIVATE === $type) {
79
            $path = $this->privateKey;
80
        }
81
        if (!is_file($path) || !is_readable($path)) {
82
            throw new \RuntimeException(
83
                sprintf(
84
                    '%s key "%s" does not exist or is not readable. 
85
                    Please run jafar:generate-keys again to regenerate the kys!',
86
                    ucfirst($type),
87
                    $path,
88
                    $type
89
                )
90
            );
91
        }
92
93
        return $path;
94
    }
95
}
96