Passed
Push — master ( 557624...00a047 )
by Anton
02:32 queued 11s
created

KeyCommand::perform()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 28
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 3
Metric Value
eloc 15
c 4
b 0
f 3
dl 0
loc 28
rs 9.7666
cc 4
nc 5
nop 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Command\Encrypter;
13
14
use Spiral\Console\Command;
15
use Spiral\Encrypter\EncrypterFactory;
16
use Spiral\Files\FilesInterface;
17
use Symfony\Component\Console\Input\InputOption;
18
19
final class KeyCommand extends Command
20
{
21
    protected const NAME        = 'encrypt:key';
22
    protected const DESCRIPTION = 'Generate new encryption key';
23
    protected const OPTIONS     = [
24
        [
25
            'mount',
26
            'm',
27
            InputOption::VALUE_OPTIONAL,
28
            'Mount encrypter key into given file'
29
        ],
30
        [
31
            'placeholder',
32
            'p',
33
            InputOption::VALUE_OPTIONAL,
34
            'Placeholder of encryption key (will attempt to use current encryption key)',
35
            '{encrypt-key}'
36
        ],
37
    ];
38
39
    /**
40
     * @param EncrypterFactory $enc
41
     * @param FilesInterface   $files
42
     */
43
    public function perform(EncrypterFactory $enc, FilesInterface $files): void
44
    {
45
        $key = $enc->generateKey();
46
47
        $this->sprintf("<info>New encryption key:</info> <fg=cyan>%s</fg=cyan>\n", $key);
48
49
        $file = $this->option('mount');
50
        if ($file === null) {
51
            return;
52
        }
53
54
        if (!$files->exists($file)) {
55
            $this->sprintf('<error>Unable to find `%s`</error>', $file);
56
            return;
57
        }
58
59
        $content = $files->read($file);
60
61
        try {
62
            $content = str_replace($this->option('placeholder'), $key, $content);
63
            $content = str_replace($enc->getKey(), $key, $content);
64
        } catch (\Throwable $e) {
65
            // current keys is not set
66
        }
67
68
        $files->write($file, $content);
69
70
        $this->writeln('<comment>Encryption key has been updated.</comment>');
71
    }
72
}
73