Completed
Push — master ( b375d3...089ee0 )
by Freek
01:52
created

FileManipulator::performConversions()   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 61
rs 8.2286
c 0
b 0
f 0
cc 6
nc 3
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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),
0 ignored issues
show
Documentation introduced by
The property collection_name does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
42
            $media,
43
            $onlyIfMissing
44
        );
45
46
        $queuedConversions = $profileCollection->getQueuedConversions($media->collection_name);
0 ignored issues
show
Documentation introduced by
The property collection_name does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
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)
0 ignored issues
show
Documentation introduced by
The property extension does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
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');
0 ignored issues
show
Documentation introduced by
The property disk does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
84
85
                if ($rootPath) {
86
                    $relativePath = str_replace($rootPath, '', $relativePath);
87
                }
88
89
                return $onlyIfMissing && Storage::disk($media->disk)->exists($relativePath);
0 ignored issues
show
Documentation introduced by
The property disk does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
90
            })
91
            ->each(function (Conversion $conversion) use ($media, $imageGenerator, $copiedOriginalFile) {
92
                event(new ConversionWillStart($media, $conversion, $copiedOriginalFile));
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
                $manipulationResult = $this->performManipulations($media, $conversion, $copiedOriginalFile);
97
98
                $newFileName = pathinfo($media->file_name, PATHINFO_FILENAME).
0 ignored issues
show
Documentation introduced by
The property file_name does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
99
                    '-'.$conversion->getName().
100
                    '.'.$conversion->getResultExtension(pathinfo($copiedOriginalFile, PATHINFO_EXTENSION));
101
102
                $renamedFile = MediaLibraryFileHelper::renameInDirectory($manipulationResult, $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
                $media->markAsConversionGenerated($conversion->getName(), true);
115
116
                event(new ConversionHasBeenCompleted($media, $conversion));
117
            });
118
119
        $temporaryDirectory->delete();
120
    }
121
122
    public function performManipulations(Media $media, Conversion $conversion, string $imageFile): string
123
    {
124
        if ($conversion->getManipulations()->isEmpty()) {
125
            return $imageFile;
126
        }
127
128
        $conversionTempFile = pathinfo($imageFile, PATHINFO_DIRNAME).'/'.str_random(16)
129
            .$conversion->getName()
130
            .'.'
131
            .$media->extension;
0 ignored issues
show
Documentation introduced by
The property extension does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
132
133
        File::copy($imageFile, $conversionTempFile);
134
135
        $supportedFormats = ['jpg', 'pjpg', 'png', 'gif'];
136
        if ($conversion->shouldKeepOriginalImageFormat() && in_array($media->extension, $supportedFormats)) {
0 ignored issues
show
Documentation introduced by
The property extension does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
137
            $conversion->format($media->extension);
0 ignored issues
show
Documentation introduced by
The property extension does not exist on object<Spatie\MediaLibrary\Models\Media>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

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