Passed
Push — dev5 ( da16e0...6692a0 )
by Ron
08:20
created

TechTipsController::createTip()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 57
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 30
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 30
c 0
b 0
f 0
nc 8
nop 1
dl 0
loc 57
ccs 30
cts 30
cp 1
crap 5
rs 9.1288

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 4
                $query->where('em_tech_tip', 1);
257 4
            })->get();
258
259 4
            Notification::send($users, new NewTechTip($details));
260
        }
261
262 4
        Log::info('New Tech Tip created by '.Auth::user()->full_name.'.  Tip Data - ', $tip->toArray());
263 4
        return $tipID;
264
    }
265
266
    //  Details controller - will move to the show controller with just the tech tip id
267 2
    public function details($id, $subject)
268
    {
269 2
        if(session()->has('newTipFile')) {
270
            session()->forget('newTipFile');
271
        }
272
273 2
        return $this->show($id);
274
    }
275
276
    //  Show the details about the tech tip
277 2
    public function show($id)
278
    {
279 2
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
280
281 2
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->first();
282
283 2
        if(!$tipData)
284
        {
285
            return view('tips.tipNotFound');
286
        }
287
288 2
        $isFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
289 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
290
291 2
        return view('tips.details', [
292 2
            'details' => $tipData,
293 2
            'isFav'   => empty($isFav) ? 'false' : 'true',
294 2
            'files'   => $files,
295
        ]);
296
    }
297
298
    //  Add or remove this tip as a favorite of the user
299
    public function toggleFav($action, $id)
300
    {
301
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
302
303
        switch($action) {
304
            case 'add':
305
                TechTipFavs::create([
306
                    'user_id' => Auth::user()->user_id,
307
                    'tip_id' => $id
308
                ]);
309
                break;
310
            case 'remove':
311
                $tipFav = TechTipFavs::where('user_id', Auth::user()->user_id)->where('tip_id', $id)->first();
312
                $tipFav->delete();
313
                break;
314
        }
315
316
        Log::debug('Tech Tip Bookmark Updated.', [
317
            'user_id' => Auth::user()->user_id,
318
            'tip_id' => $id,
319
            'action'  => $action
320
        ]);
321
        return response()->json(['success' => true]);
322
    }
323
324
    //  Edit an existing tech tip
325 6
    public function edit($id)
326
    {
327 6
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
328
329 6
        $this->authorize('hasAccess', 'Edit Tech Tip');
330 4
        $tipData = TechTips::where('tip_id', $id)->with('User')->with('SystemTypes')->with('TechTipTypes')->first();
331
332 4
        if(!$tipData) {
333 2
            return view('tips.tipNotFound');
334
        }
335
336 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
337 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
338 2
        $files = TechTipFiles::where('tip_id', $id)->with('Files')->get();
339
340 2
        return view('tips.editTip', [
341 2
            'tipTypes' => $typesArr,
342 2
            'sysTypes' => $systemsArr,
343 2
            'details' => $tipData,
344 2
            'files'   => $files,
345
        ]);
346
    }
347
348
    //  Store the edited Tech Tip
349 16
    public function update(Request $request, $id)
350
    {
351 16
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name.'. Submitted Data - ', $request->toArray());
352
353 16
        $this->authorize('hasAccess', 'Edit Tech Tip');
354
355 14
        $request->validate([
356 14
            'subject'   => 'required',
357
            'equipment' => 'required',
358
            'tipType'   => 'required',
359
            'tip'       => 'required',
360
        ]);
361
362 6
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
363
364
        //  Verify if there is a file to be processed or not
365 6
        if($receiver->isUploaded() === false || $request->_completed) {
366 6
            $this->storeUpdatedTip($request, $id);
367 6
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
368 6
            return response()->json(['tip_id' => $id]);
369
        }
370
371
        //  Recieve and process the file
372 2
        $save = $receiver->receive();
373
374
        //  See if the uploade has finished
375 2
        if($save->isFinished()) {
376 2
            $this->saveFile($save->getFile(), $id);
377
378 2
            return 'uploaded successfully';
379
        }
380
381
        //  Get the current progress
382
        $handler = $save->handler();
383
384
        Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
385
        return response()->json([
386
            'done'   => $handler->getPercentageDone(),
387
            'status' => true
388
        ]);
389
    }
390
391
    //  Store the updated tip
392 6
    public function storeUpdatedTip($tipData, $id)
393
    {
394 6
        $this->authorize('hasAccess', 'Edit Tech Tip');
395
396
        //  Remove any forward slash (/) from the Subject Field
397 6
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
398
399
        //  Enter the tip details and return the tip ID
400 6
        TechTips::find($id)->update([
401 6
            'tip_type_id' => $tipData->tipType,
402 6
            'subject'     => $tipData->subject,
403 6
            'description' => $tipData->tip,
404
            // 'user_id'     => Auth::user()->user_id TODO - updated user who modified tip
405
        ]);
406
407
        //  Add any additional equipment types to the tip
408 6
        $tipEquip = TechTipSystems::where('tip_id', $id)->get();
409 6
        foreach($tipData->equipment as $equip)
410
        {
411 6
            $found = false;
412 6
            foreach($tipEquip as $key => $value)
413
            {
414 6
                if($equip['sys_id'] == $value->sys_id)
415
                {
416
                    $tipEquip->forget($key);
417
                    $found = true;
418
                    break;
419
                }
420
            }
421 6
            if(!$found)
422
            {
423 6
                TechTipSystems::create([
424 6
                    'tip_id' => $id,
425 6
                    'sys_id' => $equip['sys_id'],
426
                ]);
427
            }
428
        }
429
430
        //  Remove the remainaing equipment types that have been removed
431 6
        foreach($tipEquip as $remaining)
432
        {
433 6
            TechTipSystems::find($remaining->tip_tag_id)->delete();
434
        }
435
436
        //  Remove any files that no longer apply
437 6
        foreach($tipData->deletedFileList as $file)
438
        {
439 2
            $file = TechTipFiles::find($file);
440 2
            $fileID = $file->file_id;
441 2
            $file->delete();
442
            //  Try to delete the file itself
443 2
            Files::deleteFile($fileID);
444
        }
445
446 6
        return true;
447
    }
448
449
    //  Soft delet the Tech Tip
450 4
    public function destroy($id)
451
    {
452 4
        Log::debug('Route '.Route::currentRouteName().' visited by '.Auth::user()->full_name);
453
454 4
        $this->authorize('hasAccess', 'Delete Tech Tip');
455
456
        //  Remove the Tip from any users favorites
457 2
        TechTipFavs::where('tip_id', $id)->delete();
458
459
        //  Disable the tip
460 2
        TechTips::find($id)->delete();
461 2
        Log::warning('User - '.Auth::user()->user_id.' deleted Tech Tip ID - '.$id);
462 2
        return response()->json(['success' => true]);
463
    }
464
}
465