Passed
Push — master ( 9c82b2...472045 )
by Prateek
07:54 queued 04:44
created

UploadController   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 137
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 19
eloc 73
dl 0
loc 137
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A uploadGallery() 0 22 4
A upload() 0 19 2
A delete() 0 19 2
A getWritableFilename() 0 10 4
A process() 0 19 3
A getPath() 0 6 2
A validateUpload() 0 18 2
1
<?php
2
namespace App\Http\Controllers\Backend;
3
4
use App\Http\Controllers\Controller;
5
use Illuminate\Http\Request;
6
use Symfony\Component\Filesystem\Filesystem;
7
use Validator;
8
use Image;
9
10
/**
11
 * Class UploadController.
12
 */
13
class UploadController extends Controller
14
{
15
    /**
16
     * @return json
17
     * 
18
     */
19
    protected $validation_error = [];
20
21
    public function upload(Request $request)
22
    {
23
        $file = $request->file('file');
24
        $moduleName = $request->input('moduleName');
25
        $field = $request->input('field');
26
27
        $valid = $this->validateUpload($file, $moduleName, $field);
28
29
        if($valid){
30
            $imagename = $this->getWritableFilename(str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'.'.$file->getClientOriginalExtension(), $moduleName, true);;
0 ignored issues
show
Deprecated Code introduced by
The function str_slug() has been deprecated: Str::slug() should be used directly instead. Will be removed in Laravel 5.9. ( Ignorable by Annotation )

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

30
            $imagename = $this->getWritableFilename(/** @scrutinizer ignore-deprecated */ str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'.'.$file->getClientOriginalExtension(), $moduleName, true);;

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
31
    
32
            $destinationPath = storage_path('images/'.$moduleName);
33
    
34
            $file->move($destinationPath, $imagename);
35
    
36
            return response()->json(['message' => 'File successfully uploaded', 'filename' => $imagename, 'status' => 200], 200);
37
        }
38
39
        return response()->json(['message' => $this->validation_error, 'filename' => false, 'status' => 500], 200);
40
    }
41
    
42
    public function uploadGallery(Request $request)
43
    {
44
        $moduleName = $request->input('moduleName');
45
        $field = $request->input('field');
0 ignored issues
show
Unused Code introduced by
The assignment to $field is dead and can be removed.
Loading history...
46
        $files = [];
47
48
        foreach ($request->file('file') as $file) {
49
            $imagename = $this->getWritableFilename(str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'.'.$file->getClientOriginalExtension(), $moduleName, true);;
0 ignored issues
show
Deprecated Code introduced by
The function str_slug() has been deprecated: Str::slug() should be used directly instead. Will be removed in Laravel 5.9. ( Ignorable by Annotation )

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

49
            $imagename = $this->getWritableFilename(/** @scrutinizer ignore-deprecated */ str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME)).'.'.$file->getClientOriginalExtension(), $moduleName, true);;

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
50
            $destinationPath = storage_path('images/'.$moduleName);
51
            try {
52
                $file->move($destinationPath, $imagename);
53
                $files[] = $imagename;
54
            } catch (\Throwable $th) {
55
                $error = $th->getMessage();
56
            }
57
        }
58
59
        if(!isset($error)){
60
            return response()->json(['message' => 'File successfully uploaded', 'filenames' => $files, 'status' => 200], 200);
61
        }
62
63
        return response()->json(['message' => $error, 'filename' => false, 'status' => 500], 200);
64
    }
65
66
    public function delete(Request $request)
67
    {
68
        $moduleName = $request->input('modelName');
69
        $modelToCall = "App\\Models\\" . ucfirst($moduleName);
70
        $model = $modelToCall::find($request->input('modelId'));
71
        $field = $request->input('field');
72
        $filename = $model->$field;
73
        $filePath = public_path('images/'.$moduleName.'/'.$filename);
74
        $fileSystem = new Filesystem;
75
76
        try {
77
            $fileSystem->remove($filePath);
78
        } catch (\Exception $ex) {
79
            return response()->json(['message' => 'File removal failed'], 500);
80
        }
81
82
        $model->$field = null;
83
        $model->save();
84
        return response()->json(['message' => 'File successfully removed'], 200);
85
    }
86
87
    /**
88
     * @return string
89
     */
90
    public function process($filename, $moduleName)
91
    {
92
        $messages=['errors'=>[]];
93
        $tempFile = storage_path('images/'.$moduleName.'/'.$filename);
94
        $fileToWrite = $this->getWritableFilename($filename, $moduleName);
95
96
        $tempImage = Image::make($tempFile);
97
98
        $methodToUse = $tempImage->width() > $tempImage->height() ? 'widen' : 'heighten';
99
100
        try {
101
            $tempImage->$methodToUse(2000, function ($constraint){
102
                $constraint->upsize();
103
            })->save($fileToWrite);
104
            $messages['success']['filename'] = $fileToWrite;
105
        } catch (\Exception $ex) {
106
            $messages['errors'][] = [ 'fileError' => $ex->getMessage()];
107
        }
108
        return $messages;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $messages returns the type array<string,array> which is incompatible with the documented return type string.
Loading history...
109
    }
110
111
    protected function getWritableFilename($filename, $moduleName, $is_storage=false)
112
    {
113
        $dir = $is_storage ? $this->getPath(storage_path('images/'.$moduleName)) : $this->getPath(public_path('images/'.$moduleName));
114
        $path = $dir.'/'.$filename;
115
        if (file_exists($path)) {
116
            $filename = pathinfo($path, PATHINFO_FILENAME);
117
            $filename .= rand(0,9).'.'.pathinfo($path, PATHINFO_EXTENSION);
118
            return $this->getWritableFilename($filename, $moduleName, $is_storage); 
119
        }else{
120
            return $is_storage ? $filename : $path;
121
        }
122
    }
123
124
    protected function getPath($path)
125
    {
126
        if (!is_dir($path))
127
            mkdir($path, 0755, true);
128
129
        return $path;
130
    }
131
132
    protected function validateUpload($file, $moduleName, $field)
133
    {
134
135
        $moduleData = config('laragen.modules')[str_plural($moduleName)];
0 ignored issues
show
Deprecated Code introduced by
The function str_plural() has been deprecated: Str::plural() should be used directly instead. Will be removed in Laravel 5.9. ( Ignorable by Annotation )

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

135
        $moduleData = config('laragen.modules')[/** @scrutinizer ignore-deprecated */ str_plural($moduleName)];

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
136
        $rules = $moduleData[$field];
137
138
        $file = array($field => $file);
139
140
        $validator = Validator::make($file , [
141
            $field => $rules,
142
        ]);
143
144
        if ($validator->passes())
145
        {
146
            return true; 
147
        }
148
        $this->validation_error = $validator->errors()->all();
149
        return false;
150
    }
151
}
152