Completed
Pull Request — master (#5)
by
unknown
02:04
created

CleanUpModelsCommand   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 110
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 8
dl 0
loc 110
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A handle() 0 10 1
A getModelsThatShouldBeCleanedUp() 0 12 1
A cleanUp() 0 13 2
A getAllModelsFromEachDirectory() 0 8 1
A getClassNamesInDirectory() 0 8 1
A getFullyQualifiedClassNameFromFile() 0 23 1
A fireEvent() 0 5 1
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\ParserFactory;
10
use ClassPreloader\Parser\NodeTraverser;
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
        $cleanableModels = $this->getModelsThatShouldBeCleanedUp();
42
43
        $this->cleanUp($cleanableModels);
44
45
        $this->comment('All done!');
46
    }
47
48
    protected function getModelsThatShouldBeCleanedUp() : Collection
49
    {
50
        $directories = config('laravel-model-cleanup.directories');
51
52
        $modelsFromDirectories = $this->getAllModelsFromEachDirectory($directories);
53
54
        return $modelsFromDirectories
55
            ->merge(collect(config('laravel-model-cleanup.models')))
56
            ->filter(function ($modelClass) {
57
                return in_array(GetsCleanedUp::class, class_implements($modelClass));
58
            });
59
    }
60
61
    protected function cleanUp(Collection $cleanableModels)
62
    {
63
        $cleanableModels->each(function (string $class) {
64
65
            $numberOfDeletedRecords = $class::cleanUp($class::query())->delete();
66
67
            if($numberOfDeletedRecords > 0)
68
                $this->fireEvent($class, $numberOfDeletedRecords);
69
70
            $this->info("Deleted {$numberOfDeletedRecords} record(s) from {$class}.");
71
72
        });
73
    }
74
75
    protected function getAllModelsFromEachDirectory(array $directories) : Collection
76
    {
77
        return collect($directories)
78
            ->map(function ($directory) {
79
                return $this->getClassNamesInDirectory($directory)->all();
80
            })
81
            ->flatten();
82
    }
83
84
    protected function getClassNamesInDirectory(string $directory) : Collection
85
    {
86
        return collect($this->filesystem->files($directory))->map(function ($path) {
87
88
            return $this->getFullyQualifiedClassNameFromFile($path);
89
90
        });
91
    }
92
93
    protected function getFullyQualifiedClassNameFromFile(string $path) : string
94
    {
95
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
96
97
        $traverser = new NodeTraverser();
98
99
        $traverser->addVisitor(new NameResolver());
100
101
        $code = file_get_contents($path);
102
103
        $statements = $parser->parse($code);
104
105
        $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...
106
107
        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...
108
            ->filter(function ($statement) {
109
                return $statement instanceof Class_;
110
            })
111
            ->map(function (Class_ $statement) {
112
                return $statement->namespacedName->toString();
0 ignored issues
show
Bug introduced by
The property namespacedName does not seem to exist in PhpParser\Node\Stmt\Class_.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
113
            })
114
            ->first();
115
    }
116
117
    protected function fireEvent(string $modelName, int $numberOfDeletedRecords){
118
119
        event(new ModelCleanedEvent($modelName, $numberOfDeletedRecords));
120
121
    }
122
}
123