Passed
Push — master ( 3b9459...1d6d9a )
by Ron
11:07 queued 34s
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\User;
6
use App\Files;
7
use App\TechTips;
8
use App\TechTipFavs;
9
use App\TechTipFiles;
10
use App\TechTipTypes;
11
use App\TechTipSystems;
12
use Illuminate\Http\File;
13
use App\SystemCategories;
14
use Illuminate\Http\Request;
15
use App\Notifications\NewTechTip;
16
use Illuminate\Http\UploadedFile;
17
use Illuminate\Support\Facades\Log;
18
use App\Http\Controllers\Controller;
19
use Illuminate\Support\Facades\Auth;
20
use Illuminate\Support\Facades\Route;
21
use Illuminate\Support\Facades\Storage;
22
use App\Http\Resources\TechTipsCollection;
23
use Illuminate\Support\Facades\Notification;
24
use App\Http\Resources\TechTipTypesCollection;
25
use App\Http\Resources\SystemCategoriesCollection;
26
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
27
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
28
use App\Http\Resources\SystemCategoriesCollection as CategoriesCollection;
29
30
class TechTipsController extends Controller
31
{
32 80
    public function __construct()
33
    {
34 80
        $this->middleware('auth');
35 80
    }
36
37
    //  Tech Tips landing page
38 2
    public function index()
39
    {
40 2
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name);
41
42 2
        $tipTypes = new TechTipTypesCollection(TechTipTypes::all());
43 2
        $sysList  = new CategoriesCollection(SystemCategories::with('SystemTypes')->with('SystemTypes.SystemDataFields.SystemDataFieldTypes')->get());
44 2
        return view('tips.index', [
45 2
            'tipTypes' => $tipTypes,
46 2
            'sysTypes' => $sysList,
47
        ]);
48
    }
49
50
    //  Search for an existing tip - If no paramaters, return all tips
51 8
    public function search(Request $request)
52
    {
53 8
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
54
55
        //  See if there are any search paramaters entered
56 8
        if (!$request->search['searchText'] && !isset($request->search['articleType']) && !isset($request->search['systemType'])) {
57
            //  No search paramaters, send all tech tips
58 2
            $tips = new TechTipsCollection(
59 2
                TechTips::orderBy('created_at', 'DESC')
60 2
                    ->with('SystemTypes')
61 2
                    ->paginate($request->pagination['perPage'])
62
            );
63
        } else {
64 6
            $article = isset($request->search['articleType']) ? true : false;
65 6
            $system  = isset($request->search['systemType'])  ? true : false;
66
            //  Search paramaters, filter results
67 6
            $tips = new TechTipsCollection(
68 6
                TechTips::orderBy('created_at', 'DESC')
69
                    //  Search by id or a phrase in the title or description
70
                    ->where(function ($query) use ($request) {
71 6
                        $query->where('subject', 'like', '%' . $request->search['searchText'] . '%')
72 6
                            ->orWhere('tip_id', 'like', '%' . $request->search['searchText'] . '%')
73 6
                            ->orWhere('description', 'like', '%' . $request->search['searchText'] . '%');
74 6
                    })
75
                    ->when($article, function ($query) use ($request) {
76 2
                        $query->whereIn('tip_type_id', $request->search['articleType']);
77 6
                    })
78
                    ->when($system, function ($query) use ($request) {
79
                        $query->whereHas('SystemTypes', function ($query) use ($request) {
80 2
                            $query->whereIn('system_types.sys_id', $request->search['systemType']);
81 2
                        });
82 6
                    })
83 6
                    ->with('SystemTypes')
84 6
                    ->paginate($request->pagination['perPage'])
85
            );
86
        }
87
88 8
        return $tips;
89
    }
90
91
    //  Process an image that is attached to a tech tip
92 6
    public function processImage(Request $request)
93
    {
94 6
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
95
96 6
        $this->authorize('hasAccess', 'Create Tech Tip');
97
98 4
        $request->validate([
99 4
            'file' => 'mimes:jpeg,bmp,png,jpg,gif'
100
        ]);
101
102
        //  Generate a unique hash as the file name and store it in a publicly accessable folder
103 2
        $path = 'img/tip_img';
104 2
        $location = Storage::disk('public')->putFile($path, new File($request->file));
105
106
        //  Return the full url path to the image
107 2
        return response()->json(['location' => Storage::url($location)]);
108
    }
109
110
    //  Create a new Tech Tip form
111 4
    public function create()
112
    {
113 4
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name);
114 4
        $this->authorize('hasAccess', 'Create Tech Tip');
115
116 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
117 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
118
119 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
120 2
        return view('tips.create', [
121 2
            'tipTypes' => $typesArr,
122 2
            'sysTypes' => $systemsArr,
123
        ]);
124
    }
125
126
    //  Submit the form to create a new tech tip
127 14
    public function store(Request $request)
