Passed
Push — dev5 ( 3685b3...3ab1f5 )
by Ron
07:25
created

TechTipsController::store()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 40
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4.2916

Importance

Changes 0
Metric Value
cc 4
eloc 22
c 0
b 0
f 0
nc 3
nop 1
dl 0
loc 40
ccs 14
cts 19
cp 0.7368
crap 4.2916
rs 9.568
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\SystemTypes;
9
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...
10
use App\TechTipFiles;
11
use App\TechTipSystems;
12
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...
13
use App\SystemCategories;
14
use Illuminate\Http\Request;
15
use Illuminate\Http\UploadedFile;
16
use Illuminate\Support\Facades\Log;
17
use App\Http\Controllers\Controller;
18
use Illuminate\Support\Facades\Auth;
19
use Illuminate\Support\Facades\Route;
20
use Pion\Laravel\ChunkUpload\Receiver\FileReceiver;
21
use Pion\Laravel\ChunkUpload\Handler\HandlerFactory;
22
use Pion\Laravel\ChunkUpload\Handler\AbstractHandler;
23
use Pion\Laravel\ChunkUpload\Exceptions\UploadMissingFileException;
24
use Illuminate\Http\File;
25
26
// use App\Http\Resources\TechTipTypes;
27
use App\Http\Resources\TechTipTypesCollection;
28
use App\TechTipTypes;
29
use Illuminate\Support\Facades\Notification;
30
use App\Notifications\NewTechTip;
31
32
use App\Http\Resources\SystemCategoriesCollection as CategoriesCollection;
33
use App\Http\Resources\SystemCategoriesCollection;
34
use App\Http\Resources\SystemTypesCollection;
35
// use App\SystemCategories;
36
// use App\SystemTypes;
37
38
use App\Http\Resources\TechTipsCollection;
39
use Illuminate\Support\Facades\Storage;
40
41
class TechTipsController extends Controller
42
{
43 44
    public function __construct()
44
    {
45 44
        $this->middleware('auth');
46 44
    }
47
48
    //  Tech Tips landing page
49 2
    public function index()
50
    {
51 2
        $tipTypes = new TechTipTypesCollection(TechTipTypes::all());
52 2
        $sysList  = new CategoriesCollection(SystemCategories::with('SystemTypes')->with('SystemTypes.SystemDataFields.SystemDataFieldTypes')->get());
53 2
        return view('tips.index', [
54 2
            'tipTypes' => $tipTypes,
55 2
            'sysTypes' => $sysList,
56 2
            'canCreate' => $this->authorize('hasAccess', 'create_tech_tip') ? true : false
57
        ]);
58
    }
59
60
    //  Search for an existing tip - If no paramaters, return all tips
61 8
    public function search(Request $request)
62
    {
63 8
        Log::debug('request Data -> ', $request->toArray());
64
65
        //  See if there are any search paramaters entered
66 8
        if (!$request->search['searchText'] && !isset($request->search['articleType']) && !isset($request->search['systemType'])) {
67
            //  No search paramaters, send all tech tips
68 2
            $tips = new TechTipsCollection(
69 2
                TechTips::orderBy('created_at', 'DESC')
70 2
                    ->with('SystemTypes')
71 2
                    ->paginate($request->pagination['perPage'])
72
            );
73
        } else {
74 6
            $article = isset($request->search['articleType']) ? true : false;
75 6
            $system  = isset($request->search['systemType'])  ? true : false;
76
            //  Search paramaters, filter results
77 6
            $tips = new TechTipsCollection(
78 6
                TechTips::orderBy('created_at', 'DESC')
79
                    //  Search by id or a phrase in the title or description
80
                    ->where(function ($query) use ($request) {
81 6
                        $query->where('subject', 'like', '%' . $request->search['searchText'] . '%')
82 6
                            ->orWhere('tip_id', 'like', '%' . $request->search['searchText'] . '%')
83 6
                            ->orWhere('description', 'like', '%' . $request->search['searchText'] . '%');
84 6
                    })
85
                    ->when($article, function ($query) use ($request) {
86 2
                        $query->whereIn('tip_type_id', $request->search['articleType']);
87 6
                    })
88
                    ->when($system, function ($query) use ($request) {
89
                        $query->whereHas('SystemTypes', function ($query) use ($request) {
90 2
                            $query->whereIn('system_types.sys_id', $request->search['systemType']);
91 2
                        });
92 6
                    })
93 6
                    ->with('SystemTypes')
94 6
                    ->paginate($request->pagination['perPage'])
95
            );
96
        }
97
98 8
        return $tips;
99
    }
100
101
    //  Process an image that is attached to a tech tip
102 6
    public function processImage(Request $request)
103
    {
104 6
        $this->authorize('hasAccess', 'create_tech_tip');
105
106 4
        $request->validate([
107 4
            'file' => 'mimes:jpeg,bmp,png,jpg,gif'
108
        ]);
109
110
        //  Generate a unique hash as the file name and store it in a publicly accessable folder
111 2
        $path = 'img/tip_img';
112 2
        $location = Storage::disk('public')->putFile($path, new File($request->file));
113
114
        //  Return the full url path to the image
115 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
116 2
        return response()->json(['location' => Storage::url($location)]);
117
    }
118
119
    //  Create a new Tech Tip form
120 4
    public function create()
121
    {
122 4
        $this->authorize('hasAccess', 'create_tech_tip');
123
124 2
        $typesArr   = new TechTipTypesCollection(TechTipTypes::all());
125 2
        $systemsArr = new SystemCategoriesCollection(SystemCategories::with('SystemTypes')->get());
126
127 2
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
128 2
        return view('tips.create', [
129 2
            'tipTypes' => $typesArr,
130 2
            'sysTypes' => $systemsArr,
131
        ]);
132
    }
133
134
    //  Submit the form to create a new tech tip
135 14
    public function store(Request $request)
136
    {
137 14
        $this->authorize('hasAccess', 'create_tech_tip');
138
139 12
        $request->validate([
140 12
            'subject'   => 'required',
141
            'equipment' => 'required',
142
            'tipType'   => 'required',
143
            'tip'       => 'required',
144
        ]);
145
146 4
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
147
148
        //  Verify if there is a file to be processed or not
149 4
        if($receiver->isUploaded() === false || $request->_completed)
150
        {
151 4
            Log::debug('about to create a tip');
152 4
            $tipID = $this->createTip($request);
153 4
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
154 4
            return response()->json(['tip_id' => $tipID]);
155
        }
156
157
        //  Recieve and process the file
158 2
        $save = $receiver->receive();
159
160
        //  See if the uploade has finished
161 2
        if ($save->isFinished()) {
162 2
            $this->saveFile($save->getFile());
163
164 2
            return 'uploaded successfully';
165
        }
166
167
        //  Get the current progress
168
        $handler = $save->handler();
169
170
        Log::debug('Route ' . Route::currentRouteName() . ' visited by User ID-' . Auth::user()->user_id);
171
        Log::debug('File being uploaded.  Percentage done - ' . $handler->getPercentageDone());
172
        return response()->json([
173
            'done'   => $handler->getPercentageDone(),
174
            'status' => true
175
        ]);
176
    }
177
178
    //  Save a file attached to the link
179 2
    private function saveFile(UploadedFile $file)
180
    {
181 2
        $filePath = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.'_tmp';
182
183
        //  Clean the file and store it
184 2
        $fileName = Files::cleanFilename($filePath, $file->getClientOriginalName());
185 2
        $file->storeAs($filePath, $fileName);
186
187
        //  Place file in Files table of DB
188 2
        $newFile = Files::create([
189 2
            'file_name' => $fileName,
190 2
            'file_link' => $filePath.DIRECTORY_SEPARATOR
191
        ]);
192 2
        $fileID = $newFile->file_id;
193
194
        //  Save the file ID in the session array
195 2
        $fileArr = session('newTipFile') != null ? session('newTipFile') : [];
196 2
        $fileArr[] = $fileID;
197 2
        session(['newTipFile' => $fileArr]);
198
199
        //  Log stored file
200 2
        Log::info('File Stored', ['file_id' => $fileID, 'file_path' => $filePath . DIRECTORY_SEPARATOR . $fileName]);
201 2
        return $fileID;
202
    }
203
204
    //  Create the tech tip
205 4
    private function createTip($tipData)
206
    {
207
        //  Remove any forward slash (/) from the Subject Field
208 4
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
209
210
        //  Enter the tip details and return the tip ID
211 4
        $tip = TechTips::create([
212 4
            'tip_type_id' => $tipData->tipType,
213 4
            'subject'     => $tipData->subject,
214 4
            'description' => $tipData->tip,
215 4
            'user_id'     => Auth::user()->user_id
216
        ]);
217 4
        $tipID = $tip->tip_id;
218
219 4
        foreach($tipData->equipment as $sys)
220
        {
221 4
            TechTipSystems::create([
222 4
                'tip_id' => $tipID,
223 4
                'sys_id' => $sys['sys_id']
224
            ]);
225
        }
226
227
        //  If there were any files uploaded, move them to the proper folder
228 4
        if(session('newTipFile') != null)
229
        {
230 2
            $files = session('newTipFile');
231 2
            $path = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$tipID;
232 2
            foreach($files as $file)
233
            {
234 2
                $data = Files::find($file);
235
                //  Move the file to the proper folder
236 2
                Storage::move($data->file_link.$data->file_name, $path.DIRECTORY_SEPARATOR.$data->file_name);
237
                // Update the database
238 2
                $data->update([
239 2
                    'file_link' => $path.DIRECTORY_SEPARATOR
240
                ]);
241
242 2
                TechTipFiles::create([
243 2
                    'tip_id' => $tipID,
244 2
                    'file_id' => $data->file_id
245
                ]);
246
            }
247
        }
248
249 4
        Log::debug('data - ', $tipData->toArray());
250
251
        //  Send out the notifications
252 4
        if(!$tipData->supressEmail)
253
        {
254 4
            $details = TechTips::find($tipID);
255
            $users = User::where('active', 1)->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.  Tip Data - ', $tip->toArray());
264 4
        return $tipID;
265
    }
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
    /**
283
     * Display the specified resource.
284
     *
285
     * @param  int  $id
286
     * @return \Illuminate\Http\Response
287
     */
288
    public function show($id)
289
    {
290
        //
291
    }
292
293
294
295
    public function details($id, $subject)
296
    {
297
        if(session()->has('newTechTip'))
298
        {
299
            session()->forget('newTechTip');
300
        }
301
302
303
304
        return response('tip details');
305
    }
306
307
    /**
308
     * Show the form for editing the specified resource.
309
     *
310
     * @param  int  $id
311
     * @return \Illuminate\Http\Response
312
     */
313
    public function edit($id)
314
    {
315
        //
316
    }
317
318
    /**
319
     * Update the specified resource in storage.
320
     *
321
     * @param  \Illuminate\Http\Request  $request
322
     * @param  int  $id
323
     * @return \Illuminate\Http\Response
324
     */
325
    public function update(Request $request, $id)
326
    {
327
        //
328
    }
329
330
    /**
331
     * Remove the specified resource from storage.
332
     *
333
     * @param  int  $id
334
     * @return \Illuminate\Http\Response
335
     */
336
    public function destroy($id)
337
    {
338
        //
339
    }
340
}
341