SearchTipsController::__invoke()   B
last analyzed

Complexity

Conditions 9
Paths 32

Size

Total Lines 44
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 22
c 2
b 0
f 0
dl 0
loc 44
rs 8.0555
cc 9
nc 32
nop 1
1
<?php
2
3
namespace App\Http\Controllers\TechTips;
4
5
use App\Http\Controllers\Controller;
6
use App\Http\Requests\TechTips\SearchTipsRequest;
7
use App\Models\TechTip;
8
use Illuminate\Http\Request;
9
10
class SearchTipsController extends Controller
11
{
12
    /**
13
     * Search for a Tech Tip
14
     */
15
    public function __invoke(SearchTipsRequest $request)
16
    {
17
        $dirty       = false;
18
        $searchText  = isset($request->search_text) ? explode(' ', $request->search_text) : null;
19
        $searchEquip = isset($request->search_equip_id) ? $request->search_equip_id : null;
20
        $searchType  = isset($request->search_type) ? $request->search_type : null;
21
22
        //  Determine if any search queries have been entered
23
        if($searchText || $searchEquip || $searchType)
24
        {
25
            $dirty = true;
26
        }
27
28
        //  If no search queries, send all Tech Tips (limited by pagination)
29
        if(!$dirty)
30
        {
31
            return TechTip::with('EquipmentType')->orderBy('sticky', 'DESC')->orderBy('created_at', 'DESC')->paginate($request->pagination_perPage);
32
        }
33
34
        //  Perform the search query
35
        return TechTip::with('EquipmentType')
36
            ->orderBy('sticky', 'DESC')
37
            ->orderBy('created_at', 'DESC')
38
            //  Search text fields
39
            ->when($searchText, function($q) use($searchText)
40
                {
41
                    foreach($searchText as $text)
42
                    {
43
                        $q->orWhere('subject', 'like', '%'.$text.'%')
44
                            ->orWhere('tip_id', 'like', '%'.$text.'%')
45
                            ->orWhere('details', 'like', '%'.$text.'%');
46
                    }
47
                })
48
            //  Search Article Type field
49
            ->when($searchType, function($q) use($searchType) {
50
                    $q->whereIn('tip_type_id', $searchType);
51
                })
52
            //  Search Equipment Type field
53
            ->when($searchEquip, function($q) use($searchEquip) {
54
                    $q->whereHas('EquipmentType', function($q2) use ($searchEquip) {
55
                        $q2->whereIn('equipment_types.equip_id', $searchEquip);
56
                    });
57
                })
58
            ->paginate($request->pagination_perPage);
59
    }
60
}
61