128
    {
129 14
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
130
131 14
        $this->authorize('hasAccess', 'Create Tech Tip');
132
133 12
        $request->validate([
134 12
            'subject'   => 'required',
135
            'equipment' => 'required',
136
            'tipType'   => 'required',
137
            'tip'       => 'required',
138
        ]);
139
140 4
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
141
142
        //  Verify if there is a file to be processed or not
143 4
        if($receiver->isUploaded() === false || $request->_completed)
144
        {
145 4
            Log::debug('about to create a tip');
146 4
            $tipID = $this->createTip($request);
147 4
            return response()->json(['tip_id' => $tipID]);
148
        }
149
150
        //  Recieve and process the file
151 2
        $save = $receiver->receive();
152
153
        //  See if the uploade has finished
154 2
        if ($save->isFinished()) {
155 2
            $this->saveFile($save->getFile());
156
157 2
            return 'uploaded successfully';
158
        }
159
160
        //  Get the current progress
161
        $handler = $save->handler();
162
163
        Log::debug('File being uploaded.  Percentage done - ' . $handler->getPercentageDone());
164
        return response()->json([
165
            'done'   => $handler->getPercentageDone(),
166
            'status' => true
167
        ]);
168
    }
169
170
    //  Save a file attached to the link
171 4
    private function saveFile(UploadedFile $file, $id = '_tmp')
172
    {
173 4
        $filePath = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$id;
174
175
        //  Clean the file and store it
176 4
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
177 4
        $file->storeAs($filePath, $fileName);
178
179
        //  Place file in Files table of DB
180 4
        $newFile = Files::create([
181 4
            'file_name' => $fileName,
182 4
            'file_link' => $filePath.DIRECTORY_SEPARATOR
183
        ]);
184 4
        $fileID = $newFile->file_id;
185
186
        //  Save the file ID in the session array
187 4
        if($id === '_tmp')
188
        {
189 2
            $fileArr = session('newTipFile') != null ? session('newTipFile') : [];
190 2
            $fileArr[] = $fileID;
191 2
            session(['newTipFile' => $fileArr]);
192
        }
193
        else
194
        {
195 2
            TechTipFiles::create([
196 2
                'tip_id' => $id,
197 2
                'file_id' => $fileID,
198
            ]);
199
        }
200
201
        //  Log stored file
202 4
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath . DIRECTORY_SEPARATOR . $fileName]);
203 4
        return $fileID;
204
    }
205
206
    //  Create the tech tip
207 4
    private function createTip($tipData)
208
    {
209
        //  Remove any forward slash (/) from the Subject Field
210 4
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
211
212
        //  Enter the tip details and return the tip ID
213 4
        $tip = TechTips::create([
214 4
            'tip_type_id' => $tipData->tipType,
215 4
            'subject'     => $tipData->subject,
216 4
            'description' => $tipData->tip,
217 4
            'user_id'     => Auth::user()->user_id
218
        ]);
219 4
        $tipID = $tip->tip_id;
220
221 4
        foreach($tipData->equipment as $sys)
222
        {
223 4
            TechTipSystems::create([
224 4
                'tip_id' => $tipID,
225 4
                'sys_id' => $sys['sys_id']
226
            ]);
227
        }
228
229
        //  If there were any files uploaded, move them to the proper folder
230 4
        if(session('newTipFile') != null)
231
        {
232 2
            $files = session('newTipFile');
233 2
            $path = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$tipID;
234 2
            foreach($files as $file)
235
            {
236 2
                $data = Files::find($file);
237
                //  Move the file to the proper folder
238 2
                Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
239
                // Update the database
240 2
                $data->update([
241 2
                    'file_link' => $path.DIRECTORY_SEPARATOR
242
                ]);
243
244 2
                TechTipFiles::create([
245 2
                    'tip_id' => $tipID,
246 2
                    'file_id' => $data->file_id
247
                ]);
248
            }
249
        }
250
251
        //  Send out the notifications
252 4
        if(!$tipData->supressEmail)
253
        {
254 4
            $details = TechTips::find($tipID);
255
            $users = User::whereHas('UserSettings', function($query)
256
            {
257 4
                $query->where('em_tech_tip', 1);
258 4
            })->get();
259
260 4
            Notification::send($users, new NewTechTip($details));
261
        }
262
263 4
        Log::info('New Tech Tip created by '.Auth::user()->full_name.'.  Tip Data - ', $tip->toArray());
264 4
        return $tipID;
265
    }
266
267
    //  Details controller - will move to the show controller with just the tech tip id
268 2
    public function details($id, $subject)
269
    {
270 2
        if (session()->has('newTipFile')) {
271
            session()->forget('newTipFile');
272
        }
273
274 2
        return $this->show($id);
275
    }
276
277
    //  Show the details about the tech tip
278 2
    public function show($id)
279
    {
280 2
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name);
281
282 2
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->first();
283
284 2
        if(!$tipData)
285
        {
286
            return view('tips.tipNotFound');
287
        }
288
289 2
        $isFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
290 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
291
292 2
        return view('tips.details', [
293 2
            'details' => $tipData,
294 2
            'isFav'   => empty($isFav) ? 'false' : 'true',
295 2
            'files'   => $files,
296
        ]);
297
    }
298
299
    //  Add or remove this tip as a favorite of the user
300
    public function toggleFav($action, $id)
