CleanUpModelsCommand   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 141
Duplicated Lines 17.02 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 10
dl 24
loc 141
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A handle() 0 14 1
A getModelsThatShouldBeCleanedUp() 12 12 1
A getModelsThatShouldBeForcedCleanedUp() 12 12 1
A getAllModelsFromEachDirectory() 0 8 1
A cleanUp() 0 12 1
A forceCleanUp() 0 12 1
A getFullyQualifiedClassNameFromFile() 0 23 1
A getClassNamesInDirectory() 0 16 2

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Spatie\ModelCleanup;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Support\Collection;
7
use Illuminate\Filesystem\Filesystem;
8
use PhpParser\Node\Stmt\Class_;
9
use PhpParser\NodeTraverser;
10
use PhpParser\ParserFactory;
11
use PhpParser\NodeVisitor\NameResolver;
12
13
class CleanUpModelsCommand extends Command
14
{
15
    /**
16
     * The console command name.
17
     *
18
     * @var string
19
     */
20
    protected $signature = 'clean:models';
21
    /**
22
     * The console command description.
23
     *
24
     * @var string
25
     */
26
    protected $description = 'Clean up models.';
27
28
    protected $filesystem;
29
30
    public function __construct(Filesystem $filesystem)
31
    {
32
        parent::__construct();
33
34
        $this->filesystem = $filesystem;
35
    }
36
37
    public function handle()
38
    {
39
        $this->comment('Cleaning models...');
40
41
        // Cleaning Normal models
42
        $cleanableModels = $this->getModelsThatShouldBeCleanedUp();
43
        $this->cleanUp($cleanableModels);
44
45
        // Cleaning softdeletes models
46
        $cleanableModels = $this->getModelsThatShouldBeForcedCleanedUp();
47
        $this->forceCleanUp($cleanableModels);
48
49
        $this->comment('All done!');
50
    }
51
52 View Code Duplication
    protected function getModelsThatShouldBeCleanedUp() : Collection
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
53
    {
54
        $directories = config('model-cleanup.directories');
55
56
        $modelsFromDirectories = $this->getAllModelsFromEachDirectory($directories);
57
58
        return $modelsFromDirectories
59
            ->merge(collect(config('model-cleanup.models')))
60
            ->filter(function ($modelClass) {
61
                return in_array(GetsCleanedUp::class, class_implements($modelClass));
62
            });
63
    }
64
65 View Code Duplication
    protected function getModelsThatShouldBeForcedCleanedUp() : Collection
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
66
    {
67
        $directories = config('model-cleanup.directories');
68
69
        $modelsFromDirectories = $this->getAllModelsFromEachDirectory($directories);
70
71
        return $modelsFromDirectories
72
            ->merge(collect(config('model-cleanup.models')))
73
            ->filter(function ($modelClass) {
74
                return in_array(GetsForcedCleanedUp::class, class_implements($modelClass));
75
            });
76
    }
77
78
    protected function cleanUp(Collection $cleanableModels)
79
    {
80
        $cleanableModels->each(function (string $modelClass) {
81
82
            $numberOfDeletedRecords = $modelClass::cleanUp($modelClass::query())->delete();
83
84
            event(new ModelWasCleanedUp($modelClass, $numberOfDeletedRecords));
85
86
            $this->info("Deleted {$numberOfDeletedRecords} record(s) from {$modelClass}.");
87
88
        });
89
    }
90
91
    protected function forceCleanUp(Collection $cleanableModels)
92
    {
93
        $cleanableModels->each(function (string $modelClass) {
94
95
            $numberOfDeletedRecords = $modelClass::forceCleanUp($modelClass::query())->forceDelete();
96
97
            event(new ModelWasCleanedUp($modelClass, $numberOfDeletedRecords));
98
99
            $this->info("Deleted {$numberOfDeletedRecords} record(s) from {$modelClass}.");
100
101
        });
102
    }
103
104
    protected function getAllModelsFromEachDirectory(array $directories) : Collection
105
    {
106
        return collect($directories)
107
            ->map(function ($directory) {
108
                return $this->getClassNamesInDirectory($directory)->all();
109
            })
110
            ->flatten();
111
    }
112
113
    protected function getClassNamesInDirectory(string $directory) : Collection
114
    {
115
        $files = config('model-cleanup.recursive', true)
116
            ? $this->filesystem->allFiles($directory)
117
            : $this->filesystem->files($directory);
118
119
        return collect($files)->map(function (string $path) {
120
121
            return $this->getFullyQualifiedClassNameFromFile($path);
122
123
        })->filter(function (string $className) {
124
125
            return !empty($className);
126
127
        });
128
    }
129
130
    protected function getFullyQualifiedClassNameFromFile(string $path) : string
131
    {
132
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
133
134
        $traverser = new NodeTraverser();
135
136
        $traverser->addVisitor(new NameResolver());
137
138
        $code = file_get_contents($path);
139
140
        $statements = $parser->parse($code);
141
142
        $statements = $traverser->traverse($statements);
0 ignored issues
show
Bug introduced by
It seems like $statements can also be of type null; however, PhpParser\NodeTraverser::traverse() does only seem to accept array<integer,object<PhpParser\Node>>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
143
144
        return collect($statements[0]->stmts)
0 ignored issues
show
Bug introduced by
Accessing stmts on the interface PhpParser\Node suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
145
            ->filter(function ($statement) {
146
                return $statement instanceof Class_;
147
            })
148
            ->map(function (Class_ $statement) {
149
                return $statement->namespacedName->toString();
150
            })
151
            ->first() ?? '';
152
    }
153
}
154