InstallCommand::setupEnv()   F
last analyzed

Complexity

Conditions 26
Paths > 20000

Size

Total Lines 121
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 80
c 1
b 0
f 0
dl 0
loc 121
rs 0
cc 26
nc 24000
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Ijeffro\LaraLocker\Commands;
4
5
use Laralocker;
6
use Illuminate\Console\Command;
7
use Illuminate\Filesystem\Filesystem;
8
use Symfony\Component\Process\Process;
9
use Symfony\Component\Console\Input\InputOption;
10
use Ijeffro\LaraLocker\LaraLockerServiceProvider;
0 ignored issues
show
Bug introduced by
The type Ijeffro\LaraLocker\LaraLockerServiceProvider was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
use Ijeffro\Laralocker\LearningLocker\API\APIHandler;
12
use Ijeffro\Laralocker\Constants\LearningLockerConstants;
13
14
class InstallCommand extends Command
15
{
16
    /**
17
     * The console command name.
18
     *
19
     * @var string
20
     */
21
    protected $name = 'laralocker:setup';
22
23
    /**
24
     * The console command signature.
25
     *
26
     * @var string
27
     */
28
    protected $signature = 'laralocker:setup {--routes : Setup Learning Locker® Endpooints.}
29
                                             {--client : Setup a Learning Locker® Client.}';
30
31
    /**
32
     * The console command description.
33
     *
34
     * @var string
35
     */
36
    protected $description = 'Setup LaraLocker - Learning Locker® package for Laravel';
37
38
    const API_ROUTE = 'api.php';
39
    const WEB_ROUTE = 'web.php';
40
    const CONSOLE_ROUTE = 'console.php';
41
    const CHANNELS_ROUTE = 'channels.php';
42
43
    protected $seedersPath = __DIR__.'/../../publishable/database/seeds/';
44
    protected $migrationsPath = __DIR__.'/../../publishable/database/migrations/';
45
46
    protected function getOptions()
47
    {
48
        return [
49
            ['client', null, InputOption::VALUE_NONE, 'Setup a Learning Locker® Client', null],
50
            ['routes', null, InputOption::VALUE_NONE, 'Setup a Learning Locker® Endpooints', null],
51
        ];
52
    }
53
54
    public function fire(Filesystem $filesystem)
55
    {
56
        return $this->handle($filesystem);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->handle($filesystem) targeting Ijeffro\LaraLocker\Comma...nstallCommand::handle() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
57
    }
58
59
    /**
60
     * Execute the console command.
61
     *
62
     * @param \Illuminate\Filesystem\Filesystem $filesystem
63
     *
64
     * @return void
65
     */
66
    public function handle(Filesystem $filesystem)
67
    {
68
        $this->info("Setup LaraLocker - A Learning Locker® package for Laravel...\n");
69
70
        $this->setupLaravelRouting($filesystem);
71
72
        // $this->setupLearningLockerClient();
73
74
        return $this->info("Successfully setup LaraLocker! Enjoy Learning Locker®");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->info('Successfull...joy Learning Locker®') targeting Illuminate\Console\Command::info() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
75
76
        // $this->call('learninglocker:client', ['--setup' => true]);
77
        // $this->setupMigrationFiles();
78
79
        // $this->info('Migrating the database tables into your application');
80
        // $this->call('migrate', ['--force' => $this->option('force')]);
81
82
        // $composer = $this->findComposer();
83
        // $process = new Process($composer.' dump-autoload');
84
85
        // $process->setTimeout(null); // Setting timeout to null
86
        // $process->setWorkingDirectory(base_path())->run();
87
88
        // $this->info('Seeding data into the database');
89
        // $this->seed('LaraLockerDatabaseSeeder');
90
91
        $this->publishVendor();
0 ignored issues
show
Unused Code introduced by
$this->publishVendor() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
92
93
        // $this->checkLearningLockerConnection();
94
    }
95
96
    /**
97
     * Setup Learning Locker® Endpoints
98
     *
99
     * @param Filesystem $filesystem
100
     * @return void
101
     */
102
    public function setupLaravelRouting(Filesystem $filesystem) {
103
        if ($this->confirm("Add the default Learning Locker® endpoints to your Laravel routes file?", true)) {
104
105
            $route_files = array_slice(scandir(base_path('routes')), 2);
0 ignored issues
show
Bug introduced by
It seems like scandir(base_path('routes')) can also be of type false; however, parameter $array of array_slice() does only seem to accept array, 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

105
            $route_files = array_slice(/** @scrutinizer ignore-type */ scandir(base_path('routes')), 2);
Loading history...
106
            $file_choice = $this->choice('Which route file?', $route_files);
107
108
            switch ($file_choice) {
109
                case self::API_ROUTE:
110
111
                $this->addLearningLockerRouting($filesystem, self::API_ROUTE);
112
            break;
113
                case self::WEB_ROUTE:
114
                $this->addLearningLockerRouting($filesystem, self::WEB_ROUTE);
115
            break;
116
                case self::CONSOLE_ROUTE:
117
                $this->addLearningLockerRouting($filesystem, self::CONSOLE_ROUTE);
118
            break;
119
                case self::CHANNELS_ROUTE:
120
                $this->addLearningLockerRouting($filesystem, self::CHANNELS_ROUTE);
121
            break;
122
            default:
123
                $this->error('Could not find the Laravel route file...'); echo "\n";
124
125
                if ($this->confirm("Would you like to try again?", true)) {
126
                    return $this->setupLaravelRouting($filesystem);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->setupLaravelRouting($filesystem) targeting Ijeffro\LaraLocker\Comma...::setupLaravelRouting() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
127
                }
128
            }
129
130
        }
131
    }
132
133
134
    public function setupLearningLockerClient() {
135
        return $this->call('learninglocker:client', ['--setup' => true]);
136
    }
137
138
    /**
139
     * Setup Learning Locker® Environment Variables
140
     *
141
     * @return LEARNING_LOCKER_URL
0 ignored issues
show
Bug introduced by
The type Ijeffro\LaraLocker\Commands\LEARNING_LOCKER_URL was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
142
     * @return LEARNING_LOCKER_KEY
143
     * @return LEARNING_LOCKER_SECRET
144
     */
145
    public function setupEnv() {
146
        $env = base_path('.env');
147
        $filesystem = new Filesystem;
148
        $env_contents = $filesystem->get($env);
149
150
        $learning_locker_url = getEnv(strtoupper(LearningLockerConstants::URL));
151
        $learning_locker_key = getEnv(strtoupper(LearningLockerConstants::KEY));
152
        $learning_locker_secret = getEnv(strtoupper(LearningLockerConstants::SECRET));
153
154
        // Has variable and value
155
        $url_has_variable_and_value = isset($learning_locker_url) && !empty($learning_locker_url);
156
        $key_has_variable_and_value = isset($learning_locker_key) && !empty($learning_locker_key);
157
        $secret_has_variable_and_value = isset($learning_locker_secret) && !empty($learning_locker_secret);
158
159
        // Has variable with no value
160
        $url_has_variable_with_no_value = false !== strpos($env_contents, strtoupper(LearningLockerConstants::URL)) && empty($learning_locker_url);
161
        $key_has_variable_with_no_value = false !== strpos($env_contents, strtoupper(LearningLockerConstants::KEY)) && empty($learning_locker_key);
162
        $secret_has_variable_with_no_value = false !== strpos($env_contents, strtoupper(LearningLockerConstants::SECRET)) && empty($learning_locker_secret);
163
164
        // Has no variable and no value
165
        $url_has_no_variable_and_no_value = true !== strpos($env_contents, strtoupper(LearningLockerConstants::URL));
166
        $key_has_no_variable_and_no_value = true !== strpos($env_contents, strtoupper(LearningLockerConstants::KEY));
167
        $secret_has_no_variable_and_no_value = true !== strpos($env_contents, strtoupper(LearningLockerConstants::SECRET));
168
169
        // Do the env smarts
170
        if ($url_has_variable_and_value && $key_has_variable_and_value && $secret_has_variable_and_value) {
171
172
            if ($this->confirm('Update Learning Locker® api connection?')) {
173
                $domain = $this->anticipate("What's the new Learning Locker® url?", [
174
                    'https://saas.learninglocker.net', 'http://saas.learninglocker.net'
175
                ]);
176
                $this->setEnv([strtoupper(LearningLockerConstants::URL) => $domain]);
177
178
                $key = $this->ask("What's the new Learning Locker® client key?");
179
                $this->setEnv([strtoupper(LearningLockerConstants::KEY) => $key]);
180
181
                $secret = $this->secret("What's the new Learning Locker® client secret");
182
                $this->setEnv([strtoupper(LearningLockerConstants::SECRET) => $secret]);
183
            }
184
185
        } else {
186
            try {
187
188
                // Check .env for Learning Locker® url status
189
                switch (file_exists($env)) {
190
                    case $url_has_variable_and_value:
191
                        if ($this->confirm('Update Learning Locker® domain?')) {
192
                            $domain = $this->anticipate("What's the new Learning Locker® domain?", [
193
                                'https://saas.learninglocker.net', 'http://saas.learninglocker.net'
194
                            ]);
195
                            $this->setEnv([strtoupper(LearningLockerConstants::URL) => $domain]);
196
                        }
197
                        break;
198
                    case $url_has_variable_with_no_value:
199
                            $domain = $this->anticipate("What's your Learning Locker® url?", [
200
                                'https://saas.learninglocker.net', 'http://saas.learninglocker.net'
201
                            ]);
202
                            $this->setEnv([strtoupper(LearningLockerConstants::URL) => $domain]);
203
                        break;
204
                    case $url_has_no_variable_and_no_value:
205
                            $domain = $this->anticipate("What's your Learning Locker® url?", [
206
                                'https://saas.learninglocker.net', 'http://saas.learninglocker.net'
207
                            ]);
208
                            $this->createEnv(strtoupper(LearningLockerConstants::URL), $domain);
209
                        break;
210
                }
211
212
                // Check .env for Learning Locker® client key status
213
                switch (file_exists($env)) {
214
                    case $key_has_variable_and_value:
215
                        if ($this->confirm('Update Learning Locker® client key?')) {
216
                            $key = $this->ask("What's the new Learning Locker® client key?");
217
                            $this->setEnv([strtoupper(LearningLockerConstants::KEY) => $key]);
218
                        }
219
                        break;
220
                    case $key_has_variable_with_no_value:
221
                            $key = $this->ask("What's your Learning Locker® client key?");
222
                            $this->setEnv([strtoupper(LearningLockerConstants::KEY) => $key]);
223
                        break;
224
                    case $key_has_no_variable_and_no_value:
225
                            $key = $this->ask("What's your Learning Locker® client key?");
226
                            $this->createEnv(strtoupper(LearningLockerConstants::KEY), $key);
227
                        break;
228
                }
229
230
                // Check .env for Learning Locker® client secret status
231
                switch (file_exists($env)) {
232
                    case $secret_has_variable_and_value:
233
                        if ($this->confirm('Update Learning Locker® client secret?')) {
234
                            $secret = $this->secret("What's the new Learning Locker® client secret");
0 ignored issues
show
Unused Code introduced by
The assignment to $secret is dead and can be removed.
Loading history...
235
                            $this->setEnv([strtoupper(LearningLockerConstants::KEY) => $key]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key does not seem to be defined for all execution paths leading up to this point.
Loading history...
236
                        }
237
                        break;
238
                    case $secret_has_variable_with_no_value:
239
                            $secret = $this->secret("What's your Learning Locker® client secret");
240
                            $this->setEnv([strtoupper(LearningLockerConstants::KEY) => $secret]);
241
                        break;
242
                    case $secret_has_no_variable_and_no_value:
243
                            $secret = $this->secret("What's your Learning Locker® client secret");
244
                            $this->createEnv(strtoupper(LearningLockerConstants::SECRET), $secret);
245
                        break;
246
                }
247
248
            } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The type Ijeffro\LaraLocker\Commands\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
249
                return $e->getMessage();
250
            }
251
        }
252
253
        return $this->info(" << Connecting to Learning Locker®...");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->info(' << Connect... Learning Locker®...') targeting Illuminate\Console\Command::info() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug Best Practice introduced by
The expression return $this->info(' << ... Learning Locker®...') returns the type void which is incompatible with the documented return type Ijeffro\LaraLocker\Commands\LEARNING_LOCKER_URL.
Loading history...
254
255
        $connectionCheck = \LearningLocker::connection()->check(env(strtoupper(LearningLockerConstants::URL)));
0 ignored issues
show
Unused Code introduced by
$connectionCheck = Learn...LockerConstants::URL))) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
256
257
        if ($connectionCheck) {
258
            return $this->info(" << Connected to Learning Locker® Succussfully");
259
        }
