OpenSSLKeyLoader::loadKey()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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