Completed
Push — master ( 6e8adf...c24137 )
by
unknown
27s
created

DeviceController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use App\Http\Requests\EditDevice;
6
use Illuminate\Http\Request;
7
use App\DataTables\DevicesDataTable;
8
use App\Device;
9
use App\Site;
10
use App\Location;
11
use Charts;
0 ignored issues
show
Bug introduced by
The type Charts 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
13
class DeviceController extends Controller
14
{
15
    /**
16
     * Create a new controller instance.
17
     *
18
     */
19
    public function __construct()
20
    {
21
        $this->middleware('auth');
22
    }
23
24
    /**
25
     * Display index page and process dataTable ajax request.
26
     *
27
     * @param \App\DataTables\DevicesDataTable $dataTable
28
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
29
     */
30
    public function index(DevicesDataTable $dataTable)
31
    {
32
        $trashed = Device::onlyTrashed()->get();
33
        return $dataTable->render('device.index', compact('trashed'));
0 ignored issues
show
Bug Best Practice introduced by
The expression return $dataTable->rende...x', compact('trashed')) also could return the type callable which is incompatible with the documented return type Illuminate\Http\JsonResponse|Illuminate\View\View.
Loading history...
34
    }
35
36
    /**
37
     * Show create device page.
38
     *
39
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
0 ignored issues
show
Bug introduced by
The type BladeView 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...
40
     */
41
    public function create()
42
    {
43
        return view('device.index');
44
    }
45
46
    /**
47
     * Show the given device.
48
     *
49
     * @param  string  $id
50
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
51
     */
52
    public function show($id)
53
    {
54
        $device = Device::findOrFail($id);
55
        
56
        $charts = [ ];
57
        foreach ($device->sensors as $sensor) {
58
            $data = $sensor->last_month_daily_avg_data;
59
            $charts[ $sensor->id ] = Charts::create('line', 'highcharts')
60
                ->title($sensor->name)
61
                ->elementLabel($sensor->type)
62
                ->labels($data->pluck('date'))
63
                ->values($data->pluck('value'))
64
                ->responsive(true);
65
        }
66
        
67
        return view('device.show', [ 'device' => $device, 'charts' => $charts ]);
68
    }
69
70
    /**
71
     * View the edit device page
72
     *
73
     * @param  string  $id
74
     * @return \BladeView|bool|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
75
     */
76
    public function edit($id)
77
    {
78
        //Get the device with the given id
79
        $device = Device::findOrFail($id);
80
        //Get the devices location
81
        $location = $device->location()->select('id', 'name', 'site_id')->first();
82
    
83
        //Get the site id and location id if they exist and if not assign 0
84
        $site_id = $location->site_id ?? 0;
85
        $location_id = $location->id ?? 0;
86
    
87
        //Get all sites with the current site first
88
        $sites = Site::select('id', 'name')->orderByRaw("id = ? DESC", $site_id)
0 ignored issues
show
Bug introduced by
It seems like $site_id can also be of type integer; however, parameter $bindings of Illuminate\Database\Query\Builder::orderByRaw() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

88
        $sites = Site::select('id', 'name')->orderByRaw("id = ? DESC", /** @scrutinizer ignore-type */ $site_id)
Loading history...
89
            ->orderBy('name', 'ASC')->get();
90
        //Get all locations for the selected site with the selected location first
91
        $locations = Location::select('id', 'name')->where('site_id', '=', $sites[ 0 ]->id ?? 0)
92
            ->orderByRaw("id = ? DESC", $location_id)->orderBy('name', 'ASC')->get();
93
        
94
        return view('device.edit', [ 'device' => $device, 'locations' => $locations, 'sites' => $sites ]);
95
    }
96
97
    /**
98
     * Update the given device.
99
     *
100
     * @param  EditDevice  $request
101
     * @param  string  $id
102
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\JsonResponse
103
     */
104
    public function update(EditDevice $request, $id)
105
    {
106
        $device = Device::findOrFail($id);
107
        
108
        //Get the site id and location id for the device if they are not null
109
        if ($request->input('new_site_name') != null || $request->input('site_id') != null)
110
        {
111
            //Get the site id of the old or newly created site
112
            if (!empty($request->input('new_site_name')))
113
            {
114
                //Create a new site
115
                $site = Site::create([ 'name' => $request->input('new_site_name') ]);
116
                $site_id = $site->id;
117
            } else {
118
                            $site_id = $request->input('site_id');
119
            }
120
    
121
            //Get the location id of the old or newly created location
122
            if (!empty($request->input('new_location_name')))
123
            {
124
                //Create a new location
125
                $location = Location::create([ 'name' => $request->input('new_location_name'), 'site_id' => $site_id ]);
126
                $location_id = $location->id;
127
            } else
128
                $location_id = $request->input('location_id');
129
    
130
            //Update the device
131
            $device->location_id = $location_id;
132
        }
133
        
134
        //Update the device
135
        if ($request->input('name') != null)
136
            $device->name = $request->input('name');
137
        if ($request->input('open_time') != null)
138
            $device->open_time = $request->input('open_time');
139
        if ($request->input('close_time') != null)
140
            $device->close_time = $request->input('close_time');
141
        if ($request->input('update_rate') != null)
142
            $device->update_rate = $request->input('update_rate');
143
        if ($request->input('image_rate') != null)
144
            $device->image_rate = $request->input('image_rate');
145
        if ($request->input('sensor_rate') != null)
146
            $device->sensor_rate = $request->input('sensor_rate');
147
        //Check if the cover_command needs to be updated
148
        if ($request->input('command') != null)
149
        {
150
            //If device is currently opening, closing or in an error state don't update command
151
            if (!$device->isReadyForCommand())
152
                return response()->json("Device is currently in use.", 403);
153
    
154
            $command = $request->input('command');
155
            
156
            //If command is to unlock the device then check if the device should be open or closed based on the schedule
157
            if ($request->command === 'unlock')
158
            {
159
                if ($device->isDuringScheduleOpen())
160
                    $command = 'open';
161
                else
162
                    $command = 'close';
163
            }
164
            $device->cover_command = $command;
165
        }
166
        
167
        $device->save();
168
    
169 View Code Duplication
        if (\Request::ajax())
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
170
            return response()->json([ 'success' => 'Device updated successfully' ]);
171
        else
172
            return redirect()->route('device.show', $id)
0 ignored issues
show
Bug introduced by
$id of type string is incompatible with the type array expected by parameter $parameters of Illuminate\Routing\Redirector::route(). ( Ignorable by Annotation )

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

172
            return redirect()->route('device.show', /** @scrutinizer ignore-type */ $id)
Loading history...
173
                ->with('success', 'Device updated successfully');
174
    }
175
176
    /**
177
     * Deletes a device.
178
     *
179
     * @param  string  $id
180
     * @return \Illuminate\Http\RedirectResponse
181
     */
182 View Code Duplication
    public function destroy($id)
183
    {
184
        $device = Device::withTrashed()->findOrFail($id);
185
186
        if ($device->trashed())
187
        {
188
            //If the device was already deleted then permanently delete it
189
            $device->forceDelete($device->id);
0 ignored issues
show
Unused Code introduced by
The call to App\User::forceDelete() has too many arguments starting with $device->id. ( Ignorable by Annotation )

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

189
            $device->/** @scrutinizer ignore-call */ 
190
                     forceDelete($device->id);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
190
        } else
191
        {
192
            //Remove the location from the device
193
            $device->location_id = null;
0 ignored issues
show
Bug introduced by
The property location_id does not seem to exist on App\User. Are you sure there is no database migration missing?

Checks if undeclared accessed properties appear in database migrations and if the creating migration is correct.

Loading history...
194
            $device->save();
195
            
196
            //Soft delete the device the first time
197
            $device->delete();
198
        }
199
200
        return redirect()->route('device.index')
201
            ->with('success', 'Device deleted successfully');
202
    }
203
    
204
    /**
205
     * Restores a device.
206
     *
207
     * @param  string  $id
208
     * @return \Illuminate\Http\RedirectResponse
209
     */
210 View Code Duplication
    public function restore($id)
211
    {
212
        $device = Device::onlyTrashed()->findOrFail($id);
213
214
        $device->restore();
215
        
216
        return redirect()->route('device.show', $device->id)
0 ignored issues
show
Bug introduced by
$device->id of type integer is incompatible with the type array expected by parameter $parameters of Illuminate\Routing\Redirector::route(). ( Ignorable by Annotation )

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

216
        return redirect()->route('device.show', /** @scrutinizer ignore-type */ $device->id)
Loading history...
217
            ->with('success', 'Device restored successfully');
218
    }
219
}
220