301
    {
302
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name);
303
304
        switch ($action) {
305
            case 'add':
306
                TechTipFavs::create([
307
                    'user_id' => Auth::user()->user_id,
308
                    'tip_id' => $id
309
                ]);
310
                break;
311
            case 'remove':
312
                $tipFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
313
                $tipFav->delete();
314
                break;
315
        }
316
317
        Log::debug('Tech Tip Bookmark Updated.', [
318
            'user_id' => Auth::user()->user_id,
319
            'tip_id' => $id,
320
            'action'  => $action
321
        ]);
322
        return response()->json(['success' => true]);
323
    }
324
325
    //  Edit an existing tech tip
326 6
    public function edit($id)
327
    {
328 6
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name);
329
330 6
        $this->authorize('hasAccess', 'Edit Tech Tip');
331 4
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->with('TechTipTypes')->first();
332
333 4
        if (!$tipData) {
334 2
            return view('tips.tipNotFound');
335
        }
336
337 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
338 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
339 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
340
341 2
        return view('tips.editTip', [
342 2
            'tipTypes' => $typesArr,
343 2
            'sysTypes' => $systemsArr,
344 2
            'details' => $tipData,
345 2
            'files'   => $files,
346
        ]);
347
    }
348
349
    //  Store the edited Tech Tip
350 16
    public function update(Request $request, $id)
351
    {
352 16
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
353
354 16
        $this->authorize('hasAccess', 'Edit Tech Tip');
355
356 14
        $request->validate([
357 14
            'subject'   => 'required',
358
            'equipment' => 'required',
359
            'tipType'   => 'required',
360
            'tip'       => 'required',
361
        ]);
362
363 6
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
364
365
        //  Verify if there is a file to be processed or not
366 6
        if ($receiver->isUploaded() === false || $request->_completed) {
367 6
            $this->storeUpdatedTip($request, $id);
368 6
            Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
369 6
            return response()->json(['tip_id' => $id]);
370
        }
371
372
        //  Recieve and process the file
373 2
        $save = $receiver->receive();
374
375
        //  See if the uploade has finished
376 2
        if ($save->isFinished()) {
377 2
            $this->saveFile($save->getFile(), $id);
378
379 2
            return 'uploaded successfully';
380
        }
381
382
        //  Get the current progress
383
        $handler = $save->handler();
384
385
        Log::debug('File being uploaded.  Percentage done - ' . $handler->getPercentageDone());
386
        return response()->json([
387
            'done'   => $handler->getPercentageDone(),
388
            'status' => true
389
        ]);
390
    }
391
392
    //  Store the updated tip
393 6
    public function storeUpdatedTip($tipData, $id)
394
    {
395 6
        $this->authorize('hasAccess', 'Edit Tech Tip');
396
397
        //  Remove any forward slash (/) from the Subject Field
398 6
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
399
400
        //  Enter the tip details and return the tip ID
401 6
        TechTips::find($id)->update([
402 6
            'tip_type_id' => $tipData->tipType,
403 6
            'subject'     => $tipData->subject,
404 6
            'description' => $tipData->tip,
405
            // 'user_id'     => Auth::user()->user_id TODO - updated user who modified tip
406
        ]);
407
408
        //  Add any additional equipment types to the tip
409 6
        $tipEquip = TechTipSystems::where('tip_id', $id)->get();
410 6
        foreach($tipData->equipment as $equip)
411
        {
412 6
            $found = false;
413 6
            foreach($tipEquip as $key => $value)
414
            {
415 6
                if($equip['sys_id'] == $value->sys_id)
416
                {
417
                    $tipEquip->forget($key);
418
                    $found = true;
419
                    break;
420
                }
421
            }
422 6
            if(!$found)
423
            {
424 6
                TechTipSystems::create([
425 6
                    'tip_id' => $id,
426 6
                    'sys_id' => $equip['sys_id'],
427
                ]);
428
            }
429
        }
430
431
        //  Remove the remainaing equipment types that have been removed
432 6
        foreach($tipEquip as $remaining)
433
        {
434 6
            TechTipSystems::find($remaining->tip_tag_id)->delete();
435
        }
436
437
        //  Remove any files that no longer apply
438 6
        foreach($tipData->deletedFileList as $file)
439
        {
440 2
            $file = TechTipFiles::find($file);
441 2
            $fileID = $file->file_id;
442 2
            $file->delete();
443
            //  Try to delete the file itself
444 2
            Files::deleteFile($fileID);
445
        }
446
447 6
        return true;
448
    }
449
450
    //  Soft delet the Tech Tip
451 4
    public function destroy($id)
452
    {
453 4
        Log::debug('Route ' . Route::currentRouteName() . ' visited by ' . Auth::user()->full_name);
454
455 4
        $this->authorize('hasAccess', 'Delete Tech Tip');
456
457
        //  Remove the Tip from any users favorites
458 2
        TechTipFavs::where('tip_id', $id)->delete();
459
460
        //  Disable the tip
461 2
        TechTips::find($id)->delete();
462 2
        Log::warning('User - '.Auth::user()->user_id.' deleted Tech Tip ID - '.$id);
463 2
        return response()->json(['success' => true]);
464
    }
465
}
466