EnvSetCommand   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 81
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 26
c 3
b 0
f 0
dl 0
loc 81
rs 10
wmc 9

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getKeyValue() 0 24 6
A __construct() 0 3 1
A handle() 0 16 2
1
<?php
2
3
namespace msztorc\LaravelEnv\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Str;
7
use InvalidArgumentException;
8
use msztorc\LaravelEnv\Commands\Traits\CommandValidator;
9
use msztorc\LaravelEnv\Env;
10
11
class EnvSetCommand extends Command
12
{
13
    use CommandValidator;
14
15
    /**
16
     * The name and signature of the console command.
17
     *
18
     * @var string
19
     */
20
    protected $signature = 'env:set {key} {value?}';
21
22
    /**
23
     * The console command description.
24
     *
25
     * @var string
26
     */
27
    protected $description = 'Update an environment variable value in .env file';
28
29
    /**
30
     * Create a new command instance.
31
     *
32
     * @return void
33
     */
34
    public function __construct()
35
    {
36
        parent::__construct();
37
    }
38
39
    /**
40
     * Execute the console command.
41
     *
42
     * @return mixed
43
     */
44
    public function handle()
45
    {
46
        try {
47
            [$key, $value] = $this->getKeyValue();
48
49
            $env = new Env();
50
            $env->setValue($key, $value);
51
52
            $this->info("Environment variable with key '{$key}' has been set to '{$value}'");
53
        } catch (\InvalidArgumentException $e) {
54
            $this->error($e->getMessage());
55
56
            return 1;
57
        }
58
59
        return 0;
60
    }
61
62
63
    /**
64
     * Determine what the supplied key and value is from the current command.
65
     *
66
     * @return array
67
     */
68
    protected function getKeyValue(): array
69
    {
70
        $key = $this->argument('key');
71
        $value = $this->argument('value');
72
73
        if (is_null($value) || !$value) {
74
            $parts = explode('=', (string)$key, 2);
75
76
            if (count($parts) !== 2) {
77
                throw new InvalidArgumentException('No value was set');
78
            }
79
80
            [$key, $value] = $parts;
81
        }
82
83
        if (Str::contains((string)$key, '=')) {
84
            throw new InvalidArgumentException("Environment key should not contain '='");
85
        }
86
87
        if (!$this->isValidKey((string)$key)) {
88
            throw new InvalidArgumentException('Invalid argument key');
89
        }
90
91
        return [(string)$key, (string)$value];
92
    }
93
}
94