260
261
        if ($this->confirm('Try updating Learning Locker® details again?')) {
262
            return $this->setupEnv();
263
        }
264
265
        return $this->error("Unable to connection with Learning Locker®");
266
    }
267
268
    /**
269
     * Get the composer command for the environment.
270
     *
271
     * @return string
272
     */
273
    protected function findComposer()
274
    {
275
        if (file_exists(getcwd().'/composer.phar')) {
276
            return '"'.PHP_BINARY.'" '.getcwd().'/composer.phar';
277
        }
278
279
        return 'composer';
280
    }
281
282
    public function addLearningLockerRouting(Filesystem $filesystem, $type)
283
    {
284
        $routes_contents = $filesystem->get(base_path('routes/' . $type));
285
286
        if (false === strpos($routes_contents, 'LearningLocker::routes()')) {
287
            if ($this->confirm('Create Laravel ' . $type . ' routes?')) {
288
                $filesystem->append(base_path('routes/' . $type), "\nLearningLocker::routes();\n");
289
                $this->info('Succesfully added Learning Locker® endpoints to laravel routes/' . $type);
290
            }
291
        } else {
292
            return $this->line('LearningLocker::routes() were already added to ' . $type . "\n");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->line('LearningLoc...ded to ' . $type . ' ') targeting Illuminate\Console\Command::line() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
293
        }
294
    }
