Completed
Push — master ( fbf079...6257a7 )
by Freek
01:50
created

CleanUpModelsCommand::forceCleanUp()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 1
nc 1
nop 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\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
        return collect($this->filesystem->files($directory))->map(function ($path) {
116
117
            return $this->getFullyQualifiedClassNameFromFile($path);
118
119
        })->filter(function (string $className) {
120
121
            return !empty($className);
122
123
        });
124
    }
125
126
    protected function getFullyQualifiedClassNameFromFile(string $path) : string
127
    {
128
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
129
130
        $traverser = new NodeTraverser();
131
132
        $traverser->addVisitor(new NameResolver());
133
134
        $code = file_get_contents($path);
135
136
        $statements = $parser->parse($code);
137
138
        $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...
139
140
        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...
141
            ->filter(function ($statement) {
142
                return $statement instanceof Class_;
143
            })
144
            ->map(function (Class_ $statement) {
145
                return $statement->namespacedName->toString();
146
            })
147
            ->first() ?? '';
148
    }
149
}
150