Completed
Push — master ( ca5a09...bdcabe )
by Renato
11:16
created

StorageManager::uploadImage()   C

Complexity

Conditions 11
Paths 261

Size

Total Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 132

Importance

Changes 0
Metric Value
cc 11
nc 261
nop 6
dl 0
loc 46
ccs 0
cts 40
cp 0
crap 132
rs 5.7208
c 0
b 0
f 0

How to fix   Complexity   

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 NwLaravel\FileStorage;
4
5
use \Exception;
6
use \RuntimeException;
7
use Symfony\Component\HttpFoundation\File\UploadedFile;
8
use Illuminate\Contracts\Filesystem\Filesystem as Storage;
9
use Intervention\Image\Image;
10
11
/**
12
 * Class StorageManager
13
 */
14
class StorageManager
15
{
16
    /**
17
     * @var Storage
18
     */
19
    protected $storage;
20
21
    /**
22
     * @var ImagineFactory
23
     */
24
    protected $imagineFactory;
25
26
    /**
27
     * Construct
28
     *
29
     * @param Storage        $storage
30
     * @param ImagineFactory $imagineFactory
31
     */
32
    public function __construct(Storage $storage, ImagineFactory $imagineFactory = null)
33
    {
34
        $this->storage = $storage;
35
        $this->imagineFactory = $imagineFactory;
36
    }
37
38
    /**
39
     * File Exists
40
     *
41
     * @param string $filename Path File
42
     *
43
     * @return bool
44
     */
45
    public function exists($filename)
46
    {
47
        try {
48
            return $this->storage->exists($filename);
49
50
        } catch (\Exception $e) {
51
            return false;
52
        }
53
    }
54
55
    /**
56
     * Get Size
57
     *
58
     * @param string $filename Path File
59
     *
60
     * @return bool
61
     */
62
    public function size($filename)
63
    {
64
        try {
65
            return intval($this->storage->size($filename));
66
67
        } catch (\Exception $e) {
68
            return 0;
69
        }
70
    }
71
72
    /**
73
     * Get MimeType File
74
     *
75
     * @param string $filename Path File
76
     *
77
     * @return bool
78
     */
79
    public function mimeType($filename)
80
    {
81
        try {
82
            return $this->storage->mimeType($filename);
83
84
        } catch (\Exception $e) {
85
            return null;
86
        }
87
    }
88
89
    /**
90
     * Path is Directory
91
     *
92
     * @param string $path Path Directory
93
     *
94
     * @return bool
95
     */
96
    public function isDir($path)
97
    {
98
        $mimeType = $this->mimeType($path);
99
100
        if ($this->exists($path) && (!$mimeType || $mimeType == 'directory')) {
101
            return true;
102
        }
103
104
        return false;
105
    }
106
107
    /**
108
     * Is File
109
     *
110
     * @param string $filename Path File
111
     *
112
     * @return bool
113
     */
114
    public function isFile($filename)
115
    {
116
        return !$this->isDir($filename);
117
    }
118
119
    /**
120
     * Get Meta Data
121
     *
122
     * @param string $filename Path File
123
     *
124
     * @return bool
125
     */
126
    public function metaData($filename)
127
    {
128
        try {
129
            return $this->storage->getMetadata($filename);
0 ignored issues
show
Bug introduced by
The method getMetadata() does not seem to exist on object<Illuminate\Contra...\Filesystem\Filesystem>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
130
131
        } catch (\Exception $e) {
132
            return null;
133
        }
134
    }
135
136
    /**
137
     * Read Content File
138
     *
139
     * @param string $filename Path File
140
     *
141
     * @return string
142
     */
143
    public function readFile($filename)
144
    {
145
        return $this->storage->get($filename);
146
    }
147
148
    /**
149
     * Delete File
150
     *
151
     * @param string $filename Path File
152
     *
153
     * @return bool
154
     */
155
    public function deleteFile($filename)
156
    {
157
        if ($this->isDir($filename)) {
158
            return false;
159
        }
160
161
        return $this->storage->delete($filename);
162
    }
163
164
    /**
165
     * Delete Folder
166
     *
167
     * @param string $folder
168
     *
169
     * @return bool
170
     */
171
    public function deleteFolder($folder)
172
    {
173
        if ($this->isFile($folder)) {
174
            return false;
175
        }
176
177
        return $this->storage->deleteDirectory($folder);
178
    }
179
180
    /**
181
     * Files in Folder
182
     *
183
     * @param string $path
184
     * @param bool   $recursive
185
     *
186
     * @return array
187
     */
188
    public function files($path, $recursive = false)
189
    {
190
        if ($this->isFile($path)) {
191
            return null;
192
        }
193
194
        return $this->storage->files($path, (bool) $recursive);
195
    }
196
197
    /**
198
     * UploadFile
199
     *
200
     * @param UploadedFile|string $file     Uploaded File
201
     * @param string       $folder   String Folder
202
     * @param string       $name     String Name
203
     * @param bool         $override Boolean Over Ride
204
     * @param array        $config   Array Config Upload
205
     *
206
     * @return bool
207
     */
208
    public function uploadFile(UploadedFile $file, $folder = null, $name = null, $override = false, array $config = [])
209
    {
210
        $data = $this->parseFile($file, $folder, $name, $override);
211
212
        $success = (bool) $this->storage->put($data['filename'], file_get_contents($file), $config);
0 ignored issues
show
Documentation introduced by
$config is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
213
214
        if ($success) {
215
            return $data;
216
        }
217
218
        return false;
219
    }
220
221
    /**
222
     * Upload Image
223
     *
224
     * @param UploadedFile $file     Uploaded File
225
     * @param string       $folder   String Folder
226
     * @param string       $name     String Name
227
     * @param array        $options  Array Options
228
     * @param bool         $override Boolean Over Ride
229
     * @param array        $config  Array Config Upload
230
     *
231
     * @return bool
232
     */
233
    public function uploadImage(
234
        $file,
235
        $folder = null,
236
        $name = null,
237
        array $options = [],
238
        $override = false,
239
        array $config = []
240
    ) {
241
        if ($file instanceof UploadedFile) {
242
            $pathImage = $file->getPathname();
243
        } elseif (file_exists($file)) {
244
            $pathImage = $file;
245
        } else {
246
            throw new RuntimeException("File invalid");
247
        }
248
249
        $data = $this->parseFile($file, $folder, $name, $override);
250
251
        if ($this->imagineFactory) {
252
            $width = isset($options['width']) ? intval($options['width']) : 0;
253
            $height = isset($options['height']) ? intval($options['height']) : 0;
254
            $scale = isset($options['scale']) ? (bool) $options['scale'] : true;
255
            $opacity = isset($options['opacity']) ? (float) $options['opacity'] : null;
256
            $watermark = isset($options['watermark']) ? $options['watermark'] : null;
257
            $quality = isset($options['quality']) ? intval($options['quality']) : 85; // Quality Deufault: 85;
258
259
            $imagine = $this->imagineFactory->make($pathImage);
260
            $imagine->stripProfiles();
261
            $imagine->resize($width, $height, !$scale);
262
            $imagine->opacity($opacity);
263
            $imagine->watermark($watermark);
264
            $imagine = $imagine->save($pathImage.'.'.$data['extension'], $quality);
265
            $data['size'] = $imagine->filesize();
266
            $content = $imagine->encode();
267
        } else {
268
            $content = file_get_contents($file);
269
        }
270
271
        $success = $this->storage->put($data['filename'], $content, $config);
0 ignored issues
show
Documentation introduced by
$config is of type array, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
272
273
        if ($success) {
274
            return $data;
275
        }
276
277
        return false;
278
    }
279
280
    /**
281
     * Parse Filename
282
     *
283
     * @param UploadedFile|string $file     Uploaded File
284
     * @param string       $name     String Name
285
     * @param string       $folder   String Folder
286
     * @param bool         $override Boolean Over Ride
287
     *
288
     * @return bool|array
289
     */
290
    protected function parseFile($file, $folder = null, $name = null, $override = false)
291
    {
292
        $folder = trim((string) $folder, '/');
293
        $folder = $folder ? "{$folder}/" : "";
294
        $this->storage->makeDirectory($folder);
295
296
        if ($file instanceof UploadedFile) {
297
            $clientOriginalName = $file->getClientOriginalName();
298
            $extension = $file->getClientOriginalExtension();
299
            $size = $file->getClientSize();
300
            $mime = $file->getClientMimeType();
301
        } else {
302
            $info = pathinfo($file);
303
            $clientOriginalName = $info['basename'];
304
            $extension = $info['extension'];
305
            $size = filesize($file);
306
            $mime = mime_content_type($file);
307
        }
308
309
        $name = $name ?: $clientOriginalName;
310
        $nameOriginal = str_slug(pathinfo($name, PATHINFO_FILENAME));
311
312
        if (empty($nameOriginal)) {
313
            $nameOriginal = str_random(10);
314
        }
315
316
        $sufix = '';
317
        $count = 1;
318
        do {
319
            $name = "{$nameOriginal}{$sufix}.{$extension}";
320
            $filename = "{$folder}{$name}";
321
            $sufix = "({$count})";
322
            $count++;
323
324
        } while (!$override && $this->storage->exists($filename));
325
326
        return compact('filename', 'name', 'extension', 'size', 'mime');
327
    }
328
329
    /**
330
     * Crop Image
331
     *
332
     * @param string $filename
333
     * @param int    $width
334
     * @param int    $height
335
     * @param int    $x
336
     * @param int    $y
337
     *
338
     * @return bool
339
     */
340
    public function cropImage(
341
        $filename,
342
        $width,
343
        $height,
344
        $x,
345
        $y,
346
        $target = null
347
    ) {
348
        if (!$this->imagineFactory) {
349
            return false;
350
        }
351
352
        $image = $this->storage->get($filename);
353
        $imagine = $this->imagineFactory->make($image);
354
        $imagine->crop($width, $height, $x, $y);
355
356
        if (!$target) {
357
            $target = $filename;
358
        }
359
360
        return $this->storage->put($target, $imagine->encode());
361
    }
362
363
    /**
364
     * Watermark Image
365
     *
366
     * @param string $filename
367
     * @param int    $width
0 ignored issues
show
Bug introduced by
There is no parameter named $width. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
368
     * @param int    $height
0 ignored issues
show
Bug introduced by
There is no parameter named $height. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
369
     * @param int    $x
0 ignored issues
show
Bug introduced by
There is no parameter named $x. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
370
     * @param int    $y
0 ignored issues
show
Bug introduced by
There is no parameter named $y. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
371
     *
372
     * @return bool
373
     */
374
    public function watermarkImage(
375
        $filename,
0 ignored issues
show
Unused Code introduced by
The parameter $filename is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
376
        $watermark,
377
        $position = 'center',
378
        $opacity = null,
379
        $target = null
380
    ) {
381
        if (!$this->imagineFactory) {
382
            return false;
383
        }
384
385
        $filename = $bemArquivo->file;
0 ignored issues
show
Bug introduced by
The variable $bemArquivo does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
386
387
        $pathTmp = tempnam(sys_get_temp_dir(), $name);
0 ignored issues
show
Bug introduced by
The variable $name does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
388
        file_put_contents($pathTmp, $this->storage->get($filename));
389
        $imagine = $this->imagineFactory->make($pathTmp);
390
        @unlink($pathTmp);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
391
392
        // Se o watermark existe
393
        if (file_exists($watermark)) {
394
            $imagine->watermark($watermark, $position, $opacity);
395
        }
396
397
        if (!$target) {
398
            $target = $filename;
399
        }
400
401
        return $this->storage->put($target, $imagine->encode());
402
    }
403
404
    /**
405
     * Dynamically handle calls into the query instance.
406
     *
407
     * @param  string  $method
408
     * @param  array  $parameters
409
     * @return mixed
410
     */
411
    public function __call($method, $parameters)
412
    {
413
        return $this->storage->{$method}(...$parameters);
414
    }
415
}
416