Completed
Pull Request — master (#82)
by Brandon
02:06
created

ApiController::sensor()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 46
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 46
ccs 0
cts 15
cp 0
rs 8.9411
cc 2
eloc 19
nc 2
nop 1
crap 6
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 Illuminate\Support\Facades\Cache;
13
use Illuminate\Support\Facades\Storage;
14
15
class ApiController extends Controller
16
{
17
    /**
18
     * Creates a json response for all the devices.
19
     *
20
     * @return Response
21
     */    
22
    public function index()
23
    {
24
        return response()->json(['data' => 'SmartSettia API - Bad request type.'], 400);
25
    }
26
27
    /**
28
     * Creates a json response for a specifc device.
29
     *
30
     * @param  Device  $device
31
     * @return Response
32
     */    
33
    public function show(Device $device)
34
    {
35
        return response()->json($device, 200);
36
    }
37
38
    /**
39
     * Updates the status of a device.
40
     *
41
     * @param  Request  $request
42
     * @return Response
43
     */
44
    public function update(Request $request)
45
    {
46
        // Validate the request
47
        $validator = Validator::make($request->all(), [
0 ignored issues
show
Unused Code introduced by
$validator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
48
            'uuid'          => 'required|string|max:255|exists:devices,uuid',
49
            'token'         => 'required|string|max:60|exists:devices,token',
50
            'version'       => 'nullable|string|max:32',
51
            'hostname'      => 'nullable|string|max:255',
52
            'ip'            => 'nullable|ip',
53
            'mac_address'   => 'nullable|string|min:12|max:12',
54
            'time'          => 'nullable|date',
55
            'cover_status'  => 'nullable|string|max:32',
56
            'error_msg'     => 'nullable|string',
57
            'limitsw_open'   => 'nullable|boolean',
58
            'limitsw_closed' => 'nullable|boolean',
59
            'light_in'      => 'nullable|numeric',
60
            'light_out'     => 'nullable|numeric',
61
            'cpu_temp'      => 'nullable|numeric',
62
            'temperature'   => 'nullable|numeric',
63
            'humidity'      => 'nullable|numeric',
64
        ])->validate();
65
        
66
        // Get the device record.
67
        $device = Device::getDeviceByUUID($request->input('uuid'));
68
        
69
        // Update the device.
70
        $device->version = $request->input('version');
71
        $device->hostname = $request->input('hostname');
72
        $device->ip = $request->input('ip');
73
        $device->mac_address = $request->input('mac_address');
74
        $device->time = $request->input('time');
75
        $device->cover_status = $request->input('cover_status');
76
        $device->error_msg = $request->input('error_msg');
77
        $device->limitsw_open = $request->input('limitsw_open');
78
        $device->limitsw_closed = $request->input('limitsw_closed');
79
        $device->light_in = $request->input('light_in');
80
        $device->light_out = $request->input('light_out');
81
        $device->cpu_temp = $request->input('cpu_temp');
82
        $device->temperature = $request->input('temperature');
83
        $device->humidity = $request->input('humidity');
84
        
85
        $device->save();
86
        
87
        // A 'Registered' event is created and will trigger any relevant
88
        // observers, such as sending a confirmation email or any 
89
        // code that needs to be run as soon as the device is created.
90
        //event(new Registered(true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
91
        
92
        // Return the new device info including the token.
93
        return response()->json(['data' => $device->toArray()], 201);
94
    }
95
    
96
    /**
97
     * Updates the sensors of a device.
98
     *
99
     * @param  Request  $request
100
     * @return Response
101
     */
102
    public function sensor(Request $request)
103
    {
104
        // Validate the request
105
        $validator = Validator::make($request->all(), [
0 ignored issues
show
Unused Code introduced by
$validator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
106
            'uuid'          => 'required|string|max:255|exists:devices,uuid',
107
            'token'         => 'required|string|max:60|exists:devices,token',
108
            'sensor_data.*.name'   => 'required|max:190',
109
            'sensor_data.*.type'   => 'required|max:190',
110
            'sensor_data.*.value'  => 'required|max:190',
111
        ])->validate();
112
        
113
        // Get the device record.
114
        $device = Device::getDeviceByUUID($request->input('uuid'));
115
        
116
        // Update the device.
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
117
// 		"sensor_data": {
118
// 			{ "name": "cpu", "type": "cpu_temperature", "value": cpu_temp() },
119
// 			{ "name": "temperature", "type": "temperature", "value": temperature() },
120
// 			{ "name": "humidity", "type": "humidity", "value": humidity() },
121
// 			{ "name": "moisture_01", "type": "moisture", "value": 0.00 },
122
// 			{ "name": "moisture_02", "type": "moisture", "value": 0.00 },
123
// 			{ "name": "light_in", "type": "light", "value": 0.00 },
124
// 			{ "name": "light_out", "type": "light", "value": 0.00 }
125
// 		}
126
        $sensor_datas = $request->input('sensor_data');
127
        foreach ($sensor_datas as $sensor_data) {
0 ignored issues
show
Bug introduced by
The expression $sensor_datas of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
128
            $sensor = Sensor::firstOrCreate([
129
                "device_id" => $device->id,
130
                "name" => $sensor_data['name'], 
131
                "type" => $sensor_data['type']
132
            ]);
133
            
134
            SensorData::create([
135
                "sensor_id" => $sensor->id,
136
                "value" => $sensor_data['value']
137
            ]);
138
        }
139
        
140
        // A 'Registered' event is created and will trigger any relevant
141
        // observers, such as sending a confirmation email or any 
142
        // code that needs to be run as soon as the device is created.
143
        //event(new Registered(true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
144
        
145
        // Return the new device info including the token.
146
        return response()->json(['data' => $device->toArray()], 201);
147
    }
148
    
149
    /**
150
     * Registers a new device.
151
     *
152
     * @param  Request  $request
153
     * @return Response
154
     */
155
    public function register(Request $request)
156
    {
157
        // Validate the request.
158
        $validator = Validator::make($request->all(), [
0 ignored issues
show
Unused Code introduced by
$validator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
159
            'uuid' => 'required|string|max:255',
160
            'challenge' => 'required|string|min:6',
161
        ])->validate();
162
        
163
        // If challenge string doesnt match then send 401 unauthorized.
164
        if ($request->input('challenge') != env('API_CHALLENGE', 'temppass')) {
165
            return response()->json(['data' => 'Bad challenge.'], 401);
166
        }
167
        
168
        // If the uuid already exists then just send them the record.
169
        if ($device = Device::getDeviceByUUID($request->input('uuid'))) {
170
            return response()->json([ 'data' => [ 
171
                'name' => $device->name,
172
                'uuid' => $device->uuid,
173
                'id' => $device->id,
174
                'token' => $device->token,
175
            ]], 200);
176
        }
177
        
178
        // Create the new device.
179
        $device = new Device;
180
        $device->name = 'New Device';
181
        $device->uuid = $request->input('uuid');
182
        $device->save();
183
        
184
        // Create an api token for the new device.
185
        $device->generateToken();
186
        
187
        // A 'Registered' event is created and will trigger any relevant
188
        // observers, such as sending a confirmation email or any 
189
        // code that needs to be run as soon as the device is created.
190
        //event(new Registered(true));
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
191
        //Notification::send(User::managers(), new DeviceRegister($device));
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
192
        
193
        // Return the new device info including the token.
194
        return response()->json([ 'data' => [ 
195
            'name' => $device->name,
196
            'uuid' => $device->uuid,
197
            'id' => $device->id,
198
            'token' => $device->token,
199
        ]], 201);
200
    }
201
    
202
    /**
203
     * Updates the image for a device.
204
     *
205
     * @param  Request  $request
206
     * @return Response
207
     */
208
    public function image(Request $request) {
209
        // Validate the request.
210
        $validator = Validator::make($request->all(), [
0 ignored issues
show
Unused Code introduced by
$validator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
211
            'uuid'          => 'required|string|max:255|exists:devices,uuid',
212
            'token'         => 'required|string|max:60|exists:devices,token',
213
            'image'         => 'required|image|mimes:jpeg,jpg,png,gif|max:2048',
214
        ])->validate();
215
        
216
        // Get the device record.
217
        $device = Device::getDeviceByUUID($request->input('uuid'));
218
        
219
        // Save the image to disk.
220
        $path = $request->file('image')->storeAs('deviceimage', $device['id'], 'private');
221
        
222
        // Update the url for the image.
223
        $deviceimage = Deviceimage::updateOrCreate(
224
            ['device_id' => $device['id']],
225
            ['url' => $path]
226
        );
227
        
228
        // Force the updated_at timestamp to update as the url may not change.
229
        $deviceimage->touch();
230
        
231
        return response()->json([ 'data' => [ 
232
            'id' => $deviceimage['id'],
233
            'url' => $path,
234
        ]], 201);
235
    }
236
}
237
238
// HTTP STATUS CODES:
239
// 200: OK. The standard success code and default option.
240
// 201: Object created. Useful for the store actions.
241
// 204: No content. When an action was executed successfully, but there is no content to return.
242
// 206: Partial content. Useful when you have to return a paginated list of resources.
243
// 400: Bad request. The standard option for requests that fail to pass validation.
244
// 401: Unauthorized. The user needs to be authenticated.
245
// 403: Forbidden. The user is authenticated, but does not have the permissions to perform an action.
246
// 404: Not found. This will be returned automatically by Laravel when the resource is not found.
247
// 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.
248
// 503: Service unavailable. Pretty self explanatory, but also another code that is not going to be returned explicitly by the application.