Passed
Push — dev5 ( b08d9a...c43caf )
by Ron
04:08
created

TechTipsController::search()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 57

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 57
ccs 0
cts 14
cp 0
rs 8.627
c 0
b 0
f 0
cc 5
nc 4
nop 1
crap 30

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\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
Coding Style Comprehensibility introduced by
$typeArr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $typeArr = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
37
            'text'  => 'Tech Tip',
38
            'value' => 'tech-tip'
39
        ];
40
        $typeArr[] = [
41
            'text'  => 'Documentation',
42
            'value' => 'documentation'
43
        ];
44
//        foreach($filterTypes as $type)
45
//        {
46
//            $typeArr[] = [
47
//                'text' => $type->description,
48
//                'value' => str_replace(' ', '-', $type->description)
49
//            ];
50
//        }
51
        
52
        //  Get the types of systems that can be filtered
53
        $sysTypes = SystemTypes::orderBy('cat_id', 'ASC')->orderBy('name', 'ASC')->get();
54
        $sysArr = [];
55
        foreach($sysTypes as $type)
56
        {
57
            $sysArr[] = [
58
                'text' => $type->name,
59
                'value' => $type->sys_id
60
            ];
61
        }
62
        
63
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
0 ignored issues
show
Bug introduced by
Accessing user_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
64
        return view('tips.index', [
65
            'filterTypes' => $typeArr,
66
            'systemTypes' => $sysArr
67
        ]);
68
    }
69
    
70
    //  Process an image that is attached to a tech tip
71
    public function processImage(Request $request)
72
    {
73
        $request->validate([
74
            'image' => 'mimes:jpeg,bmp,png'
75
        ]);
76
77
        $file     = $request->file;
78
        $fileName = $file->getClientOriginalName();
79
        $file->storeAs('img/tip_img', $fileName, 'public');
80
81
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
0 ignored issues
show
Bug introduced by
Accessing user_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
82
        return json_encode(['location' => '/storage/img/tip_img/'.$fileName]);
83
    }
84
85
    //  Create a new Tech Tip form
86
    public function create()
87
    {
88
        //  Get the types of systems that can be filtered
89
        $categories = SystemCategories::all();
90
        $systems    = SystemTypes::orderBy('cat_id', 'ASC')->orderBy('name', 'ASC')->get();
91
        $sysArr = [];
92
        $i = 0;
93
        foreach($categories as $cat)
94
        {
95
            $sysArr[$i] = [
96
                'group' => $cat->name,
97
            ];
98
            foreach($systems as $sys)
99
            {
100
                if($sys->cat_id === $cat->cat_id)
101
                {
102
                    $sysArr[$i]['data'][] = [
103
                        'name'  => $sys->name,
104
                        'value' => $sys->sys_id
105
                    ];
106
                }
107
            }
108
            $i++;
109
        }
110
        
111
        //  Get the types of documents that can be filtered
112
//        $fileTypes = SystemFileTypes::all();
113
        $typesArr = ['Tech Tip', 'Documentation'];
114
//        foreach($fileTypes as $type)
115
//        {
116
//            $typesArr[] = $type->description;
117
//        }
118
        
119
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
0 ignored issues
show
Bug introduced by
Accessing user_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
120
        return view('tips.create', [
121
            'sysTypes' => $sysArr,
122
            'tipTypes' => $typesArr
123
        ]);
124
    }
125
126
    //  Submit the form to create a new tech tip
127
    public function store(Request $request)
