Completed
Push — dev5 ( e18bfd...f3ddc1 )
by Ron
25:27
created

TechTipsController::createTip()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 13
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 25
rs 9.8333
1
<?php
2
3
namespace App\Http\Controllers\TechTips;
4
5
use App\Files;
6
use App\TechTips;
7
use App\SystemTypes;
8
use App\SystemFiles;
9
use App\TechTipFiles;
10
use App\TechTipSystems;
11
use App\SystemFileTypes;
12
use App\SystemCategories;
13
use Illuminate\Http\Request;
14
use Illuminate\Http\UploadedFile;
15
use Illuminate\Support\Facades\Log;
16
use App\Http\Controllers\Controller;
17
use Illuminate\Support\Facades\Auth;
18
use Illuminate\Support\Facades\Route;
19
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
20
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
21
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
22
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
23
24
class TechTipsController extends Controller
25
{
26
    public function __construct()
27
    {
28
        $this->middleware('auth');
29
    }
30
    
31
    //  Tech Tips landing page
32
    public function index()
33
    {
34
        //  Get the types of documents that can be filtered
35
        $filterTypes = SystemFileTypes::all();
36
        $typeArr[] = [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$typeArr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $typeArr = array(); before regardless.
Loading history...
37
            'text' => 'Tech Tip',
38
            'value' => 'tech-tip'
39
        ];
40
        foreach($filterTypes as $type)
41
        {
42
            $typeArr[] = [
43
                'text' => $type->description,
44
                'value' => str_replace(' ', '-', $type->description)
45
            ];
46
        }
47
        
48
        //  Get the types of systems that can be filtered
49
        $sysTypes = SystemTypes::orderBy('cat_id', 'ASC')->orderBy('name', 'ASC')->get();
50
        $sysArr = [];
51
        foreach($sysTypes as $type)
52
        {
53
            $sysArr[] = [
54
                'text' => $type->name,
55
                'value' => $type->sys_id
56
            ];
57
        }
58
        
59
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
60
        return view('tips.index', [
61
            'filterTypes' => $typeArr,
62
            'systemTypes' => $sysArr
63
        ]);
64
    }
65
    
66
    //  Process an image that is attached to a tech tip
67
    public function processImage(Request $request)
68
    {
69
        $request->validate([
70
            'image' => 'mimes:jpeg,bmp,png'
71
        ]);
72
73
        $file     = $request->file;
74
        $fileName = $file->getClientOriginalName();
75
        $file->storeAs('img/tip_img', $fileName, 'public');
76
77
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
78
        return json_encode(['location' => '/storage/img/tip_img/'.$fileName]);
79
    }
80
81
    //  Create a new Tech Tip form
82
    public function create()
83
    {
84
        //  Get the types of systems that can be filtered
85
        $categories = SystemCategories::all();
86
        $systems    = SystemTypes::orderBy('cat_id', 'ASC')->orderBy('name', 'ASC')->get();
87
        $sysArr = [];
88
        $i = 0;
89
        foreach($categories as $cat)
90
        {
91
            $sysArr[$i] = [
92
                'group' => $cat->name,
93
            ];
94
            foreach($systems as $sys)
95
            {
96
                if($sys->cat_id === $cat->cat_id)
97
                {
98
                    $sysArr[$i]['data'][] = [
99
                        'name'  => $sys->name,
100
                        'value' => $sys->sys_id
101
                    ];
102
                }
103
            }
104
            $i++;
105
        }
106
        
107
        //  Get the types of documents that can be filtered
108
        $fileTypes = SystemFileTypes::all();
109
        $typesArr  = ['Tech Tip'];
110
        foreach($fileTypes as $type)
111
        {
112
            $typesArr[] = $type->description;
113
        }
114
        
115
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
116
        return view('tips.create', [
117
            'sysTypes' => $sysArr,
118
            'tipTypes' => $typesArr
119
        ]);
120
    }
121
122
    //  Submit the form to create a new tech tip
123
    public function store(Request $request)
124
    {
125
        $request->validate([
126
            'subject' => 'required',
127
            'systems' => 'required',
128
            'tipType' => 'required',
129
            'tip'     => 'required',
130
        ]);
131
                
132
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
133
        
134
        //  Verify if there is a file to be processed or not (only Tech Tips can be processed without file)
135
        if($receiver->isUploaded() === false && $request->tipType === 'Tech Tip')
136
        {
137
            $tipID = $this->createTip($request);
138
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
139
            return response()->json(['url' => route('tips.details', [$tipID, urlencode($request->subject)])]);
140
        }
141
        else if($receiver->isUploaded() === false)
142
        {
143
            Log::error('Upload File Missing - '.$request->toArray());
144
            throw new UploadMissingFileException();
145
        }
146
        
147
        //  Receive and process the file
148
        $save = $receiver->receive();
149
        
150
        if($save->isFinished())
151
        {
152
            if($request->tipType === 'Tech Tip')
153
            {
154
                if(!$request->session()->has('newTechTip'))
155
                {
156
                    $tipID = $this->createTip($request);
157
                    $request->session()->put('newTechTip', $tipID);
158
                }
159
                
160
                $tipID = session('newTechTip');
161
162
                $file     = $save->getFile();
163
                $path     = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$tipID;
0 ignored issues
show
Bug introduced by
Are you sure $tipID of type Illuminate\Session\Sessi...ate\Session\Store|mixed can be used in concatenation? ( Ignorable by Annotation )

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

163
                $path     = config('filesystems.paths.tips').DIRECTORY_SEPARATOR./** @scrutinizer ignore-type */ $tipID;
Loading history...
164
                $fileName = Files::cleanFilename($path, $file->getClientOriginalName());
165
                $file->storeAs($path, $fileName);
166
                
167
                $newFile = Files::create([
168
                    'file_name' => $fileName,
169
                    'file_link' => $path.DIRECTORY_SEPARATOR
170
                ]);
171
                
172
                TechTipFiles::create([
173
                    'tip_id'  => $tipID,
174
                    'file_id' => $newFile->file_id
175
                ]);
176
                
177
                Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
178
                return response()->json(['url' => route('tips.details', [$tipID, urlencode($request->subject)])]);
179
            } 
180
            else
181
            {
182
                $file = $save->getFile();
183
                
184
                $sysArr = is_array($request->systems) ? $request->systems : json_decode($request->systems, true);
185
                foreach($sysArr as $sys)
186
                {
187
                    $sysData = SystemTypes::where('sys_id', $sys['value'])->first();
188
                    $catName = SystemCategories::where('cat_id', $sysData->cat_id)->first()->name;
189
                    $path = config('filesystems.paths.systems').DIRECTORY_SEPARATOR.strtolower($catName).DIRECTORY_SEPARATOR.$sysData->folder_location;
190
                    $fileName = Files::cleanFilename($path, $file->getClientOriginalName());
191
                    
192
                    Log::debug($fileName);
193
                    Log::debug($path);
194
                    
195
                    $file->storeAs($path, $fileName);
196
                    $file = Files::create([
197
                        'file_name' => $fileName,
198
                        'file_link' => $path.DIRECTORY_SEPARATOR
199
                    ]);
200
                    
201
                    $fileType = SystemFileTypes::where('description', $request->tipType)->first()->type_id;
202
                    
203
                    SystemFiles::create([
204
                        'sys_id'      => $sysData->sys_id,
205
                        'type_id'     => $fileType,
206
                        'file_id'     => $file->file_id,
207
                        'name'        => $request->subject,
208
                        'description' => $request->tip,
209
                        'user_id'     => Auth::user()->user_id
210
                    ]);
211
                }
212
                
213
                Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
214
                return response()->json(['url' => route('tips.details', [urlencode($sysData->name), urlencode($request->subject)])]);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $sysData seems to be defined by a foreach iteration on line 185. Are you sure the iterator is never empty, otherwise this variable is not defined?
Loading history...
215
            }
216
        }
217
        
218
        //  Get the current progress
219
        $handler = $save->handler();
220
221
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
222
        Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
223
        return response()->json([
224
            'done'   => $handler->getPercentageDone(),
225
            'status' => true
226
        ]);
227
    }
228
        
229
    //  Create the tech tip
230
    private function createTip($tipData)
231
    {
232
        //  Remove any forward slash (/) from the Subject Field
233
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
234
        
235
        //  Enter the tip details and return the tip ID
236
        $tip = TechTips::create([
237
            'subject' => $tipData->subject,
238
            'description' => $tipData->tip,
239
            'user_id' => Auth::user()->user_id
240
        ]);
241
        $tipID = $tip->tip_id;
242
        
243
        $sysArr = is_array($tipData->systems) ? $tipData->systems : json_decode($tipData->systems, true);
244
        
245
        foreach($sysArr as $sys)
246
        {
247
            TechTipSystems::create([
248
                'tip_id' => $tipID,
249
                'sys_id' => $sys['value']
250
            ]);
251
        }
252
        
253
        Log::info('New Tech Tip created.  Tip Data - ', $tip->toArray());
254
        return $tipID;
255
    }
256
257
    /**
258
     * Display the specified resource.
259
     *
260
     * @param  int  $id
261
     * @return \Illuminate\Http\Response
262
     */
263
    public function show($id)
264
    {
265
        //
266
    }
267
    
268
    public function search(Request $request)
269
    {
270
        Log::debug('request Data -> '. $request->getContent());
271
        
272
273
        $tips = [];
274
        $docs = [];
275
            
276
        //  Determine if the search form is empty or has data in it
277
        if($request->searchText === null && empty($request->articleType) && empty($request->sysstemType))
278
        {
279
            $tips = TechTips::all();
280
            $docs = SystemFiles::all();
281
        }
282
        else
283
        {
284
//            if(in_array('tech-tip', $request->articleType))
285
            if(false !== $key = array_search('tech-tip', $request->articleType))
286
            {
287
                Log::debug('has tech tip');
288
                
289
                
290
                
291
                
292
                Log::debug($key);
293
//                unset($request->articleType[$key]);
294
            }
295
            
296
            
297
            
298
            
299
            
300
            Log::debug('request Data -> '. $request->getContent());
0 ignored issues
show
Bug introduced by
Are you sure $request->getContent() of type resource|string can be used in concatenation? ( Ignorable by Annotation )

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

300
            Log::debug('request Data -> '. /** @scrutinizer ignore-type */ $request->getContent());
Loading history...
301
            
302
            
303
        }
304
        
305
            
306
        
307
        
308
        
309
        
310
        //  Sort the results for the proper output
311
        $kbArray = [];
312
        foreach($tips as $tip)
313
        {
314
            $kbArray[] = [
315
                'url'         => route('tips.details', [urlencode($tip->tip_id), urlencode($tip->subject)]),
316
                'title'       => $tip->subject,
317
                'description' => $tip->description,
318
                'created'     => $tip->created_at,
319
                'updated'     => date('M d, Y', strtotime($tip->updated_at))
320
            ];
321
        }
322
        foreach($docs as $doc)
323
        {
324
            $kbArray[] = [
325
                'url'         => route('tips.details', [urlencode($doc->type_id), urlencode($doc->name)]),
326
                'title'       => $doc->name,
327
                'description' => !$doc->description ? 'No Description Given' : $doc->description,
328
                'created'     => $doc->created_at,
329
                'updated'     => date('M d, Y', strtotime($doc->updated_at))
330
            ];
331
        }
332
        
333
        usort($kbArray, function($a, $b)
334
        {
335
          return $b['created'] <=> $a['created'];
336
        });
337
        
338
        return response()->json($kbArray);
339
    }
340
    
341
    public function details($id, $subject)
342
    {
343
        if(session()->has('newTechTip'))
344
        {
345
            session()->forget('newTechTip');
346
        }
347
        
348
        
349
        
350
        return response('new tech tip');
351
    }
352
353
    /**
354
     * Show the form for editing the specified resource.
355
     *
356
     * @param  int  $id
357
     * @return \Illuminate\Http\Response
358
     */
359
    public function edit($id)
360
    {
361
        //
362
    }
363
364
    /**
365
     * Update the specified resource in storage.
366
     *
367
     * @param  \Illuminate\Http\Request  $request
368
     * @param  int  $id
369
     * @return \Illuminate\Http\Response
370
     */
371
    public function update(Request $request, $id)
372
    {
373
        //
374
    }
375
376
    /**
377
     * Remove the specified resource from storage.
378
     *
379
     * @param  int  $id
380
     * @return \Illuminate\Http\Response
381
     */
382
    public function destroy($id)
383
    {
384
        //
385
    }
386
}
387