Completed
Push — master ( 644543...87fc1c )
by Freek
02:17
created

CleanCommand::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 4
1
<?php
2
3
namespace Spatie\MediaLibrary\Commands;
4
5
use Illuminate\Console\Command;
6
use Illuminate\Console\ConfirmableTrait;
7
use Illuminate\Contracts\Filesystem\Factory;
8
use Illuminate\Database\Eloquent\Collection;
9
use Spatie\MediaLibrary\Conversion\ConversionCollection;
10
use Spatie\MediaLibrary\Exceptions\FileCannotBeAdded;
11
use Spatie\MediaLibrary\FileManipulator;
12
use Spatie\MediaLibrary\Media;
13
use Spatie\MediaLibrary\MediaRepository;
14
use Spatie\MediaLibrary\PathGenerator\BasePathGenerator;
15
16
class CleanCommand extends Command
17
{
18
    use ConfirmableTrait;
19
20
    /**
21
     * The console command name.
22
     *
23
     * @var string
24
     */
25
    protected $signature = 'medialibrary:clean {modelType?} {collectionName?} {disk?} {--dry-run}';
26
27
    /**
28
     * The console command description.
29
     *
30
     * @var string
31
     */
32
    protected $description = 'Clean deprecated conversions and files without related model.';
33
34
    /**
35
     * @var \Spatie\MediaLibrary\MediaRepository
36
     */
37
    protected $mediaRepository;
38
39
    /**
40
     * @var \Spatie\MediaLibrary\FileManipulator
41
     */
42
    protected $fileManipulator;
43
44
    /**
45
     * @var Factory
46
     */
47
    private $fileSystem;
48
49
    /**
50
     * @var BasePathGenerator
51
     */
52
    private $basePathGenerator;
53
54
    /**
55
     * @var bool
56
     */
57
    protected $dry = false;
58
59
    /**
60
     * @param MediaRepository   $mediaRepository
61
     * @param FileManipulator   $fileManipulator
62
     * @param Factory           $fileSystem
63
     * @param BasePathGenerator $basePathGenerator
64
     */
65
    public function __construct(
66
        MediaRepository $mediaRepository,
67
        FileManipulator $fileManipulator,
68
        Factory $fileSystem,
69
        BasePathGenerator $basePathGenerator
70
    ) {
71
        parent::__construct();
72
        $this->mediaRepository = $mediaRepository;
73
        $this->fileManipulator = $fileManipulator;
74
        $this->fileSystem = $fileSystem;
75
        $this->basePathGenerator = $basePathGenerator;
76
    }
77
78
    /**
79
     * Handle command.
80
     */
81
    public function handle()
82
    {
83
        if (!$this->confirmToProceed()) {
84
            return;
85
        }
86
87
        $this->dry = $this->option('dry-run');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->option('dry-run') of type string or array is incompatible with the declared type boolean of property $dry.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
88
89
        // Clean deprecated conversions
90
        $this->getMediaItems()->each(function (Media $media) {
91
            $this->cleanDeprecatedConversions($media);
92
        });
93
94
        // Clean files without related models
95
        $this->cleanOrphanFiles();
96
97
        $this->info('All done!');
98
    }
99
100
    public function getMediaItems() : Collection
101
    {
102
        $modelType = $this->argument('modelType');
103
        $collectionName = $this->argument('collectionName');
104
105
        if (!is_null($modelType) && !is_null($collectionName)) {
106
            return $this->mediaRepository->getByModelTypeAndCollectionName(
107
                $modelType,
0 ignored issues
show
Bug introduced by
It seems like $modelType defined by $this->argument('modelType') on line 102 can also be of type array; however, Spatie\MediaLibrary\Medi...TypeAndCollectionName() does only seem to accept string, 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...
108
                $collectionName
0 ignored issues
show
Bug introduced by
It seems like $collectionName defined by $this->argument('collectionName') on line 103 can also be of type array; however, Spatie\MediaLibrary\Medi...TypeAndCollectionName() does only seem to accept string, 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...
109
            );
110
        }
111
112
        if (!is_null($modelType)) {
113
            return $this->mediaRepository->getByModelType($modelType);
0 ignored issues
show
Bug introduced by
It seems like $modelType defined by $this->argument('modelType') on line 102 can also be of type array; however, Spatie\MediaLibrary\Medi...itory::getByModelType() does only seem to accept string, 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...
114
        }
115
116
        if (!is_null($collectionName)) {
117
            return $this->mediaRepository->getByCollectionName($collectionName);
0 ignored issues
show
Bug introduced by
It seems like $collectionName defined by $this->argument('collectionName') on line 103 can also be of type array; however, Spatie\MediaLibrary\Medi...::getByCollectionName() does only seem to accept string, 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...
118
        }
119
120
        return $this->mediaRepository->all();
121
    }
122
123
    /**
124
     * @param Media $media
125
     */
126
    private function cleanDeprecatedConversions(Media $media)
127
    {
128
        // Get conversion directory
129
        $path = $this->basePathGenerator->getPathForConversions($media);
130
        $files = $this->fileSystem->disk($media->disk)->files($path);
131
132
        // Get the list of currently defined conversions
133
        $conversions = ConversionCollection::createForMedia($media)->getConversionsFiles($media->collection_name);
134
135
        // Verify that each file on disk is defined in a conversion, else we delete the file
136
        foreach ($files as $file) {
137
            if (!$conversions->contains(basename($file))) {
138
                if (!$this->dry) {
139
                    $this->fileSystem->disk($media->disk)->delete($file);
140
                }
141
142
                $this->info("Deprecated conversion file $file " . ($this->dry ? '' : 'has been removed'));
143
            }
144
        }
145
    }
146
147
    private function cleanOrphanFiles()
148
    {
149
        $diskName = $this->argument('disk') ?: config('laravel-medialibrary.defaultFilesystem');
150
151
        if (is_null(config("filesystems.disks.{$diskName}"))) {
152
            throw FileCannotBeAdded::diskDoesNotExist($diskName);
153
        }
154
155
        $medias = $this->mediaRepository->all()->pluck('id');
156
        $directories = new Collection($this->fileSystem->disk($diskName)->directories());
157
158
        // Ignore all directories related to a media row and non numeric directories name
159
        $directories = $directories->filter(function ($directory) use ($medias) {
160
            return is_numeric($directory) ? !$medias->contains((int)$directory) : false;
161
        });
162
163
        // Delete all directories with bo media row
164
        foreach ($directories as $directory) {
165
            if (!$this->dry) {
166
                $this->fileSystem->disk($diskName)->deleteDirectory($directory);
167
            }
168
169
            $this->info("Orphan media file $directory " . ($this->dry ? '' : 'has been removed'));
170
        }
171
    }
172
}
173