128
    {
129
        $request->validate([
130
            'subject' => 'required',
131
            'systems' => 'required',
132
            'tipType' => 'required',
133
            'tip'     => 'required',
134
        ]);
135
                
136
        $receiver = new FileReceiver('file', $request, HandlerFactory::classFromRequest($request));
137
        
138
        //  Verify if there is a file to be processed or not (only Tech Tips can be processed without file)
139
        if($receiver->isUploaded() === false && $request->tipType === 'Tech Tip')
140
        {
141
            $tipID = $this->createTip($request);
142
            Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
0 ignored issues
show
Bug introduced by
Accessing user_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
143
            return response()->json(['url' => route('tips.details', [$tipID, urlencode($request->subject)])]);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
144
        }
145
        else if($receiver->isUploaded() === false)
146
        {
147
            Log::error('Upload File Missing - '.$request->toArray());
148
            throw new UploadMissingFileException();
149
        }
150
        
151
        //  Receive and process the file
152
        $save = $receiver->receive();
153
        
154
        if($save->isFinished())
155
        {
156
//            if($request->tipType === 'Tech Tip')
157
//            {
158
                if(!$request->session()->has('newTechTip'))
159
                {
160
                    $tipID = $this->createTip($request);
161
                    $request->session()->put('newTechTip', $tipID);
0 ignored issues
show
Bug introduced by
The method put() does not seem to exist on object<Symfony\Component...ssion\SessionInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
162
                }
163
                
164
                $tipID = session('newTechTip');
165
            
166
//                Log::debug('Tip ID - '.$tipID);
167
168
                $file     = $save->getFile();
169
                $path     = config('filesystems.paths.tips').DIRECTORY_SEPARATOR.$tipID;
170
                $fileName = Files::cleanFilename($path, $file->getClientOriginalName());
171
                $file->storeAs($path, $fileName);
172
                
173
                $newFile = Files::create([
174
                    'file_name' => $fileName,
175
                    'file_link' => $path.DIRECTORY_SEPARATOR
176
                ]);
177
                
178
                TechTipFiles::create([
179
                    'tip_id'  => $tipID,
180
                    'file_id' => $newFile->file_id
181
                ]);
182
                
183
                Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
0 ignored issues
show
Bug introduced by
Accessing user_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
184
                return response()->json(['url' => route('tips.details', [$tipID, urlencode($request->subject)])]);
185
//            } 
186
//            else
187
//            {
188
//                $file = $save->getFile();
189
//                
190
//                $sysArr = is_array($request->systems) ? $request->systems : json_decode($request->systems, true);
191
//                foreach($sysArr as $sys)
192
//                {
193
//                    $sysData = SystemTypes::where('sys_id', $sys['value'])->first();
194
//                    $catName = SystemCategories::where('cat_id', $sysData->cat_id)->first()->name;
195
//                    $path = config('filesystems.paths.systems').DIRECTORY_SEPARATOR.strtolower($catName).DIRECTORY_SEPARATOR.$sysData->folder_location;
196
//                    $fileName = Files::cleanFilename($path, $file->getClientOriginalName());
197
//                    
198
//                    Log::debug($fileName);
199
//                    Log::debug($path);
200
//                    
201
//                    $file->storeAs($path, $fileName);
202
//                    $file = Files::create([
203
//                        'file_name' => $fileName,
204
//                        'file_link' => $path.DIRECTORY_SEPARATOR
205
//                    ]);
206
//                    
207
//                    $fileType = SystemFileTypes::where('description', $request->tipType)->first()->type_id;
208
//                    
209
//                    SystemFiles::create([
210
//                        'sys_id'      => $sysData->sys_id,
211
//                        'type_id'     => $fileType,
212
//                        'file_id'     => $file->file_id,
213
//                        'name'        => $request->subject,
214
//                        'description' => $request->tip,
215
//                        'user_id'     => Auth::user()->user_id
216
//                    ]);
217
//                }
218
                
219
//                Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
220
//                return response()->json(['url' => route('tips.details', [urlencode($sysData->name), urlencode($request->subject)])]);
221
//            }
222
        }
223
        
224
        //  Get the current progress
225
        $handler = $save->handler();
226
227
        Log::debug('Route '.Route::currentRouteName().' visited by User ID-'.Auth::user()->user_id);
0 ignored issues
show
Bug introduced by
Accessing user_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
228
        Log::debug('File being uploaded.  Percentage done - '.$handler->getPercentageDone());
229
        return response()->json([
230
            'done'   => $handler->getPercentageDone(),
231
            'status' => true
232
        ]);
233
    }
234
        
235
    //  Create the tech tip
236
    private function createTip($tipData)
