CheckEarlyReturns::handle()   C
last analyzed

Complexity

Conditions 15
Paths 42

Size

Total Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
nc 42
nop 0
dl 0
loc 52
rs 5.9166
c 0
b 0
f 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 Imanghafoori\LaravelMicroscope\Commands;
4
5
use Illuminate\Console\Command;
6
use Imanghafoori\LaravelMicroscope\Analyzers\ComposerJson;
7
use Imanghafoori\LaravelMicroscope\Analyzers\Refactor;
8
use Imanghafoori\LaravelMicroscope\ErrorReporters\ErrorPrinter;
9
use Imanghafoori\LaravelMicroscope\LaravelPaths\FilePath;
10
11
class CheckEarlyReturns extends Command
12
{
13
    protected $signature = 'check:early_returns {--t|test : backup the changed files} {--s|nofix}';
14
15
    protected $description = 'Applies the early return on the classes';
16
17
    public function handle()
18
    {
19
        if ($this->option('nofix')) {
20
            $this->info(PHP_EOL.' Checking for possible code flattenings...'.PHP_EOL);
21
        }
22
23
        if (! $this->option('nofix') && ! $this->startWarning()) {
24
            return;
25
        }
26
27
        $psr4 = ComposerJson::readAutoload();
28
29
        $fixingFilesCount = $totalNumberOfFixes = $fixedFilesCount = 0;
30
        foreach ($psr4 as $psr4Namespace => $psr4Path) {
31
            $files = FilePath::getAllPhpFiles($psr4Path);
32
            foreach ($files as $file) {
33
                $path = $file->getRealPath();
34
                $tokens = token_get_all(file_get_contents($path));
35
                if (empty($tokens) || $tokens[0][0] !== T_OPEN_TAG) {
36
                    continue;
37
                }
38
39
                try {
40
                    [$fixes, $tokens] = $this->refactor($tokens);
0 ignored issues
show
Bug introduced by
The variable $fixes does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
41
                } catch (\Exception $e) {
42
                    dump('(O_o)   Well, It seems we had some problem parsing the contents of:  (O_o)');
43
                    dump('Skipping : '.$path);
44
                    continue;
45
                }
46
47
                $fixes !== 0 && $fixingFilesCount++;
48
49
                if ($this->option('nofix') && $fixes !== 0) {
50
                    $filePath = FilePath::getRelativePath($path);
51
                    $this->line("<fg=red>    - $filePath</fg=red>");
52
                    continue;
53
                }
54
55
                if ($fixes == 0 || ! $this->getConfirm($path)) {
56
                    continue;
57
                }
58
59
                $this->fix($path, $tokens, $fixes);
60
                $fixedFilesCount++;
61
                $totalNumberOfFixes += $fixes;
62
            }
63
        }
64
65
        $this->printFinalMsg($fixedFilesCount, $fixingFilesCount);
66
67
        return app(ErrorPrinter::class)->hasErrors() ? 1 : 0;
68
    }
69
70
    private function fix($filePath, $tokens, $tries)
71
    {
72
        Refactor::saveTokens($filePath, $tokens, $this->option('test'));
73
74
        $this->warn(PHP_EOL.$tries.' fixes applied to: '.class_basename($filePath));
75
    }
76
77
    private function refactor($tokens)
78
    {
79
        $fixes = 0;
80
        do {
81
            [$tokens, $refactored] = Refactor::flatten($tokens);
82
        } while ($refactored > 0 && $fixes++);
0 ignored issues
show
Bug introduced by
The variable $refactored does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
83
84
        return [$fixes, $tokens];
85
    }
86
87
    private function printFinalMsg($fixed, $fixingFilesCount)
88
    {
89
        if ($fixed > 0) {
90
            $msg = ' Hooraay!!!, '.$fixed.' files were flattened by laravel-microscope!';
91
        } elseif ($fixingFilesCount == 0) {
92
            $msg = ' Congratulations, your code base does not seems to need any flattening. <fg=red> \(^_^)/ </fg=red>';
93
        } elseif ($fixingFilesCount !== 0 && $this->option('nofix')) {
94
            $msg = ' The files above can be flattened by: <fg=cyan>php artisan check:early</fg=cyan>';
95
        }
96
97
        isset($msg) && $this->info(PHP_EOL.$msg);
98
        $this->info(PHP_EOL);
99
        $this->line('========================================');
100
    }
101
102
    private function getConfirm($filePath)
103
    {
104
        $filePath = FilePath::getRelativePath($filePath);
105
106
        return $this->output->confirm(' Do you want to flatten: '.$filePath, true);
107
    }
108
109
    private function startWarning()
110
    {
111
        $this->info(PHP_EOL.' Checking for Early Returns...');
112
        $this->warn(' Warning: This command is going to make "CHANGES" to your files!');
113
114
        return $this->output->confirm(' Do you have committed everything in git?', false);
115
    }
116
}
117