GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#66)
by
unknown
01:14
created

GlideConversion::save()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
cc 4
nc 3
nop 1
1
<?php
2
3
namespace Spatie\Image;
4
5
use FilesystemIterator;
6
use League\Glide\Server;
7
use League\Glide\ServerFactory;
8
use Spatie\Image\Exceptions\CouldNotConvert;
9
use Spatie\Image\Exceptions\DefectiveConfiguration;
10
11
final class GlideConversion
12
{
13
14
    /** @var string */
15
    private $inputImage;
16
17
    /** @var string */
18
    private $imageDriver = 'gd';
19
20
    /** @var string */
21
    private $conversionResult = null;
22
23
    /** @var string */
24
    private $temporaryDirectory = null;
25
26
    public static function create(string $inputImage, $config = []): self
27
    {
28
        return new self($inputImage, $config);
0 ignored issues
show
Unused Code introduced by
The call to GlideConversion::__construct() has too many arguments starting with $config.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
29
    }
30
31
    public function setTemporaryDirectory($tempDir)
32
    {
33
34
        if (isset($tempDir)) {
35
            if (! is_dir($tempDir)) {
36
                try {
37
                    mkdir($tempDir);
38
                } catch (\Exception $e) {
39
                    throw DefectiveConfiguration::invalidTemporaryDirectory($tempDir);
40
                }
41
            }
42
43
            if (! self::isValidTemporaryDirectoryLocation($tempDir)) {
44
                throw DefectiveConfiguration::invalidTemporaryDirectory($tempDir);
45
            }
46
47
48
            $this->temporaryDirectory = $tempDir;
49
50
        }
51
52
        return $this;
53
    }
54
55
    public function getTemporaryDirectory(): string
56
    {
57
        return $this->temporaryDirectory;
58
    }
59
60
    private static function isValidTemporaryDirectoryLocation($dir): bool
61
    {
62
        return isset($dir) && is_dir($dir) && is_writable($dir);
63
    }
64
65
66
    public function __construct(string $inputImage)
67
    {
68
        $this->inputImage = $inputImage;
69
    }
70
71
    public function useImageDriver(string $imageDriver): self
72
    {
73
        $this->imageDriver = $imageDriver;
74
75
        return $this;
76
    }
77
78
    public function performManipulations(Manipulations $manipulations)
79
    {
80
        foreach ($manipulations->getManipulationSequence() as $manipulationGroup) {
81
            $inputFile = $this->conversionResult ?? $this->inputImage;
82
83
            $watermarkPath = $this->extractWatermarkPath($manipulationGroup);
84
85
            $glideServer = $this->createGlideServer($inputFile, $watermarkPath);
86
87
            $glideServer->setGroupCacheInFolders(false);
88
89
            $this->conversionResult = $this->temporaryDirectory.DIRECTORY_SEPARATOR.$glideServer->makeImage(
90
                    pathinfo($inputFile, PATHINFO_BASENAME),
91
                    $this->prepareManipulations($manipulationGroup)
92
                );
93
        }
94
95
        return $this;
96
    }
97
98
    /**
99
     * Removes the watermark path from the manipulationGroup and returns it. This way it can be injected into the Glide
100
     * server as the `watermarks` path.
101
     *
102
     * @param $manipulationGroup
103
     *
104
     * @return null|string
105
     */
106
    private function extractWatermarkPath(&$manipulationGroup)
107
    {
108
        if (array_key_exists('watermark', $manipulationGroup)) {
109
            $watermarkPath = dirname($manipulationGroup['watermark']);
110
111
            $manipulationGroup['watermark'] = basename($manipulationGroup['watermark']);
112
113
            return $watermarkPath;
114
        }
115
    }
116
117
    private function createGlideServer($inputFile, string $watermarkPath = null): Server
118
    {
119
        $config = [
120
            'source' => dirname($inputFile),
121
            'cache' => $this->temporaryDirectory,
122
            'driver' => $this->imageDriver,
123
        ];
124
125
        if ($watermarkPath) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $watermarkPath of type null|string is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
126
            $config['watermarks'] = $watermarkPath;
127
        }
128
129
        return ServerFactory::create($config);
130
    }
131
132
    public function save(string $outputFile)
133
    {
134
        if ($this->conversionResult == '') {
135
            copy($this->inputImage, $outputFile);
136
137
            return;
138
        }
139
140
        $conversionResultDirectory = pathinfo($this->conversionResult, PATHINFO_DIRNAME);
141
142
        copy($this->conversionResult, $outputFile);
143
144
        unlink($this->conversionResult);
145
146
        if ($this->directoryIsEmpty($conversionResultDirectory) && $conversionResultDirectory !== '/tmp') {
147
            rmdir($conversionResultDirectory);
148
        }
149
    }
150
151
    private function prepareManipulations(array $manipulationGroup): array
152
    {
153
        $glideManipulations = [];
154
155
        foreach ($manipulationGroup as $name => $argument) {
156
            if ($name !== 'optimize') {
157
                $glideManipulations[$this->convertToGlideParameter($name)] = $argument;
158
            }
159
        }
160
161
        return $glideManipulations;
162
    }
163
164
    private function convertToGlideParameter(string $manipulationName): string
165
    {
166
        $conversions = [
167
            'width' => 'w',
168
            'height' => 'h',
169
            'blur' => 'blur',
170
            'pixelate' => 'pixel',
171
            'crop' => 'fit',
172
            'manualCrop' => 'crop',
173
            'orientation' => 'or',
174
            'flip' => 'flip',
175
            'fit' => 'fit',
176
            'devicePixelRatio' => 'dpr',
177
            'brightness' => 'bri',
178
            'contrast' => 'con',
179
            'gamma' => 'gam',
180
            'sharpen' => 'sharp',
181
            'filter' => 'filt',
182
            'background' => 'bg',
183
            'border' => 'border',
184
            'quality' => 'q',
185
            'format' => 'fm',
186
            'watermark' => 'mark',
187
            'watermarkWidth' => 'markw',
188
            'watermarkHeight' => 'markh',
189
            'watermarkFit' => 'markfit',
190
            'watermarkPaddingX' => 'markx',
191
            'watermarkPaddingY' => 'marky',
192
            'watermarkPosition' => 'markpos',
193
            'watermarkOpacity' => 'markalpha',
194
        ];
195
196
        if (! isset($conversions[$manipulationName])) {
197
            throw CouldNotConvert::unknownManipulation($manipulationName);
198
        }
199
200
        return $conversions[$manipulationName];
201
    }
202
203
    private function directoryIsEmpty(string $directory): bool
204
    {
205
        $iterator = new FilesystemIterator($directory);
206
207
        return ! $iterator->valid();
208
    }
209
210
}
211