295
296
    public function publishVendor()
297
    {
298
        $tags = ['config'];
299
        $this->call('vendor:publish', ['--provider' => LaraLockerServiceProvider::class, '--tag' => $tags]);
300
    }
301
302
    public function checkLearningLockerConnection()
303
    {
304
305
        $this->learning_locker_api = new APIHandler;
0 ignored issues
show
Bug Best Practice introduced by
The property learning_locker_api does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
306
307
        if ($this->learning_locker_api->check()) {
0 ignored issues
show
Bug introduced by
The method check() does not exist on Ijeffro\Laralocker\LearningLocker\API\APIHandler. ( Ignorable by Annotation )

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

307
        if ($this->learning_locker_api->/** @scrutinizer ignore-call */ check()) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
308
            $this->info('Successfully connected to Learning Locker®');
309
        } else {
310
           return $this->error(' << Could not connect to Learning Locker® ');
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->error(' << Could ...to Learning Locker® ') targeting Illuminate\Console\Command::error() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
311
        }
312
313
    }
314
315
    /**
316
     * Get a Laralocker env variable
317
     *
318
     */
319
    public function getEnv($key = null)
320
    {
321
        $env = base_path('.env');
322
323
        if (file_exists($env) && !is_null($key)) {
324
            return env($key);
325
        }
326
327
        if (file_exists($env) && is_null($key)) {
328
            $env_variables = parse_ini_file($env, true, INI_SCANNER_RAW);
329
            return $env_variables;
330
        }
331
332
    }
