Completed
Push — master ( 87fc1c...85a536 )
by Freek
02:47
created

deleteFilesGeneratedForDeprecatedConversions()   B

Complexity

Conditions 5
Paths 1

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
cc 5
eloc 10
nc 1
nop 0
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 \Illuminate\Contracts\Filesystem\Factory
46
     */
47
    private $fileSystem;
48
49
    /**
50
     * @var \Spatie\MediaLibrary\PathGenerator\BasePathGenerator
51
     */
52
    private $basePathGenerator;
53
54
    /**
55
     * @var bool
56
     */
57
    protected $dry = false;
58
59
    /**
60
     * @param \Spatie\MediaLibrary\MediaRepository $mediaRepository
61
     * @param \Spatie\MediaLibrary\FileManipulator $fileManipulator
62
     * @param \Illuminate\Contracts\Filesystem\Factory $fileSystem
63
     * @param \Spatie\MediaLibrary\PathGenerator\BasePathGenerator $basePathGenerator
64
     */
65
    public function __construct(
66
        MediaRepository $mediaRepository,
67
        FileManipulator $fileManipulator,
68
        Factory $fileSystem,
69
        BasePathGenerator $basePathGenerator
70
    )
71
    {
72
        parent::__construct();
73
        $this->mediaRepository = $mediaRepository;
74
        $this->fileManipulator = $fileManipulator;
75
        $this->fileSystem = $fileSystem;
76
        $this->basePathGenerator = $basePathGenerator;
77
    }
78
79
    /**
80
     * Handle command.
81
     */
82
    public function handle()
83
    {
84
        if (!$this->confirmToProceed()) {
85
            return;
86
        }
87
88
        $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...
89
90
        $this->deleteFilesGeneratedForDeprecatedConversions();
91
92
        $this->deleteOrphanedFiles();
93
94
        $this->info('All done!');
95
    }
96
97
    public function getMediaItems() : Collection
98
    {
99
        $modelType = $this->argument('modelType');
100
        $collectionName = $this->argument('collectionName');
101
102
        if (!is_null($modelType) && !is_null($collectionName)) {
103
            return $this->mediaRepository->getByModelTypeAndCollectionName(
104
                $modelType,
0 ignored issues
show
Bug introduced by
It seems like $modelType defined by $this->argument('modelType') on line 99 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...
105
                $collectionName
0 ignored issues
show
Bug introduced by
It seems like $collectionName defined by $this->argument('collectionName') on line 100 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...
106
            );
107
        }
108
109
        if (!is_null($modelType)) {
110
            return $this->mediaRepository->getByModelType($modelType);
0 ignored issues
show
Bug introduced by
It seems like $modelType defined by $this->argument('modelType') on line 99 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...
111
        }
112
113
        if (!is_null($collectionName)) {
114
            return $this->mediaRepository->getByCollectionName($collectionName);
0 ignored issues
show
Bug introduced by
It seems like $collectionName defined by $this->argument('collectionName') on line 100 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...
115
        }
116
117
        return $this->mediaRepository->all();
118
    }
119
120
    protected function deleteFilesGeneratedForDeprecatedConversions()
121
    {
122
        $this->getMediaItems()->each(function (Media $media) {
123
124
            // Get conversion directory
125
            $path = $this->basePathGenerator->getPathForConversions($media);
126
            $files = $this->fileSystem->disk($media->disk)->files($path);
127
128
            // Get the list of currently defined conversions
129
            $conversions = ConversionCollection::createForMedia($media)->getConversionsFiles($media->collection_name);
130
131
            // Verify that each file on disk is defined in a conversion, else we delete the file
132
            foreach ($files as $file) {
133
                if (!$conversions->contains(basename($file))) {
134
                    if (!$this->dry) {
135
                        $this->fileSystem->disk($media->disk)->delete($file);
136
                    }
137
138
                    $this->info("Deprecated conversion file `{$file}` " . ($this->dry ? 'found' : 'has been removed'));
139
                }
140
            }
141
        });
142
    }
143
144
    protected function deleteOrphanedFiles()
145
    {
146
        $diskName = $this->argument('disk') ?: config('laravel-medialibrary.defaultFilesystem');
147
148
        if (is_null(config("filesystems.disks.{$diskName}"))) {
149
            throw FileCannotBeAdded::diskDoesNotExist($diskName);
150
        }
151
152
        $mediaIds = $this->mediaRepository->all()->pluck('id');
153
154
        collect($this->fileSystem->disk($diskName)->directories())
155
            ->filter(function (string $directory) use ($mediaIds) {
156
                return is_numeric($directory) ? !$mediaIds->contains((int)$directory) : false;
157
            })->each(function (string $directory) use ($diskName) {
158
                if (!$this->dry) {
159
                    $this->fileSystem->disk($diskName)->deleteDirectory($directory);
160
                }
161
162
                $this->info("Orphaned media directory `{$directory}` " . ($this->dry ? 'found' : 'has been removed'));
163
            });
164
    }
165
}
166