ApiController::update()   B
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 2
eloc 25
c 3
b 0
f 0
nc 2
nop 1
dl 0
loc 41
ccs 0
cts 17
cp 0
crap 6
rs 8.8571
1
<?php
2
3
namespace App\Http\Controllers;
4
5
use Validator;
6
use Illuminate\Http\Request;
7
use App\Device;
8
use App\Deviceimage;
9
use App\User;
10
use App\Sensor;
11
use App\SensorData;
12
use Carbon\Carbon;
13
14
class ApiController extends Controller
15
{
16
    /**
17
     * Creates a json response for all the devices.
18
     *
19
     * @return \Illuminate\Http\JsonResponse
20
     */    
21
    public function index()
22
    {
23
        return response()->json([ 'data' => 'SmartSettia API - Bad request type.' ], 400);
24
    }
25
26
    /**
27
     * Creates a json response for a specifc device.
28
     *
29
     * @param  Device  $device
30
     * @return \Illuminate\Http\JsonResponse
31
     */    
32
    public function show(Device $device)
33
    {
34
        return response()->json($device, 200);
35
    }
36
37
    /**
38
     * Updates the status of a device.
39
     *
40
     * @param  Request  $request
41
     * @return \Illuminate\Http\JsonResponse
42
     */
43
    public function update(Request $request)
44
    {
45
        // Validate the request
46
        $validator = Validator::make($request->all(), [
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $validator is correct as Validator::make($request...r_string'))->validate() targeting Illuminate\Validation\Validator::validate() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
The assignment to $validator is dead and can be removed.
Loading history...
47
            'uuid'          => 'required|size:36|uuid|exists:devices,uuid',
48
            'token'         => 'required|max:60|alpha_num|exists:devices,token',
49
            'version'       => 'nullable|max:32|version',
50
            'hostname'      => 'nullable|max:255|url',
51
            'ip'            => 'nullable|ip',
52
            'mac_address'   => 'nullable|size:12|mac',
53
            'time'          => 'nullable|date',
54
            'cover_status'  => 'nullable|alpha|max:7|in:opening,closing,open,closed,locked,error',
55
            'cover_command'  => 'nullable|alpha|max:5|in:open,close',
56
            'error_msg'     => 'nullable|max:1000|error_string',
57
        ])->validate();
58
        
59
        // Get the device record.
60
        $device = Device::getDeviceByUUID($request->input('uuid'));
0 ignored issues
show
Bug introduced by
$request->input('uuid') of type array is incompatible with the type string expected by parameter $uuid of App\Device::getDeviceByUUID(). ( Ignorable by Annotation )

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

60
        $device = Device::getDeviceByUUID(/** @scrutinizer ignore-type */ $request->input('uuid'));
Loading history...
61
        
62
        // Update the device.
63
        $device->version = $request->input('version');
64
        $device->hostname = $request->input('hostname');
65
        $device->ip = $request->input('ip');
66
        $device->mac_address = $request->input('mac_address');
67
        $device->time = $request->input('time');
68
        $device->cover_status = $request->input('cover_status');
69
        if ($request->input('cover_command') != null) {
70
                    $device->cover_command = $request->input('cover_command');
71
        }
72
        $device->error_msg = $request->input('error_msg');
73
        $device->last_network_update_at = Carbon::now();
74
        
75
        $device->save();
76
        
77
        // A 'Registered' event is created and will trigger any relevant
78
        // observers, such as sending a confirmation email or any 
79
        // code that needs to be run as soon as the device is created.
80
        //event(new Registered(true));
81
        
82
        // Return the new device info including the token.
83
        return response()->json([ 'data' => $device->toArray() ], 201);
84
    }
85
    
86
    /**
87
     * Updates the sensors of a device.
88
     *
89
     * @param  Request  $request
90
     * @return \Illuminate\Http\JsonResponse
91
     */
92
    public function sensor(Request $request)
93
    {
94
        // Validate the request
95
        Validator::make($request->all(), [
96
            'uuid'          => 'required|size:36|uuid|exists:devices,uuid',
97
            'token'         => 'required|max:60|alpha_num|exists:devices,token',
98
            'sensor_data.*.name'   => 'required|min:2|max:190|name',
99
            'sensor_data.*.type'   => 'required|max:190|type_name',
100
            'sensor_data.*.value'  => 'required|max:190|value_string',
101
        ])->validate();
102
        
103
        // Get the device record.
104
        $device = Device::getDeviceByUUID($request->input('uuid'));
0 ignored issues
show
Bug introduced by
$request->input('uuid') of type array is incompatible with the type string expected by parameter $uuid of App\Device::getDeviceByUUID(). ( Ignorable by Annotation )

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

104
        $device = Device::getDeviceByUUID(/** @scrutinizer ignore-type */ $request->input('uuid'));
Loading history...
105
        
106
        // Update the device.
107
// 		"sensor_data": {
108
// 			{ "name": "cpu", "type": "cpu_temperature", "value": cpu_temp() },
109
// 			{ "name": "temperature", "type": "temperature", "value": temperature() },
110
// 			{ "name": "humidity", "type": "humidity", "value": humidity() },
111
// 			{ "name": "moisture_01", "type": "moisture", "value": 0.00 },
112
// 			{ "name": "moisture_02", "type": "moisture", "value": 0.00 },
113
// 			{ "name": "light_in", "type": "light", "value": 0.00 },
114
// 			{ "name": "light_out", "type": "light", "value": 0.00 }
115
// 		}
116
        $sensor_datas = $request->input('sensor_data');
117
        foreach ($sensor_datas as $sensor_data) {
118
            $sensor = Sensor::firstOrCreate([
119
                "device_id" => $device->id,
120
                "name" => $sensor_data[ 'name' ], 
121
                "type" => $sensor_data[ 'type' ]
122
            ]);
123
            
124
            SensorData::create([
125
                "sensor_id" => $sensor->id,
126
                "value" => $sensor_data[ 'value' ]
127
            ]);
128
        }
129
        
130
        // A 'Registered' event is created and will trigger any relevant
131
        // observers, such as sending a confirmation email or any 
132
        // code that needs to be run as soon as the device is created.
133
        //event(new Registered(true));
134
        
135
        // Return the new device info including the token.
136
        return response()->json([ 'data' => $device->toArray() ], 201);
137
    }
138
    
139
    /**
140
     * Registers a new device.
141
     *
142
     * @param  Request  $request
143
     * @return \Illuminate\Http\JsonResponse
144
     */
145
    public function register(Request $request)
146
    {
147
        // Validate the request.
148
        Validator::make($request->all(), [
149
            'uuid' => 'required|size:36|uuid',
150
            'challenge' => 'required|min:6|string',
151
        ])->validate();
152
        
153
        // If challenge string doesnt match then send 401 unauthorized.
154
        if ($request->input('challenge') != env('API_CHALLENGE', 'temppass')) {
155
            return response()->json([ 'data' => 'Bad challenge.' ], 401);
156
        }
157
        
158
        // If the uuid already exists then just send them the record.
159
        if ($device = Device::getDeviceByUUID($request->input('uuid'))) {
0 ignored issues
show
Bug introduced by
$request->input('uuid') of type array is incompatible with the type string expected by parameter $uuid of App\Device::getDeviceByUUID(). ( Ignorable by Annotation )

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

159
        if ($device = Device::getDeviceByUUID(/** @scrutinizer ignore-type */ $request->input('uuid'))) {
Loading history...
160
            return response()->json([ 'data' => [ 
161
                'name' => $device->name,
162
                'uuid' => $device->uuid,
163
                'id' => $device->id,
164
                'token' => $device->token,
165
            ] ], 200);
166
        }
167
        
168
        // Create the new device.
169
        $device = new Device;
170
        $device->name = 'New Device';
171
        $device->uuid = $request->input('uuid');
172
        $device->save();
173
        
174
        // Create an api token for the new device.
175
        $device->generateToken();
176
        
177
        // A 'Registered' event is created and will trigger any relevant
178
        // observers, such as sending a confirmation email or any 
179
        // code that needs to be run as soon as the device is created.
180
        //event(new Registered(true));
181
        //Notification::send(User::managers(), new DeviceRegister($device));
182
        
183
        // Return the new device info including the token.
184
        return response()->json([ 'data' => [ 
185
            'name' => $device->name,
186
            'uuid' => $device->uuid,
187
            'id' => $device->id,
188
            'token' => $device->token,
189
        ] ], 201);
190
    }
191
    
192
    /**
193
     * Updates the image for a device.
194
     *
195
     * @param  Request  $request
196
     * @return \Illuminate\Http\JsonResponse
197
     */
198
    public function image(Request $request) {
199
        // Validate the request.
200
        Validator::make($request->all(), [
201
            'uuid'          => 'required|size:36|uuid|exists:devices,uuid',
202
            'token'         => 'required|max:60|alpha_num|exists:devices,token',
203
            'image'         => 'required|image|mimes:jpeg,jpg,png,gif|max:2048',
204
        ])->validate();
205
        
206
        // Get the device record.
207
        $device = Device::getDeviceByUUID($request->input('uuid'));
0 ignored issues
show
Bug introduced by
$request->input('uuid') of type array is incompatible with the type string expected by parameter $uuid of App\Device::getDeviceByUUID(). ( Ignorable by Annotation )

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

207
        $device = Device::getDeviceByUUID(/** @scrutinizer ignore-type */ $request->input('uuid'));
Loading history...
208
        
209
        // Save the image to disk.
210
        $path = $request->file('image')->storeAs('deviceimage', $device[ 'id' ], 'private');
211
        
212
        // Update the url for the image.
213
        $deviceimage = Deviceimage::updateOrCreate(
214
            [ 'device_id' => $device[ 'id' ] ],
215
            [ 'url' => $path ]
216
        );
217
        
218
        // Force the updated_at timestamp to update as the url may not change.
219
        $deviceimage->touch();
220
        
221
        return response()->json([ 'data' => [ 
222
            'id' => $deviceimage[ 'id' ],
223
            'url' => $path,
224
        ] ], 201);
225
    }
226
}
227
228
// HTTP STATUS CODES:
229
// 200: OK. The standard success code and default option.
230
// 201: Object created. Useful for the store actions.
231
// 204: No content. When an action was executed successfully, but there is no content to return.
232
// 206: Partial content. Useful when you have to return a paginated list of resources.
233
// 400: Bad request. The standard option for requests that fail to pass validation.
234
// 401: Unauthorized. The user needs to be authenticated.
235
// 403: Forbidden. The user is authenticated, but does not have the permissions to perform an action.
236
// 404: Not found. This will be returned automatically by Laravel when the resource is not found.
237
// 500: Internal server error. Ideally you're not going to be explicitly returning this, but if something unexpected breaks, this is what your user is going to receive.
238
// 503: Service unavailable. Pretty self explanatory, but also another code that is not going to be returned explicitly by the application.
239