237
    {
238
        //  Remove any forward slash (/) from the Subject Field
239
        $tipData->merge(['subject' => str_replace('/', '-', $tipData->subject)]);
240
        
241
        //  Enter the tip details and return the tip ID
242
        $tip = TechTips::create([
243
            'documentation' => $tipData->tipType === 'documentation' ? true : false,
244
            'subject'       => $tipData->subject,
245
            'description'   => $tipData->tip,
246
            'user_id'       => Auth::user()->user_id
0 ignored issues
show
Bug introduced by
Accessing user_id on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
247
        ]);
248
        $tipID = $tip->tip_id;
249
        
250
        $sysArr = is_array($tipData->systems) ? $tipData->systems : json_decode($tipData->systems, true);
251
        
252
        foreach($sysArr as $sys)
253
        {
254
            TechTipSystems::create([
255
                'tip_id' => $tipID,
256
                'sys_id' => $sys['value']
257
            ]);
258
        }
259
        
260
        Log::info('New Tech Tip created.  Tip Data - ', $tip->toArray());
261
        return $tipID;
262
    }
263
264
    /**
265
     * Display the specified resource.
266
     *
267
     * @param  int  $id
268
     * @return \Illuminate\Http\Response
269
     */
270
    public function show($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
271
    {
272
        //
273
    }
274
    
275
    public function search(Request $request)
276
    {
277
        Log::debug('request Data -> '.$request->getContent());
278
        $tips = [];
279
            
280
        //  Determine if the search form is empty or has data in it
281
        if($request->searchText === null && empty($request->articleType) && empty($request->sysstemType))
282
        {
283
            $tips = TechTips::orderBy('updated_at')->get();
284
        }
285
        else
286
        {
287
288
//            $tips = TechTips::
289
            
290
            
291
            
292
            
293
            
294
            
295
        }
296
        
297
            
298
        
299
        
300
        
301
        
302
        //  Sort the results for the proper output
303
        $kbArray = [];
304
        foreach($tips as $tip)
305
        {
306
            $kbArray[] = [
307
                'url'         => route('tips.details', [urlencode($tip->tip_id), urlencode($tip->subject)]),
308
                'title'       => $tip->subject,
309
                'description' => $tip->description,
310
                'created'     => $tip->created_at,
311
                'updated'     => date('M d, Y', strtotime($tip->updated_at))
312
            ];
313
        }
314
//        foreach($docs as $doc)
315
//        {
316
//            $kbArray[] = [
317
//                'url'         => route('tips.details', [urlencode($doc->type_id), urlencode($doc->name)]),
318
//                'title'       => $doc->name,
319
//                'description' => !$doc->description ? 'No Description Given' : $doc->description,
320
//                'created'     => $doc->created_at,
321
//                'updated'     => date('M d, Y', strtotime($doc->updated_at))
322
//            ];
323
//        }
324
        
325
//        usort($kbArray, function($a, $b)
326
//        {
327
//          return $b['created'] <=> $a['created'];
328
//        });
329
        
330
        return response()->json($kbArray);
0 ignored issues
show
Bug introduced by
The method json does only exist in Illuminate\Contracts\Routing\ResponseFactory, but not in Illuminate\Http\Response.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
331
    }
332
    
333
    public function details($id, $subject)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $subject is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
334
    {
335
        if(session()->has('newTechTip'))
336
        {
337
            session()->forget('newTechTip');
338
        }
339
        
340
        
341
        
342
        return response('new tech tip');
343
    }
344
345
    /**
346
     * Show the form for editing the specified resource.
347
     *
348
     * @param  int  $id
349
     * @return \Illuminate\Http\Response
350
     */
351
    public function edit($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
352
    {
353
        //
354
    }
355
356
    /**
357
     * Update the specified resource in storage.
358
     *
359
     * @param  \Illuminate\Http\Request  $request
360
     * @param  int  $id
361
     * @return \Illuminate\Http\Response
362
     */
363
    public function update(Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
364
    {
365
        //
366
    }
367
368
    /**
369
     * Remove the specified resource from storage.
370
     *
371
     * @param  int  $id
372
     * @return \Illuminate\Http\Response
373
     */
374
    public function destroy($id)
0 ignored issues
show
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
375
    {
376
        //
377
    }
378
}
379