Completed
Push — master ( 3cd240...ef1fc0 )
by Freek
6s
created

CleanUpModelsCommand   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 101
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6
Metric Value
wmc 7
lcom 1
cbo 6
dl 0
loc 101
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A handle() 0 10 1
A getModelsThatShouldBeCleanedUp() 0 12 1
A cleanUp() 0 10 1
A getClassNamesInDirectory() 0 8 1
A getFullyQualifiedClassNameFromFile() 0 23 1
A getAllModelsFromEachDirectory() 0 8 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
            $this->info("Deleted {$numberOfDeletedRecords} record(s) from {$class}.");
68
69
        });
70
    }
71
72
    protected function getAllModelsFromEachDirectory(array $directories) : Collection
73
    {
74
        return collect($directories)
75
            ->map(function ($directory) {
76
                return $this->getClassNamesInDirectory($directory)->all();
77
            })
78
            ->flatten();
79
    }
80
81
    protected function getClassNamesInDirectory(string $directory) : Collection
82
    {
83
        return collect($this->filesystem->files($directory))->map(function ($path) {
84
85
            return $this->getFullyQualifiedClassNameFromFile($path);
86
87
        });
88
    }
89
90
    protected function getFullyQualifiedClassNameFromFile(string $path) : string
91
    {
92
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
93
94
        $traverser = new NodeTraverser();
95
96
        $traverser->addVisitor(new NameResolver());
97
98
        $code = file_get_contents($path);
99
100
        $statements = $parser->parse($code);
101
102
        $statements = $traverser->traverse($statements);
103
104
        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...
105
            ->filter(function ($statement) {
106
                return $statement instanceof Class_;
107
            })
108
            ->map(function (Class_ $statement) {
109
                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...
110
            })
111
            ->first();
112
    }
113
}
114