Passed
Push — master ( 99d0e8...9e7049 )
by Ondra
03:35
created

AbstractKey   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 92.86%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 46
ccs 13
cts 14
cp 0.9286
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getContent() 0 8 2
A verifyFile() 0 4 3
A __construct() 0 4 1
A getKey() 0 7 2
1
<?php
2
3
/**
4
 * This file is part of the Pixidos package.
5
 *
6
 *  (c) Ondra Votava <[email protected]>
7
 *
8
 *  For the full copyright and license information, please view the LICENSE
9
 *  file that was distributed with this source code.
10
 *
11
 */
12
13
declare(strict_types=1);
14
15
namespace Pixidos\GPWebPay\Signer\Key;
16
17
use OpenSSLAsymmetricKey;
18
use Pixidos\GPWebPay\Exceptions\InvalidArgumentException;
19
use Pixidos\GPWebPay\Exceptions\SignerException;
20
21
abstract class AbstractKey
22
{
23
    protected OpenSSLAsymmetricKey|null $key = null;
24
25
    /**
26
     * @param string $file
27
     * @throws InvalidArgumentException
28
     */
29 25
    public function __construct(
30
        protected readonly string $file
31
    ) {
32 25
        $this->verifyFile($file);
33
    }
34
35
36 20
    public function getKey(): OpenSSLAsymmetricKey
37
    {
38 20
        if (null !== $this->key) {
39 13
            return $this->key;
40
        }
41
42 20
        return $this->key = $this->createKey();
43
    }
44
45
    /**
46
     * @param string $file
47
     * @throws InvalidArgumentException
48
     */
49 25
    protected function verifyFile(string $file): void
50
    {
51 25
        if (!file_exists($file) || !is_readable($file)) {
52 1
            throw new InvalidArgumentException(sprintf('Key file (%s) not exists or not readable!', $file));
53
        }
54
    }
55
56 19
    protected function getContent(): string
57
    {
58 19
        $content = file_get_contents($this->file);
59 19
        if (false === $content) {
60
            throw new SignerException(sprintf('Failed open file with key "%s"', $this->file));
61
        }
62
63 19
        return $content;
64
    }
65
66
    abstract protected function createKey(): OpenSSLAsymmetricKey;
67
}
68