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