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
Push — master ( 4bb723...4c5500 )
by Freek
01:16
created

GlideConversion::setTemporaryDirectory()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.2888
c 0
b 0
f 0
cc 5
nc 6
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\InvalidTemporaryDirectory;
10
11
final class GlideConversion
12
{
13
    /** @var string */
14
    private $inputImage;
15
16
    /** @var string */
17
    private $imageDriver = 'gd';
18
19
    /** @var string */
20
    private $conversionResult = null;
21
22
    /** @var string */
23
    private $temporaryDirectory = null;
24
25
    public static function create(string $inputImage): self
26
    {
27
        return new self($inputImage);
28
    }
29
30
    public function setTemporaryDirectory($tempDir)
31
    {
32
        if (isset($tempDir)) {
33
            if (! is_dir($tempDir)) {
34
                try {
35
                    mkdir($tempDir);
36
                } catch (\Exception $e) {
37
                    throw InvalidTemporaryDirectory::temporaryDirectoryNotCreatable($tempDir);
38
                }
39
            }
40
41
            if (! is_writable($tempDir)) {
42
                throw InvalidTemporaryDirectory::temporaryDirectoryNotWritable($tempdir);
43
            }
44
45
            $this->temporaryDirectory = $tempDir;
46
        }
47
48
        return $this;
49
    }
50
51
    public function getTemporaryDirectory(): string
52
    {
53
        return $this->temporaryDirectory;
54
    }
55
56
    public function __construct(string $inputImage)
57
    {
58
        $this->inputImage = $inputImage;
59
    }
60
61
    public function useImageDriver(string $imageDriver): self
62
    {
63
        $this->imageDriver = $imageDriver;
64
65
        return $this;
66
    }
67
68
    public function performManipulations(Manipulations $manipulations)
69
    {
70
        foreach ($manipulations->getManipulationSequence() as $manipulationGroup) {
71
            $inputFile = $this->conversionResult ?? $this->inputImage;
72
73
            $watermarkPath = $this->extractWatermarkPath($manipulationGroup);
74
75
            $glideServer = $this->createGlideServer($inputFile, $watermarkPath);
76
77
            $glideServer->setGroupCacheInFolders(false);
78
79
            $this->conversionResult = $this->temporaryDirectory.DIRECTORY_SEPARATOR.$glideServer->makeImage(
80
                    pathinfo($inputFile, PATHINFO_BASENAME),
81
                    $this->prepareManipulations($manipulationGroup)
82
                );
83
        }
84
85
        return $this;
86
    }
87
88
    /**
89
     * Removes the watermark path from the manipulationGroup and returns it. This way it can be injected into the Glide
90
     * server as the `watermarks` path.
91
     *
92
     * @param $manipulationGroup
93
     *
94
     * @return null|string
95
     */
96
    private function extractWatermarkPath(&$manipulationGroup)
97
    {
98
        if (array_key_exists('watermark', $manipulationGroup)) {
99
            $watermarkPath = dirname($manipulationGroup['watermark']);
100
101
            $manipulationGroup['watermark'] = basename($manipulationGroup['watermark']);
102
103
            return $watermarkPath;
104
        }
105
    }
106
107
    private function createGlideServer($inputFile, string $watermarkPath = null): Server
108
    {
109
        $config = [
110
            'source' => dirname($inputFile),
111
            'cache' => $this->temporaryDirectory,
112
            'driver' => $this->imageDriver,
113
        ];
114
115
        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...
116
            $config['watermarks'] = $watermarkPath;
117
        }
118
119
        return ServerFactory::create($config);
120
    }
121
122
    public function save(string $outputFile)
123
    {
124
        if ($this->conversionResult == '') {
125
            copy($this->inputImage, $outputFile);
126
127
            return;
128
        }
129
130
        $conversionResultDirectory = pathinfo($this->conversionResult, PATHINFO_DIRNAME);
131
132
        copy($this->conversionResult, $outputFile);
133
134
        unlink($this->conversionResult);
135
136
        if ($this->directoryIsEmpty($conversionResultDirectory) && $conversionResultDirectory !== '/tmp') {
137
            rmdir($conversionResultDirectory);
138
        }
139
    }
140
141
    private function prepareManipulations(array $manipulationGroup): array
142
    {
143
        $glideManipulations = [];
144
145
        foreach ($manipulationGroup as $name => $argument) {
146
            if ($name !== 'optimize') {
147
                $glideManipulations[$this->convertToGlideParameter($name)] = $argument;
148
            }
149
        }
150
151
        return $glideManipulations;
152
    }
153
154
    private function convertToGlideParameter(string $manipulationName): string
155
    {
156
        $conversions = [
157
            'width' => 'w',
158
            'height' => 'h',
159
            'blur' => 'blur',
160
            'pixelate' => 'pixel',
161
            'crop' => 'fit',
162
            'manualCrop' => 'crop',
163
            'orientation' => 'or',
164
            'flip' => 'flip',
165
            'fit' => 'fit',
166
            'devicePixelRatio' => 'dpr',
167
            'brightness' => 'bri',
168
            'contrast' => 'con',
169
            'gamma' => 'gam',
170
            'sharpen' => 'sharp',
171
            'filter' => 'filt',
172
            'background' => 'bg',
173
            'border' => 'border',
174
            'quality' => 'q',
175
            'format' => 'fm',
176
            'watermark' => 'mark',
177
            'watermarkWidth' => 'markw',
178
            'watermarkHeight' => 'markh',
179
            'watermarkFit' => 'markfit',
180
            'watermarkPaddingX' => 'markx',
181
            'watermarkPaddingY' => 'marky',
182
            'watermarkPosition' => 'markpos',
183
            'watermarkOpacity' => 'markalpha',
184
        ];
185
186
        if (! isset($conversions[$manipulationName])) {
187
            throw CouldNotConvert::unknownManipulation($manipulationName);
188
        }
189
190
        return $conversions[$manipulationName];
191
    }
192
193
    private function directoryIsEmpty(string $directory): bool
194
    {
195
        $iterator = new FilesystemIterator($directory);
196
197
        return ! $iterator->valid();
198
    }
199
}
200