Completed
Push — master ( 1a8b44...b0ffd4 )
by Lorenzo
12:26
created

Uploadable::getUploadFileBasePath()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 4
nop 1
1
<?php
2
3
namespace Padosoft\Uploadable;
4
5
use DB;
6
use Illuminate\Support\Facades\Log;
7
use Illuminate\Database\Eloquent\Model;
8
use Illuminate\Http\UploadedFile;
9
use Padosoft\Io\DirHelper;
10
use Padosoft\Io\FileHelper;
11
use Padosoft\Laravel\Request\RequestHelper;
12
use Padosoft\Laravel\Request\UploadedFileHelper;
13
14
/**
15
 * Class Uploadable
16
 * Auto upload and save files on save/create/delete model.
17
 * @package Padosoft\Uploadable
18
 */
19
trait Uploadable
20
{
21
    /** @var UploadOptions */
22
    protected $uploadOptions;
23
24
    /**
25
     * Boot the trait.
26
     */
27
    public static function bootUploadable()
28
    {
29
        static::creating(function ($model) {
30
            $model->uploadOptions = $model->getUploadOptionsOrDefault();
31
            $model->guardAgainstInvalidUploadOptions();
32
        });
33
34
        static::saving(function (Model $model) {
35
            $model->generateAllNewUploadFileNameAndSetAttribute();
36
        });
37
        static::saved(function (Model $model) {
38
            $model->uploadFiles();
39
        });
40
41
        static::updating(function (Model $model) {
42
            $model->generateAllNewUploadFileNameAndSetAttribute();
43
        });
44
        static::updated(function (Model $model) {
45
            $model->uploadFiles();
46
        });
47
48
        static::deleting(function (Model $model) {
49
            $model->uploadOptions = $model->getUploadOptionsOrDefault();
50
            $model->guardAgainstInvalidUploadOptions();
51
        });
52
53
        static::deleting(function (Model $model) {
54
            $model->uploadOptions = $model->getUploadOptionsOrDefault();
55
            $model->guardAgainstInvalidUploadOptions();
56
        });
57
58
        static::deleted(function (Model $model) {
59
            $model->deleteUploadedFiles();
60
        });
61
    }
62
63
    /**
64
     * Retrive a specifice UploadOptions for this model, or return default UploadOptions
65
     * @return UploadOptions
66
     */
67
    public function getUploadOptionsOrDefault() : UploadOptions
68
    {
69
        if ($this->uploadOptions) {
70
            return $this->uploadOptions;
71
        }
72
73
        if (method_exists($this, 'getUploadOptions')) {
74
            $method = 'getUploadOptions';
75
            $this->uploadOptions = $this->{$method}();
76
        } else {
77
            $this->uploadOptions = UploadOptions::create()->getUploadOptionsDefault()
78
                ->setUploadBasePath(public_path('upload/' . $this->getTable()));
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
79
        }
80
81
        return $this->uploadOptions;
82
    }
83
84
    /**
85
     * This function will throw an exception when any of the options is missing or invalid.
86
     * @throws InvalidOption
87
     */
88
    public function guardAgainstInvalidUploadOptions()
89
    {
90
        if (!count($this->uploadOptions->uploads)) {
91
            throw InvalidOption::missingUploadFields();
92
        }
93
        if ($this->uploadOptions->uploadBasePath===null || $this->uploadOptions->uploadBasePath=='') {
94
            throw InvalidOption::missingUploadBasePath();
95
        }
96
    }
97
98
    /**
99
     * Handle file upload.
100
     */
101
    public function uploadFiles()
102
    {
103
        //invalid model
104
        if ($this->id < 1) {
0 ignored issues
show
Bug introduced by
The property id does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
105
            return;
106
        }
107
108
        //check request for valid files and server for correct paths defined in model
109
        if (!$this->requestHasValidFilesAndCorrectPaths()) {
110
            return;
111
        }
112
113
        //loop for every upload model attributes and do upload if has a file in request
114
        foreach ($this->getUploadsAttributesSafe() as $uploadField) {
115
            $this->uploadFile($uploadField);
116
        }
117
    }
118
119
    /**
120
     * Upload a file releted to a passed attribute name
121
     * @param string $uploadField
122
     */
123
    public function uploadFile(string $uploadField)
124
    {
125
        //check if there is a valid file in request for current attribute
126
        if(!RequestHelper::isValidCurrentRequestUploadFile($uploadField,$this->getUploadOptionsOrDefault()->uploadsMimeType)){
127
            return;
128
        }
129
130
        //retrive the uploaded file
131
        $uploadedFile = RequestHelper::getCurrentRequestFileSafe($uploadField);
132
        if ($uploadedFile===null) {
133
            return;
134
        }
135
136
        //do the work
137
        $this->doUpload($uploadedFile, $uploadField);
1 ignored issue
show
Bug introduced by
It seems like $uploadedFile defined by \Padosoft\Laravel\Reques...tFileSafe($uploadField) on line 131 can also be of type array; however, Padosoft\Uploadable\Uploadable::doUpload() does only seem to accept object<Illuminate\Http\UploadedFile>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
138
    }
139
140
    /**
141
     * Get an UploadedFile, generate new name, and save it in destination path.
142
     * Return empty string if it fails, otherwise return the saved file name.
143
     * @param UploadedFile $uploadedFile
144
     * @param string $uploadAttribute
145
     * @return string
146
     */
147
    public function doUpload(UploadedFile $uploadedFile, $uploadAttribute) : string
148
    {
149
        if (($this->id < 1) || !$uploadedFile || !$uploadAttribute) {
150
            return '';
151
        }
152
153
        //get file name by attribute
154
        $newName = $this->{$uploadAttribute};
155
156
        //get upload path to store
157
        $pathToStore = $this->getUploadFileBasePath($uploadAttribute);
158
159
        //delete if file already exists
160
        FileHelper::unlinkSafe($pathToStore . '/' . $newName);
161
162
        //move file to destination folder
163
        try {
164
            $targetFile = $uploadedFile->move($pathToStore, $newName);
165
        } catch (\Symfony\Component\HttpFoundation\File\Exception\FileException $e) {
166
            Log::warning('Error in doUpload() when try to move ' . $newName . ' to folder: ' . $pathToStore . PHP_EOL . $e->getMessage() . PHP_EOL . $e->getTraceAsString());
167
            return '';
168
        }
169
170
        return $targetFile ? $newName : '';
171
    }
172
173
    /**
174
     * Check request for valid files and server for correct paths defined in model
175
     * @return bool
176
     */
177
    protected function requestHasValidFilesAndCorrectPaths() : bool
178
    {
179
        //current request has not uploaded files
180
        if (!RequestHelper::currentRequestHasFiles()) {
181
            return false;
182
        }
183
184
        //ensure that all upload path are ok or create it.
185
        if (!$this->checkOrCreateAllUploadBasePaths()) {
186
            return false;
187
        }
188
189
        return true;
190
    }
191
192
    /**
193
     * Generate a new file name for uploaded file.
194
     * Return empty string if uploadedFile is null, otherwise return the new file name..
195
     * @param UploadedFile $uploadedFile
196
     * @param string $uploadField
197
     * @return string
198
     */
199
    public function generateNewUploadFileName(UploadedFile $uploadedFile, string $uploadField) : string
200
    {
201
        if (!$uploadField) {
202
            return '';
203
        }
204
        if (!$uploadedFile) {
205
            return '';
206
        }
207
208
        //check if file need a new name
209
        $newName = $this->calcolateNewUploadFileName($uploadedFile);
210
        if ($newName != '') {
211
            return $newName;
212
        }
213
214
        //no new file name, return original file name
215
        return $uploadedFile->getFilename();
216
    }
217
218
    /**
219
     * Check if file need a new name and return it, otherwise return empty string.
220
     * @param UploadedFile $uploadedFile
221
     * @return string
222
     */
223
    protected function calcolateNewUploadFileName(UploadedFile $uploadedFile) : string
224
    {
225
        if (!$this->getUploadOptionsOrDefault()->appendModelIdSuffixInUploadedFileName) {
226
            return '';
227
        }
228
229
        //retrive original file name and extension
230
        $filenameWithoutExtension = UploadedFileHelper::getFilenameWithoutExtension($uploadedFile);
231
        $ext = $uploadedFile->getClientOriginalExtension();
232
233
        $newName = $filenameWithoutExtension . $this->getUploadOptionsOrDefault()->uploadFileNameSuffixSeparator . $this->id . '.' . $ext;
234
        return $newName;
235
    }
236
237
    /**
238
     * delete all Uploaded Files
239
     */
240
    public function deleteUploadedFiles()
241
    {
242
        //loop for every upload model attributes
243
        foreach ($this->getUploadOptionsOrDefault()->uploads as $uploadField) {
244
            $this->deleteUploadedFile($uploadField);
245
        }
246
    }
247
248
    /**
249
     * Delete upload file related to passed attribute name
250
     * @param string $uploadField
251
     */
252
    public function deleteUploadedFile(string $uploadField)
253
    {
254
        if (!$uploadField) {
255
            return;
256
        }
257
258
        if (!$this->{$uploadField}) {
259
            return;
260
        }
261
262
        //retrive correct upload storage path for current attribute
263
        $uploadFieldPath = $this->getUploadFileBasePath($uploadField);
264
265
        //unlink file
266
        $path = sprintf("%s/%s", $uploadFieldPath, $this->{$uploadField});
267
        FileHelper::unlinkSafe($path);
268
269
        //reset model attribute and update db field
270
        $this->setBlanckAttributeAndDB($uploadField);
271
    }
272
273
    /**
274
     * Reset model attribute and update db field
275
     * @param string $uploadField
276
     */
277
    protected function setBlanckAttributeAndDB(string $uploadField)
278
    {
279
        //set to black attribute
280
        $this->{$uploadField} = '';
281
282
        //save on db (not call model save because invoke event and entering in loop)
283
        DB::table($this->getTable())
0 ignored issues
show
Bug introduced by
It seems like getTable() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
284
            ->where('id', $this->id)
285
            ->update([$uploadField => '']);
286
    }
287
288
    /**
289
     * Return true If All Upload atrributes Are Empty or
290
     * if the uploads array is not set.
291
     * @return bool
292
     */
293
    public function checkIfAllUploadFieldsAreEmpty() : bool
294
    {
295
        foreach ($this->getUploadsAttributesSafe() as $uploadField) {
296
            //for performance if one attribute has value exit false
297
            if ($this->{$uploadField}) {
298
                return false;
299
            }
300
        }
301
302
        return true;
303
    }
304
305
    /**
306
     * Check all attributes upload path, and try to create dir if not already exists.
307
     * Return false if it fails to create all founded dirs.
308
     * @return bool
309
     */
310
    public function checkOrCreateAllUploadBasePaths() : bool
311
    {
312
        foreach ($this->getUploadsAttributesSafe() as $uploadField) {
313
            if (!$this->checkOrCreateUploadBasePath($uploadField)) {
314
                return false;
315
            }
316
        }
317
318
        return true;
319
    }
320
321
    /**
322
     * Check uploads property and return a uploads class field
323
     * or empty array if somethings wrong.
324
     * @return array
325
     */
326
    public function getUploadsAttributesSafe() : array
327
    {
328
        if (!is_array($this->getUploadOptionsOrDefault()->uploads)) {
329
            return [];
330
        }
331
332
        return $this->getUploadOptionsOrDefault()->uploads;
333
    }
334
335
    /**
336
     * Check attribute upload path, and try to create dir if not already exists.
337
     * Return false if it fails to create the dir.
338
     * @param string $uploadField
339
     * @return bool
340
     */
341
    public function checkOrCreateUploadBasePath(string $uploadField) : bool
342
    {
343
        $uploadFieldPath = $this->getUploadFileBasePath($uploadField);
344
345
        return FileHelper::checkDirExistOrCreate($uploadFieldPath,
0 ignored issues
show
Bug introduced by
The method checkDirExistOrCreate() does not seem to exist on object<Padosoft\Io\FileHelper>.

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...
346
            $this->getUploadOptionsOrDefault()->uploadCreateDirModeMask);
347
    }
348
349
    /**
350
     * Return the upload path for the passed attribute and try to create it if not exists.
351
     * Returns empty string if dir if not exists and fails to create it.
352
     * @param string $uploadField
353
     * @return string
354
     */
355
    public function getUploadFileBasePath(string $uploadField) : string
356
    {
357
        //default model upload path
358
        $uploadFieldPath = $this->getUploadOptionsOrDefault()->uploadBasePath;
359
360
        //overwrite if there is specific path for the field
361
        $specificPath = $this->getUploadFileBasePathSpecific($uploadField);
362
        if ($specificPath != '') {
363
            $uploadFieldPath = $specificPath;
364
        }
365
366
        //check if exists or try to create dir
367
        if (!FileHelper::checkDirExistOrCreate($uploadFieldPath,
0 ignored issues
show
Bug introduced by
The method checkDirExistOrCreate() does not seem to exist on object<Padosoft\Io\FileHelper>.

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...
368
            $this->getUploadOptionsOrDefault()->uploadCreateDirModeMask)
369
        ) {
370
            return '';
371
        }
372
373
        return $uploadFieldPath;
374
    }
375
376
    /**
377
     * Return the specific upload path (by uploadPaths prop) for the passed attribute if exists, otherwise return empty string.
378
     * @param string $uploadField
379
     * @return string
380
     */
381
    public function getUploadFileBasePathSpecific(string $uploadField) : string
382
    {
383
        //check if there is a specified upload path
384
        if (!empty($this->getUploadOptionsOrDefault()->uploadPaths) && count($this->getUploadOptionsOrDefault()->uploadPaths) > 0 && array_key_exists($uploadField,
385
                $this->getUploadOptionsOrDefault()->uploadPaths)
386
        ) {
387
            return public_path($this->getUploadOptionsOrDefault()->uploadPaths[$uploadField]);
388
        }
389
390
        return '';
391
    }
392
393
    /**
394
     * Return the full (path+filename) upload abs path for the passed attribute.
395
     * Returns empty string if dir if not exists.
396
     * @param string $uploadField
397
     * @return string
398
     */
399
    public function getUploadFileFullPath(string $uploadField) : string
400
    {
401
        $uploadFieldPath = $this->getUploadFileBasePath($uploadField);
402
        $uploadFieldPath = DirHelper::addFinalSlash($uploadFieldPath) . $this->{$uploadField};
403
404
        if ($uploadFieldPath === null || $uploadFieldPath == '' || $uploadFieldPath == '/') {
405
            return '';
406
        }
407
408
        return $uploadFieldPath;
409
    }
410
411
    /**
412
     * Return the full url (base url + filename) for the passed attribute.
413
     * Returns empty string if dir if not exists.
414
     * Ex.:  http://localhost/laravel/public/upload/news/pippo.jpg
415
     * @param string $uploadField
416
     * @return string
417
     */
418 View Code Duplication
    public function getUploadFileUrl(string $uploadField) : string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
419
    {
420
        $fallBack = '';
421
422
        $Url = $this->getUploadFileFullPath($uploadField);
423
        if($Url===null || $Url=='')
424
        {
425
            return $fallBack;
426
        }
427
428
        $uploadFieldPath = str_replace(public_path(), '', $Url);
429
430
        if ($uploadFieldPath === null || $uploadFieldPath == '' || $uploadFieldPath == '/') {
431
            return $fallBack;
432
        }
433
434
        return URL::to($uploadFieldPath);
435
    }
436
    /**
437
     * Return the base url (without filename) for the passed attribute.
438
     * Returns empty string if dir if not exists.
439
     * Ex.:  http://localhost/laravel/public/upload/
440
     * @param string $uploadField
441
     * @return string
442
     */
443 View Code Duplication
    public function getUploadFileBaseUrl(string $uploadField) : string
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
444
    {
445
        $fallBack = '';
446
447
        $uploadFieldPath = $this->getUploadFileBasePath($uploadField);
448
        if($uploadFieldPath===null || $uploadFieldPath=='')
449
        {
450
            return $fallBack;
451
        }
452
453
        $uploadFieldPath = DirHelper::addFinalSlash(str_replace(public_path(), '', $uploadFieldPath));
454
455
        if ($uploadFieldPath === null || $uploadFieldPath == '' || $uploadFieldPath == '/') {
456
            return $fallBack;
457
        }
458
459
        return URL::to($uploadFieldPath);
460
    }
461
462
    /**
463
     * Calcolate the new name for ALL uploaded files and set relative upload attributes
464
     */
465
    public function generateAllNewUploadFileNameAndSetAttribute()
466
    {
467
        foreach ($this->getUploadsAttributesSafe() as $uploadField) {
468
            $this->generateNewUploadFileNameAndSetAttribute($uploadField);
469
        }
470
    }
471
472
    /**
473
     * Calcolate the new name for uploaded file relative to passed attribute name and set the upload attribute
474
     * @param string $uploadField
475
     */
476
    public function generateNewUploadFileNameAndSetAttribute(string $uploadField)
477
    {
478
        if ($uploadField === null || trim($uploadField) == '') {
479
            return;
480
        }
481
482
        //generate new file name
483
        $uploadedFile = RequestHelper::getCurrentRequestFileSafe($uploadField);
484
        if ($uploadedFile === null) {
485
            return;
486
        }
487
        $newName = $this->generateNewUploadFileName($uploadedFile, $uploadField);
0 ignored issues
show
Bug introduced by
It seems like $uploadedFile defined by \Padosoft\Laravel\Reques...tFileSafe($uploadField) on line 483 can also be of type array; however, Padosoft\Uploadable\Uplo...rateNewUploadFileName() does only seem to accept object<Illuminate\Http\UploadedFile>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
488
        if ($newName == '') {
489
            return;
490
        }
491
492
        //set attribute
493
        $this->{$uploadField} = $newName;
494
    }
495
}
496