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

OpenSSLKeyLoader   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
B loadKey() 0 23 5
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 OpenSSLKeyLoader.
15
 *
16
 * @author Jafar Jabr <[email protected]>
17
 */
18
class OpenSSLKeyLoader extends AbstractKeyLoader
19
{
20
    /**
21
     * {@inheritdoc}
22
     *
23
     * @throws \RuntimeException If the key cannot be read
24
     * @throws \RuntimeException Either the key or the passPhrase is not valid
25
     */
26
    public function loadKey($type)
27
    {
28
        $path         = $this->getKeyPath($type);
29
        $encryptedKey = file_get_contents($path);
30
        $key          = call_user_func_array(
31
            sprintf('openssl_pkey_get_%s', $type),
32
            self::TYPE_PRIVATE == $type ? [$encryptedKey, $this->getPassPhrase()] : [$encryptedKey]
33
        );
34
        if (!$key) {
35
            $sslError = '';
36
            while ($msg = trim(openssl_error_string(), " \n\r\t\0\x0B\"")) {
37
                if ('error:' === substr($msg, 0, 6)) {
38
                    $msg = substr($msg, 6);
39
                }
40
                $sslError .= "\n ".$msg;
41
            }
42
43
            throw new \RuntimeException(
44
                sprintf('Failed to load %s key "%s": %s', $type, $path, $sslError)
45
            );
46
        }
47
48
        return $key;
49
    }
50
}
51