Passed
Push — main ( a1448d...532f1f )
by Peter
03:51
created

GenerateKeys::setIsOpenSslAvailable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace AbterPhp\Framework\Console\Commands\Oauth2;
6
7
use Opulence\Console\Commands\Command;
8
use Opulence\Console\Responses\IResponse;
9
10
class GenerateKeys extends Command
11
{
12
    public const NAME = 'oauth2:generatekeys';
13
14
    protected string $privateKeyPassword;
15
16
    protected string $privateKeyPath;
17
18
    protected string $publicKeyPath;
19
20
    protected bool $isOpenSslAvailable = true;
21
22
    /**
23
     * GenerateKeys constructor.
24
     *
25
     * @param string $privateKeyPassword
26
     * @param string $privateKeyPath
27
     * @param string $publicKeyPath
28
     */
29
    public function __construct(string $privateKeyPassword, string $privateKeyPath, string $publicKeyPath)
30
    {
31
        $this->privateKeyPassword = $privateKeyPassword;
32
        $this->privateKeyPath     = $privateKeyPath;
33
        $this->publicKeyPath      = $publicKeyPath;
34
35
        if (!defined('OPENSSL_VERSION_NUMBER')) {
36
            $this->isOpenSslAvailable = false;
37
        }
38
39
        parent::__construct();
40
    }
41
42
    /**
43
     * @param bool $isOpenSslAvailable
44
     *
45
     * @return $this
46
     */
47
    public function setIsOpenSslAvailable(bool $isOpenSslAvailable): self
48
    {
49
        $this->isOpenSslAvailable = $isOpenSslAvailable;
50
51
        return $this;
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57
    protected function define()
58
    {
59
        $this->setName(static::NAME)
60
            ->setDescription('Generates openssl keys');
61
    }
62
63
    /**
64
     * @inheritdoc
65
     */
66
    protected function doExecute(IResponse $response)
67
    {
68
        if (!$this->isOpenSslAvailable) {
69
            $response->writeln('<fatal>OpenSSL is not installed.</fatal>');
70
71
            return;
72
        }
73
74
        $genPrivateKeyCmd = sprintf(
75
            'openssl genrsa -passout pass:%s -out %s 2048 2> /dev/null',
76
            $this->privateKeyPassword,
77
            $this->privateKeyPath
78
        );
79
        $response->writeln(sprintf('<comment>%s</comment>', $genPrivateKeyCmd));
80
        exec($genPrivateKeyCmd);
81
82
        $genPublicKeyCmd = sprintf(
83
            'openssl rsa -in %s -passin pass:%s -pubout -out %s 2> /dev/null',
84
            $this->privateKeyPath,
85
            $this->privateKeyPassword,
86
            $this->publicKeyPath
87
        );
88
        $response->writeln(sprintf('<comment>%s</comment>', $genPublicKeyCmd));
89
        exec($genPublicKeyCmd);
90
91
        chmod($this->privateKeyPath, 0600);
92
        chmod($this->publicKeyPath, 0600);
93
    }
94
}
95