HasFileUpload   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 26
c 2
b 1
f 0
dl 0
loc 39
rs 10
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A fileUpload() 0 37 4
1
<?php
2
3
namespace Adminetic\Website\Traits;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Facades\File;
7
use Illuminate\Support\Facades\Storage;
8
9
trait HasFileUpload
10
{
11
    public function fileUpload($file, $directory, $given_name = null)
12
    {
13
        if (! $file->isValid()) {
14
            throw new \Exception('File was not uploaded successfully');
15
        }
16
17
        /** Check if folder exits or not. If not then create the folder */
18
        if (! File::exists(storage_path($directory))) {
19
            File::makeDirectory(storage_path($directory), 0775, true);
20
        }
21
22
        $original_name = strtolower(str_replace([' ', '-', '$', '<', '>', '&', '{', '}', '*', '\\', '/', ':', '.', ';', ',', "'", '"'], '_', trim($given_name ?? pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME))));
0 ignored issues
show
Bug introduced by
It seems like $given_name ?? pathinfo(...aits\PATHINFO_FILENAME) can also be of type array; however, parameter $string of trim() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

22
        $original_name = strtolower(str_replace([' ', '-', '$', '<', '>', '&', '{', '}', '*', '\\', '/', ':', '.', ';', ',', "'", '"'], '_', trim(/** @scrutinizer ignore-type */ $given_name ?? pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME))));
Loading history...
23
        $timestamp = Carbon::now()->toDateString();
24
        $extension = $file->getClientOriginalExtension();
25
        $size = $file->getSize();
26
        $name = str_replace(' ', '', $original_name.'-'.Carbon::now()->toDateString().'-'.$size.'.'.$file->getClientOriginalExtension());
27
28
        $disk = config('filesystems.default', 'public');
29
30
        $path = null;
31
        if ($disk == 'public') {
32
            $path = $file->storeAs($directory, $name, 'public');
33
        } else {
34
            $path = Storage::disk($disk)->putFileAs(
35
                $directory,
36
                $file,
37
                $name
38
            );
39
        }
40
41
        return json_decode(json_encode([
42
            'original_name' => $original_name ?? null,
43
            'timestamp' => $timestamp ?? null,
44
            'extension' => $extension ?? null,
45
            'size' => $size ?? null,
46
            'name' => $name ?? null,
47
            'path' => $path ?? null,
48
        ]));
49
    }
50
}
51