AbstractKeyLoader::getKeyPath()   A
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
c 1
b 0
f 0
nc 9
nop 1
dl 0
loc 18
rs 9.2222
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
use InvalidArgumentException;
14
use RuntimeException;
15
16
/**
17
 * Class AbstractKeyLoader.
18
 *
19
 * @author Jafar Jabr <[email protected]>
20
 */
21
abstract class AbstractKeyLoader implements KeyLoaderInterface
22
{
23
    const TYPE_PUBLIC = 'public';
24
25
    const TYPE_PRIVATE = 'private';
26
27
    /**
28
     * @var string
29
     */
30
    private $privateKey;
31
32
    /**
33
     * @var string
34
     */
35
    private $publicKey;
36
37
    /**
38
     * @var string
39
     */
40
    private $passPhrase;
41
42
    /**
43
     * AbstractKeyLoader constructor.
44
     *
45
     * @param string $passPhrase
46
     * @param string $keys_dir
47
     */
48
    public function __construct(string $passPhrase, string $keys_dir)
49
    {
50
        $this->privateKey = $keys_dir.'private.pem';
51
        $this->publicKey  = $keys_dir.'public.pem';
52
        $this->passPhrase = $passPhrase;
53
    }
54
55
    /**
56
     * {@inheritdoc}
57
     */
58
    public function getPassPhrase()
59
    {
60
        return $this->passPhrase;
61
    }
62
63
    /**
64
     * @param string $type One of "public" or "private"
65
     *
66
     * @return null|string The path of the key
67
     *
68
     * @throws InvalidArgumentException If the given type is not valid
69
     */
70
    protected function getKeyPath($type)
71
    {
72
        if (!in_array($type, [self::TYPE_PUBLIC, self::TYPE_PRIVATE])) {
73
            throw new InvalidArgumentException(sprintf('The key type must be "public" or "private", "%s" given.', $type));
74
        }
75
        $path = null;
76
        if (self::TYPE_PUBLIC === $type) {
77
            $path = $this->publicKey;
78
        }
79
        if (self::TYPE_PRIVATE === $type) {
80
            $path = $this->privateKey;
81
        }
82
        if (!is_file($path) || !is_readable($path)) {
83
            throw new RuntimeException(sprintf('%s key "%s" does not exist or is not readable. 
84
            Please run jafar:generate-keys again to regenerate the kys!', ucfirst($type), $path));
85
        }
86
87
        return $path;
88
    }
89
}
90