Passed
Push — dev5 ( c2dc0b...cbc2fc )
by Ron
08:19
created

TechTipsController::storeUpdatedTip()   B

Complexity

Conditions 7
Paths 28

Size

Total Lines 55
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 7.0671

Importance

Changes 0
Metric Value
cc 7
eloc 26
c 0
b 0
f 0
nc 28
nop 2
dl 0
loc 55
ccs 24
cts 27
cp 0.8889
crap 7.0671
rs 8.5706

How to fix   Long Method   

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 App\Http\Controllers\TechTips;
4
5
use App\Domains\Equipment\GetEquipmentData;
6
use App\Domains\TechTips\GetTechTips;
7
use App\User;
8
use App\Files;
9
use App\TechTips;
10
use App\TechTipFavs;
11
use App\TechTipFiles;
12
use App\TechTipTypes;
13
use App\TechTipSystems;
14
use Illuminate\Http\File;
15
use App\SystemCategories;
16
use Illuminate\Http\Request;
17
use App\Notifications\NewTechTip;
18
use Illuminate\Http\UploadedFile;
19
use Illuminate\Support\Facades\Log;
20
use App\Http\Controllers\Controller;
21
use Illuminate\Support\Facades\Auth;
22
use Illuminate\Support\Facades\Route;
23
use Illuminate\Support\Facades\Storage;
24
use App\Http\Resources\TechTipsCollection;
25
use Illuminate\Support\Facades\Notification;
26
use App\Http\Resources\TechTipTypesCollection;
27
use App\Http\Resources\SystemCategoriesCollection;
28
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
29
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
30
use App\Http\Resources\SystemCategoriesCollection as CategoriesCollection;
31
32
33
use App\Domains\TechTips\GetTechTipTypes;
34
use App\Domains\TechTips\SetTechTips;
35
use App\Http\Requests\TechTipNewTipRequest;
36
use App\Http\Requests\TechTipProcessImageRequest;
37
use App\Http\Requests\TechTipSearchRequest;
38
39
class TechTipsController extends Controller
40
{
41 78
    public function __construct()
42
    {
43 78
        $this->middleware('auth');
44 78
    }
45
46
    //  Tech Tips landing page
47 2
    public function index()
48
    {
49 2
        return view('tips.index', [
50 2
            'tipTypes' => (new GetTechTipTypes)->execute(true),
51 2
            'sysTypes' => (new GetEquipmentData)->getAllEquipmentWithDataList(),
52
        ]);
53
    }
54
55
    //  Search for an existing tip - If no paramaters, return all tips
56 8
    public function search(TechTipSearchRequest $request)
57
    {
58 8
        return (new GetTechTips)->searchTips($request);
59
    }
60
61
    //  Process an image that is attached to a tech tip
62 4
    public function processImage(TechTipProcessImageRequest $request)
63
    {
64 4
        $this->authorize('hasAccess', 'Create Tech Tip');
65
66 2
        $imgLocation = (new SetTechTips)->processTipImage($request);
67 2
        return response()->json(['location' => $imgLocation]);
68
69
    }
70
71
    //  Create a new Tech Tip form
72 4
    public function create()
73
    {
74 4
        $this->authorize('hasAccess', 'Create Tech Tip');
75
76 2
        return view('tips.create', [
77 2
            'tipTypes' => (new GetTechTipTypes)->execute(true),
78 2
            'sysTypes' => (new GetEquipmentData)->getAllEquipmentWithDataList(),
79
        ]);
80
    }
81
82
    //  Submit the form to create a new tech tip
83 6
    public function store(TechTipNewTipRequest $request)
84
    {
85 6
        $this->authorize('hasAccess', 'Create Tech Tip');
86
87 4
        $tipData = (new SetTechTips)->processNewTip($request);
88 4
        return response()->json(['success' => $tipData]);
89
    }
90
91
92
93
94
95
96
97
98
    //  Details controller - will move to the show controller with just the tech tip id
99 2
    public function details($id, $subject)
100
    {
101 2
        if(session()->has('newTipFile')) {
102
            session()->forget('newTipFile');
103
        }
104
105 2
        return $this->show($id);
106
    }
107
108
    //  Show the details about the tech tip
109 2
    public function show($id)
110
    {
111 2
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
112
113 2
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->first();
114
115 2
        if(!$tipData)
116
        {
117
            return view('tips.tipNotFound');
118
        }
119
120 2
        $isFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
121 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
122
123 2
        return view('tips.details', [
124 2
            'details' => $tipData,
125 2
            'isFav'   => empty($isFav) ? 'false' : 'true',
126 2
            'files'   => $files,
127
        ]);
128
    }
129
130
    //  Add or remove this tip as a favorite of the user
131
    public function toggleFav($action, $id)
132
    {
133
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
134
135
        switch($action) {
136
            case 'add':
137
                TechTipFavs::create([
138
                    'user_id' => Auth::user()->user_id,
139
                    'tip_id' => $id
140
                ]);
141
                break;
142
            case 'remove':
143
                $tipFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
144
                $tipFav->delete();
145
                break;
146
        }
147
148
        Log::debug('Tech Tip Bookmark Updated.', [
149
            'user_id' => Auth::user()->user_id,
150
            'tip_id' => $id,
151
            'action'  => $action
152
        ]);
153
        return response()->json(['success' => true]);
154
    }
155
156
    //  Edit an existing tech tip
157 6
    public function edit($id)
158
    {
159 6
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
160
161 6
        $this->authorize('hasAccess', 'Edit Tech Tip');
162 4
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->with('TechTipTypes')->first();
163
164 4
        if(!$tipData) {
165 2
            return view('tips.tipNotFound');
166
        }
167
168 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
169 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
170 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
171
172 2
        return view('tips.editTip', [
173 2
            'tipTypes' => $typesArr,
174 2
            'sysTypes' => $systemsArr,
175 2
            'details' => $tipData,
176 2
            'files'   => $files,
177
        ]);
178
    }
179
180
    //  Store the edited Tech Tip
181 14
    public function update(Request $request, $id)
182
    {
183 14
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
184
185 14
        $this->authorize('hasAccess', 'Edit Tech Tip');
186
187 12
        $request->validate([
188 12
            'subject'   => 'required',
189
            'equipment' => 'required',
190
            'tipType'   => 'required',
191
            'tip'       => 'required',
192
        ]);
193
194 4
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
195
196
        //  Verify if there is a file to be processed or not
197 4
        if($receiver->isUploaded() === false || $request->_completed) {
198 4
            $this->storeUpdatedTip($request, $id);
199 4
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
200 4
            return response()->json(['tip_id' => $id]);
201
        }
202
203
        //  Recieve and process the file
204
        $save = $receiver->receive();
205
206
        //  See if the uploade has finished
207
        if($save->isFinished()) {
208
            $this->saveFile($save->getFile(), $id);
0 ignored issues
show
Bug introduced by
The method saveFile() does not exist on App\Http\Controllers\TechTips\TechTipsController. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

208
            $this->/** @scrutinizer ignore-call */ 
209
                   saveFile($save->getFile(), $id);
Loading history...
209
210
            return 'uploaded successfully';
211
        }
212
213
        //  Get the current progress
214
        $handler = $save->handler();
215
216
        Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
217
        return response()->json([
218
            'done'   => $handler->getPercentageDone(),
219
            'status' => true
220
        ]);
221
    }
222
223
    //  Store the updated tip
224 4
    public function storeUpdatedTip($tipData, $id)
225
    {
226 4
        $this->authorize('hasAccess', 'Edit Tech Tip');
227
228
        //  Remove any forward slash (/) from the Subject Field
229 4
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
230
231
        //  Enter the tip details and return the tip ID
232 4
        TechTips::find($id)->update([
233 4
            'tip_type_id' => $tipData->tipType,
234 4
            'subject'     => $tipData->subject,
235 4
            'description' => $tipData->tip,
236
            // 'user_id'     => Auth::user()->user_id TODO - updated user who modified tip
237
        ]);
238
239
        //  Add any additional equipment types to the tip
240 4
        $tipEquip = TechTipSystems::where('tip_id', $id)->get();
241 4
        foreach($tipData->equipment as $equip)
242
        {
243 4
            $found = false;
244 4
            foreach($tipEquip as $key => $value)
245
            {
246 4
                if($equip['sys_id'] == $value->sys_id)
247
                {
248
                    $tipEquip->forget($key);
249
                    $found = true;
250
                    break;
251
                }
252
            }
253 4
            if(!$found)
254
            {
255 4
                TechTipSystems::create([
256 4
                    'tip_id' => $id,
257 4
                    'sys_id' => $equip['sys_id'],
258
                ]);
259
            }
260
        }
261
262
        //  Remove the remainaing equipment types that have been removed
263 4
        foreach($tipEquip as $remaining)
264
        {
265 4
            TechTipSystems::find($remaining->tip_tag_id)->delete();
266
        }
267
268
        //  Remove any files that no longer apply
269 4
        foreach($tipData->deletedFileList as $file)
270
        {
271 2
            $file = TechTipFiles::find($file);
272 2
            $fileID = $file->file_id;
273 2
            $file->delete();
274
            //  Try to delete the file itself
275 2
            Files::deleteFile($fileID);
276
        }
277
278 4
        return true;
279
    }
280
281
    //  Soft delet the Tech Tip
282 4
    public function destroy($id)
283
    {
284 4
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
285
286 4
        $this->authorize('hasAccess', 'Delete Tech Tip');
287
288
        //  Remove the Tip from any users favorites
289 2
        TechTipFavs::where('tip_id', $id)->delete();
290
291
        //  Disable the tip
292 2
        TechTips::find($id)->delete();
293 2
        Log::warning('User - '.Auth::user()->user_id.' deleted Tech Tip ID - '.$id);
294 2
        return response()->json(['success' => true]);
295
    }
296
}
297