Passed
Push — dev5 ( 6e89ff...3685b3 )
by Ron
05:58
created

TechTipsController::search()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 43
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 22
c 0
b 0
f 0
nc 5
nop 1
dl 0
loc 43
ccs 0
cts 22
cp 0
crap 42
rs 8.9457
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;
0 ignored issues
show
Bug introduced by
The type App\SystemFiles was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use App\TechTipFiles;
10
use App\TechTipSystems;
11
use App\SystemFileTypes;
0 ignored issues
show
Bug introduced by
The type App\SystemFileTypes was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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
// use App\Http\Resources\TechTipTypes;
25
use App\Http\Resources\TechTipTypesCollection;
26
use App\TechTipTypes;
27
28
use App\Http\Resources\SystemCategoriesCollection as CategoriesCollection;
29
// use App\SystemCategories;
30
// use App\SystemTypes;
31
32
use App\Http\Resources\TechTipsCollection;
33
34
class TechTipsController extends Controller
35
{
36
    public function __construct()
37
    {
38
        $this->middleware('auth');
39
    }
40
41
    //  Tech Tips landing page
42
    public function index()
43
    {
44
        $tipTypes = new TechTipTypesCollection(TechTipTypes::all());
45
        $sysList = new CategoriesCollection(SystemCategories::with('SystemTypes')->with('SystemTypes.SystemDataFields.SystemDataFieldTypes')->get());
46
        return view('tips.index', [
47
            'tipTypes' => $tipTypes,
48
            'sysTypes' => $sysList,
49
        ]);
50
    }
51
52
    //  Process an image that is attached to a tech tip
53
    public function processImage(Request $request)
54
    {
55
        $request->validate([
56
            'image' => 'mimes:jpeg,bmp,png'
57
        ]);
58
59
        $file     = $request->file;
60
        $fileName = $file->getClientOriginalName();
61
        $file->storeAs('img/tip_img', $fileName, 'public');
62
63
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
64
        return json_encode(['location' => '/storage/img/tip_img/'.$fileName]);
65
    }
66
67
    //  Create a new Tech Tip form
68
    public function create()
69
    {
70
        //  Get the types of systems that can be filtered
71
        $categories = SystemCategories::all();
72
        $systems    = SystemTypes::orderBy('cat_id', 'ASC')->orderBy('name', 'ASC')->get();
73
        $sysArr = [];
74
        $i = 0;
75
        foreach($categories as $cat)
76
        {
77
            $sysArr[$i] = [
78
                'group' => $cat->name,
79
            ];
80
            foreach($systems as $sys)
81
            {
82
                if($sys->cat_id === $cat->cat_id)
83
                {
84
                    $sysArr[$i]['data'][] = [
85
                        'name'  => $sys->name,
86
                        'value' => $sys->sys_id
87
                    ];
88
                }
89
            }
90
            $i++;
91
        }
92
93
        //  Get the types of documents that can be filtered
94
//        $fileTypes = SystemFileTypes::all();
95
        $typesArr = ['Tech Tip', 'Documentation'];
96
//        foreach($fileTypes as $type)
97
//        {
98
//            $typesArr[] = $type->description;
99
//        }
100
101
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
102
        return view('tips.create', [
103
            'sysTypes' => $sysArr,
104
            'tipTypes' => $typesArr
105
        ]);
106
    }
107
108
    //  Submit the form to create a new tech tip
109
    public function store(Request $request)
110
    {
111
        $request->validate([
112
            'subject' => 'required',
113
            'systems' => 'required',
114
            'tipType' => 'required',
115
            'tip'     => 'required',
116
        ]);
117
118
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
119
120
        //  Verify if there is a file to be processed or not (only Tech Tips can be processed without file)
121
        if($receiver->isUploaded() === false && $request->tipType === 'Tech Tip')
122
        {
123
            $tipID = $this->createTip($request);
124
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
125
            return response()->json(['url' => route('tips.details', [$tipID, urlencode($request->subject)])]);
126
        }
127
        else if($receiver->isUploaded() === false)
128
        {
129
            Log::error('Upload File Missing - '.$request->toArray());
0 ignored issues
show
Bug introduced by
Are you sure $request->toArray() of type array 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

129
            Log::error('Upload File Missing - './** @scrutinizer ignore-type */ $request->toArray());
Loading history...
130
            throw new UploadMissingFileException();
131
        }
132
133
        //  Receive and process the file
134
        $save = $receiver->receive();
135
136
        if($save->isFinished())
137
        {
138
//            if($request->tipType === 'Tech Tip')
139
//            {
140
                if(!$request->session()->has('newTechTip'))
141
                {
142
                    $tipID = $this->createTip($request);
143
                    $request->session()->put('newTechTip', $tipID);
144
                }
145
146
                $tipID = session('newTechTip');
147
148
//                Log::debug('Tip ID - '.$tipID);
149
150
                $file     = $save->getFile();
151
                $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

151
                $path     = config('filesystems.paths.tips').DIRECTORY_SEPARATOR./** @scrutinizer ignore-type */ $tipID;
Loading history...
152
                $fileName = Files::cleanFilename($path, $file->getClientOriginalName());
153
                $file->storeAs($path, $fileName);
154
155
                $newFile = Files::create([
156
                    'file_name' => $fileName,
157
                    'file_link' => $path.DIRECTORY_SEPARATOR
158
                ]);
159
160
                TechTipFiles::create([
161
                    'tip_id'  => $tipID,
162
                    'file_id' => $newFile->file_id
163
                ]);
164
165
                Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
166
                return response()->json(['url' => route('tips.details', [$tipID, urlencode($request->subject)])]);
167
//            }
168
//            else
169
//            {
170
//                $file = $save->getFile();
171
//
172
//                $sysArr = is_array($request->systems) ? $request->systems : json_decode($request->systems, true);
173
//                foreach($sysArr as $sys)
174
//                {
175
//                    $sysData = SystemTypes::where('sys_id', $sys['value'])->first();
176
//                    $catName = SystemCategories::where('cat_id', $sysData->cat_id)->first()->name;
177
//                    $path = config('filesystems.paths.systems').DIRECTORY_SEPARATOR.strtolower($catName).DIRECTORY_SEPARATOR.$sysData->folder_location;
178
//                    $fileName = Files::cleanFilename($path, $file->getClientOriginalName());
179
//
180
//                    Log::debug($fileName);
181
//                    Log::debug($path);
182
//
183
//                    $file->storeAs($path, $fileName);
184
//                    $file = Files::create([
185
//                        'file_name' => $fileName,
186
//                        'file_link' => $path.DIRECTORY_SEPARATOR
187
//                    ]);
188
//
189
//                    $fileType = SystemFileTypes::where('description', $request->tipType)->first()->type_id;
190
//
191
//                    SystemFiles::create([
192
//                        'sys_id'      => $sysData->sys_id,
193
//                        'type_id'     => $fileType,
194
//                        'file_id'     => $file->file_id,
195
//                        'name'        => $request->subject,
196
//                        'description' => $request->tip,
197
//                        'user_id'     => Auth::user()->user_id
198
//                    ]);
199
//                }
200
201
//                Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
202
//                return response()->json(['url' => route('tips.details', [urlencode($sysData->name), urlencode($request->subject)])]);
203
//            }
204
        }
205
206
        //  Get the current progress
207
        $handler = $save->handler();
208
209
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
210
        Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
211
        return response()->json([
212
            'done'   => $handler->getPercentageDone(),
213
            'status' => true
214
        ]);
215
    }
216
217
    //  Create the tech tip
218
    private function createTip($tipData)
219
    {
220
        //  Remove any forward slash (/) from the Subject Field
221
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
222
223
        //  Enter the tip details and return the tip ID
224
        $tip = TechTips::create([
225
            'documentation' => $tipData->tipType === 'documentation' ? true : false,
226
            'subject'       => $tipData->subject,
227
            'description'   => $tipData->tip,
228
            'user_id'       => Auth::user()->user_id
229
        ]);
230
        $tipID = $tip->tip_id;
231
232
        $sysArr = is_array($tipData->systems) ? $tipData->systems : json_decode($tipData->systems, true);
233
234
        foreach($sysArr as $sys)
235
        {
236
            TechTipSystems::create([
237
                'tip_id' => $tipID,
238
                'sys_id' => $sys['value']
239
            ]);
240
        }
241
242
        Log::info('New Tech Tip created.  Tip Data - ', $tip->toArray());
243
        return $tipID;
244
    }
245
246
    /**
247
     * Display the specified resource.
248
     *
249
     * @param  int  $id
250
     * @return \Illuminate\Http\Response
251
     */
252
    public function show($id)
253
    {
254
        //
255
    }
256
257
    public function search(Request $request)
258
    {
259
        Log::debug('request Data -> ', $request->toArray());
260
261
        //  See if there are any search paramaters entered
262
        if(!$request->search['searchText'] && !isset($request->search['articleType']) && !isset($request->search['systemType']))
263
        {
264
            //  No search paramaters, send all tech tips
265
            $tips = new TechTipsCollection(TechTips::orderBy('created_at', 'DESC')
266
                            ->with('SystemTypes')
267
                            ->paginate($request->pagination['perPage'])
268
                        );
269
        }
270
        else
271
        {
272
            $article = isset($request->search['articleType']) ? true : false;
273
            $system  = isset($request->search['systemType'])  ? true : false;
274
            //  Search paramaters, filter results
275
            $tips = new TechTipsCollection(
276
                TechTips::orderBy('created_at', 'DESC')
277
                    //  Search by id or a phrase in the title or description
278
                    ->where(function($query) use ($request)
279
                    {
280
                        $query->where('subject', 'like', '%'.$request->search['searchText'].'%')
281
                            ->orWhere('tip_id', 'like', '%' . $request->search['searchText'].'%')
282
                            ->orWhere('description', 'like', '%' . $request->search['searchText'].'%');
283
                    })
284
                    ->when($article, function($query) use ($request)
285
                    {
286
                        $query->whereIn('tip_type_id', $request->search['articleType']);
287
                    })
288
                    ->when($system, function ($query) use ($request) {
289
                        $query->whereHas('SystemTypes', function($query) use ($request)
290
                        {
291
                            $query->whereIn('system_types.sys_id', $request->search['systemType']);
292
                        });
293
                    })
294
                    ->with('SystemTypes')
295
                    ->paginate($request->pagination['perPage'])
296
            );
297
        }
298
299
        return $tips;
300
    }
301
302
    public function details($id, $subject)
303
    {
304
        if(session()->has('newTechTip'))
305
        {
306
            session()->forget('newTechTip');
307
        }
308
309
310
311
        return response('tip details');
312
    }
313
314
    /**
315
     * Show the form for editing the specified resource.
316
     *
317
     * @param  int  $id
318
     * @return \Illuminate\Http\Response
319
     */
320
    public function edit($id)
321
    {
322
        //
323
    }
324
325
    /**
326
     * Update the specified resource in storage.
327
     *
328
     * @param  \Illuminate\Http\Request  $request
329
     * @param  int  $id
330
     * @return \Illuminate\Http\Response
331
     */
332
    public function update(Request $request, $id)
333
    {
334
        //
335
    }
336
337
    /**
338
     * Remove the specified resource from storage.
339
     *
340
     * @param  int  $id
341
     * @return \Illuminate\Http\Response
342
     */
343
    public function destroy($id)
344
    {
345
        //
346
    }
347
}
348