Completed
Push — master ( 5e0c04...b90889 )
by Brent
05:29 queued 03:52
created

FileManipulator::dispatchQueuedConversions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace Spatie\MediaLibrary;
4
5
use Storage;
6
use Illuminate\Support\Facades\File;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Spatie\MediaLibrary\File.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
7
use Spatie\MediaLibrary\Models\Media;
8
use Illuminate\Contracts\Bus\Dispatcher;
9
use Spatie\MediaLibrary\Helpers\ImageFactory;
10
use Spatie\MediaLibrary\Conversion\Conversion;
11
use Spatie\MediaLibrary\Filesystem\Filesystem;
12
use Spatie\MediaLibrary\Jobs\PerformConversions;
13
use Spatie\MediaLibrary\Events\ConversionWillStart;
14
use Spatie\MediaLibrary\Helpers\TemporaryDirectory;
15
use Spatie\MediaLibrary\ImageGenerators\ImageGenerator;
16
use Spatie\MediaLibrary\Conversion\ConversionCollection;
17
use Spatie\MediaLibrary\Events\ConversionHasBeenCompleted;
18
use Spatie\MediaLibrary\Helpers\File as MediaLibraryFileHelper;
19
use Spatie\MediaLibrary\ResponsiveImages\ResponsiveImageGenerator;
20
21
class FileManipulator
22
{
23
    /**
24
     * Create all derived files for the given media.
25
     *
26
     * @param \Spatie\MediaLibrary\Models\Media $media
27
     * @param array $only
28
     * @param bool $onlyIfMissing
29
     */
30
    public function createDerivedFiles(Media $media, array $only = [], $onlyIfMissing = false)
31
    {
32
        $profileCollection = ConversionCollection::createForMedia($media);
33
34
        if (! empty($only)) {
35
            $profileCollection = $profileCollection->filter(function ($collection) use ($only) {
36
                return in_array($collection->getName(), $only);
37
            });
38
        }
39
40
        $this->performConversions(
41
            $profileCollection->getNonQueuedConversions($media->collection_name),
42
            $media,
43
            $onlyIfMissing
44
        );
45
46
        $queuedConversions = $profileCollection->getQueuedConversions($media->collection_name);
47
48
        if ($queuedConversions->isNotEmpty()) {
49
            $this->dispatchQueuedConversions($media, $queuedConversions);
50
        }
51
    }
52
53
    /**
54
     * Perform the given conversions for the given media.
55
     *
56
     * @param \Spatie\MediaLibrary\Conversion\ConversionCollection $conversions
57
     * @param \Spatie\MediaLibrary\Models\Media $media
58
     * @param bool $onlyIfMissing
59
     */
60
    public function performConversions(ConversionCollection $conversions, Media $media, $onlyIfMissing = false)
61
    {
62
        if ($conversions->isEmpty()) {
63
            return;
64
        }
65
66
        $imageGenerator = $this->determineImageGenerator($media);
67
68
        if (! $imageGenerator) {
69
            return;
70
        }
71
72
        $temporaryDirectory = TemporaryDirectory::create();
73
74
        $copiedOriginalFile = app(Filesystem::class)->copyFromMediaLibrary(
75
            $media,
76
            $temporaryDirectory->path(str_random(16).'.'.$media->extension)
77
        );
78
79
        $conversions
80
            ->reject(function (Conversion $conversion) use ($onlyIfMissing, $media) {
81
                $relativePath = $media->getPath($conversion->getName());
82
83
                $rootPath = config('filesystems.disks.'.$media->disk.'.root');
84
85
                if ($rootPath) {
86
                    $relativePath = str_replace($rootPath, '', $relativePath);
87
                }
88
89
                return $onlyIfMissing && Storage::disk($media->disk)->exists($relativePath);
90
            })
91
            ->each(function (Conversion $conversion) use ($media, $imageGenerator, $copiedOriginalFile) {
92
                event(new ConversionWillStart($media, $conversion));
93
94
                $copiedOriginalFile = $imageGenerator->convert($copiedOriginalFile, $conversion);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $copiedOriginalFile, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
95
96
                $conversionResult = $this->performConversion($media, $conversion, $copiedOriginalFile);
97
98
                $newFileName = pathinfo($media->file_name, PATHINFO_FILENAME).
99
                    '-'.$conversion->getName().
100
                    '.'.$conversion->getResultExtension(pathinfo($copiedOriginalFile, PATHINFO_EXTENSION));
101
102
                $renamedFile = MediaLibraryFileHelper::renameInDirectory($conversionResult, $newFileName);
103
104
                if ($conversion->shouldGenerateResponsiveImages()) {
105
                    app(ResponsiveImageGenerator::class)->generateResponsiveImagesForConversion(
106
                        $media,
107
                        $conversion,
108
                        $renamedFile
109
                    );
110
                }
111
112
                app(Filesystem::class)->copyToMediaLibrary($renamedFile, $media, 'conversions');
113
114
                event(new ConversionHasBeenCompleted($media, $conversion));
115
            });
116
117
        $temporaryDirectory->delete();
118
    }
119
120
    public function performConversion(Media $media, Conversion $conversion, string $imageFile): string
121
    {
122
        $conversionTempFile = pathinfo($imageFile, PATHINFO_DIRNAME).'/'.str_random(16)
123
            .$conversion->getName()
124
            .'.'
125
            .$media->extension;
126
127
        File::copy($imageFile, $conversionTempFile);
128
129
        $supportedFormats = ['jpg', 'pjpg', 'png', 'gif'];
130
        if ($conversion->shouldKeepOriginalImageFormat() && in_array($media->extension, $supportedFormats)) {
131
            $conversion->format($media->extension);
0 ignored issues
show
Bug introduced by
The method format() does not exist on Spatie\MediaLibrary\Conversion\Conversion. Did you maybe mean keepOriginalImageFormat()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
132
        }
133
134
        ImageFactory::load($conversionTempFile)
135
            ->manipulate($conversion->getManipulations())
136
            ->save();
137
138
        return $conversionTempFile;
139
    }
140
141
    protected function dispatchQueuedConversions(Media $media, ConversionCollection $queuedConversions)
142
    {
143
        $job = new PerformConversions($queuedConversions, $media);
144
145
        if ($customQueue = config('medialibrary.queue_name')) {
146
            $job->onQueue($customQueue);
147
        }
148
149
        app(Dispatcher::class)->dispatch($job);
150
    }
151
152
    /**
153
     * @param \Spatie\MediaLibrary\Models\Media $media
154
     *
155
     * @return \Spatie\MediaLibrary\ImageGenerators\ImageGenerator|null
156
     */
157
    public function determineImageGenerator(Media $media)
158
    {
159
        return $media->getImageGenerators()
160
            ->map(function (string $imageGeneratorClassName) {
161
                return app($imageGeneratorClassName);
162
            })
163
            ->first(function (ImageGenerator $imageGenerator) use ($media) {
164
                return $imageGenerator->canConvert($media);
165
            });
166
    }
167
}
168