Passed
Push — master ( 169102...d8a6c3 )
by Ollie
10:08 queued 04:10
created

KeyGenerateCommand::addKeyToEnv()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 6
rs 10
1
<?php
2
3
namespace Sprocketbox\JWT\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Console\ConfirmableTrait;
7
use Illuminate\Support\Str;
8
9
/**
10
 * Class KeyGenerateCommand
11
 *
12
 * @package Sprocketbox\JWT\Commands
13
 */
14
class KeyGenerateCommand extends Command
15
{
16
    use ConfirmableTrait;
17
18
    /**
19
     * The name and signature of the console command.
20
     *
21
     * @var string
22
     */
23
    protected $signature = 'jwt:generate {guard}
24
                    {--length : The length of the key, defaults to 32}
25
                    {--show : Display the key instead of modifying files}
26
                    {--force : Force the operation to run when in production}';
27
28
    /**
29
     * The console command description.
30
     *
31
     * @var string
32
     */
33
    protected $description = 'Set the JWT key for the given guard';
34
35
    /**
36
     * @throws \Exception
37
     */
38
    public function handle(): void
39
    {
40
        $key    = $this->generateRandomKey();
41
        $envKey = 'JWT_KEY_' . strtoupper($this->argument('guard'));
0 ignored issues
show
Bug introduced by
It seems like $this->argument('guard') can also be of type string[]; however, parameter $string of strtoupper() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

41
        $envKey = 'JWT_KEY_' . strtoupper(/** @scrutinizer ignore-type */ $this->argument('guard'));
Loading history...
42
43
        if ($this->option('show')) {
44
            $this->line('<comment>' . $key . '</comment>');
45
46
            return;
47
        }
48
49
        if (! $this->setEnvVariable($envKey, $key)) {
50
            return;
51
        }
52
53
        $this->info('JWT key set successfully for \'' . $this->argument('guard') . '\'.');
0 ignored issues
show
Bug introduced by
Are you sure $this->argument('guard') of type null|string|string[] can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

53
        $this->info('JWT key set successfully for \'' . /** @scrutinizer ignore-type */ $this->argument('guard') . '\'.');
Loading history...
54
    }
55
56
    /**
57
     * Generate a random key for the JWT signing.
58
     *
59
     * @return string
60
     * @throws \Exception
61
     */
62
    protected function generateRandomKey(): string
63
    {
64
        return Str::random($this->option('length') ?: 32);
0 ignored issues
show
Bug introduced by
It seems like $this->option('length') ?: 32 can also be of type string; however, parameter $length of Illuminate\Support\Str::random() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

64
        return Str::random(/** @scrutinizer ignore-type */ $this->option('length') ?: 32);
Loading history...
65
    }
66
67
    /**
68
     * Set the value in the environment file.
69
     *
70
     * @param string $envKey
71
     * @param string $key
72
     *
73
     * @return bool
74
     */
75
    private function setEnvVariable(string $envKey, string $key): bool
76
    {
77
        $currentKey = env($envKey);
78
79
        if (($currentKey !== '' || $currentKey !== null) && ! $this->confirmToProceed()) {
0 ignored issues
show
introduced by
The condition $currentKey !== '' is always true.
Loading history...
80
            return false;
81
        }
82
83
        if ($currentKey !== null) {
84
            $this->replaceKeyInEnv($envKey, $key, $currentKey);
85
        } else {
86
            $this->addKeyToEnv($envKey, $key);
87
        }
88
89
        return true;
90
    }
91
92
    /**
93
     * Replace the old JWT key in the env file.
94
     *
95
     * @param string $envKey
96
     * @param string $key
97
     * @param        $currentKey
98
     */
99
    private function replaceKeyInEnv(string $envKey, string $key, $currentKey): void
100
    {
101
        file_put_contents($this->laravel->environmentFilePath(), preg_replace(
102
            '/^' . preg_quote($envKey . '=' . $currentKey, '/') . '/m',
103
            $envKey . '=' . $key,
104
            file_get_contents($this->laravel->environmentFilePath())
105
        ));
106
    }
107
108
    /**
109
     * Add the JWT key to the env file.
110
     *
111
     * @param string $envKey
112
     * @param string $key
113
     */
114
    private function addKeyToEnv(string $envKey, string $key): void
115
    {
116
        file_put_contents(
117
            $this->laravel->environmentFilePath(),
118
            PHP_EOL . $envKey . '=' . $key . PHP_EOL,
119
            FILE_APPEND
120
        );
121
    }
122
}