Completed
Push — master ( b8b92e...ffbaab )
by Alex
80:13 queued 80:07
created

CryptKey::__construct()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 13
rs 9.2
cc 4
eloc 7
nc 4
nop 2
1
<?php
2
/**
3
 * Cryptography key holder.
4
 *
5
 * @author      Julián Gutiérrez <[email protected]>
6
 * @copyright   Copyright (c) Alex Bilbie
7
 * @license     http://mit-license.org/
8
 *
9
 * @link        https://github.com/thephpleague/oauth2-server
10
 */
11
12
namespace League\OAuth2\Server;
13
14
class CryptKey
15
{
16
    /**
17
     * @var string
18
     */
19
    protected $keyPath;
20
21
    /**
22
     * @var null|string
23
     */
24
    protected $passPhrase;
25
26
    /**
27
     * @param string $keyPath
28
     * @param null|string $passPhrase
29
     */
30
    public function __construct($keyPath, $passPhrase = null)
31
    {
32
        if (strpos($keyPath, '://') === false) {
33
            $keyPath = 'file://' . $keyPath;
34
        }
35
36
        if (!file_exists($keyPath) || !is_readable($keyPath)) {
37
            throw new \LogicException(sprintf('Key path "%s" does not exist or is not readable', $keyPath));
38
        }
39
40
        $this->keyPath = $keyPath;
41
        $this->passPhrase = $passPhrase;
42
    }
43
44
    /**
45
     * Retrieve key path.
46
     *
47
     * @return string
48
     */
49
    public function getKeyPath()
50
    {
51
        return $this->keyPath;
52
    }
53
54
    /**
55
     * Retrieve key pass phrase.
56
     *
57
     * @return null|string
58
     */
59
    public function getPassPhrase()
60
    {
61
        return $this->passPhrase;
62
    }
63
64
    /**
65
     * @param $key
66
     * @param null $passPhrase
67
     * @return CryptKey
68
     */
69
    public static function fromString($key, $passPhrase = null)
70
    {
71
        $keyPath = sys_get_temp_dir() . '/' . sha1($key) . '.key';
72
73
        if (!file_exists($keyPath) && !touch($keyPath)) {
74
            // @codeCoverageIgnoreStart
75
            throw new \RuntimeException('"%s" key file could not be created', $keyPath);
76
            // @codeCoverageIgnoreEnd
77
        }
78
79
        file_put_contents($keyPath, $key);
80
81
        return new static('file://' . $keyPath, $passPhrase);
82
    }
83
}
84