333
334
    /**
335
     * Set the Laralocker env variables
336
     *
337
     */
338
    public function setEnv($data)
339
    {
340
        $env = base_path('.env');
341
        $variables = array_keys($data);
342
343
        if (file_exists($env)) {
344
            foreach ($variables as $variable) {
345
                $env_variable = $this->getEnv($variable);
346
                $contents = file_get_contents($env);
347
                $contents = str_replace(strtoupper($variable) . '=' . $env_variable, strtoupper($variable) . '=' . $data[$variable], $contents);
348
                file_put_contents($env, $contents);
349
            }
350
        }
351
    }
352
353
    /**
354
     * Create a Laralocker env variable
355
     *
356
     */
357
    public function createEnv($key, $value)
358
    {
359
        $env = base_path('.env');
360
361
        if (file_exists($env)) {
362
363
            $filesystem = new Filesystem;
364
            $env_contents = $filesystem->get($env);
365
366
            if (false === strpos($env_contents, $key)) {
367
                $filesystem->append($env, "\n" . strtoupper($key) . '=' .  strtolower($value));
368
                return $this->info("Created Environment variable $value successfully.");
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->info('Created Env...value.' successfully.') targeting Illuminate\Console\Command::info() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
369
            }
370
        }
371
    }
372
373
374
}
375