Completed
Push — master ( 659d82...f5ba6f )
by Arthur
05:40
created

ACSController::handleDevice()   B

Complexity

Conditions 3
Paths 7

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 17
nc 7
nop 1
1
<?php namespace BB\Http\Controllers;
2
3
use BB\Entities\DetectedDevice;
4
use BB\Events\MemberActivity;
5
use BB\Exceptions\ValidationException;
6
use BB\Repo\ACSNodeRepository;
7
use BB\Repo\EquipmentLogRepository;
8
use BB\Validators\ACSValidator;
9
10
class ACSController extends Controller
11
{
12
13
    /**
14
     * @var ACSNodeRepository
15
     */
16
    private $deviceRepository;
0 ignored issues
show
Unused Code introduced by
The property $deviceRepository is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
17
    /**
18
     * @var ACSValidator
19
     */
20
    private $ACSValidator;
21
    /**
22
     * @var \BB\Services\KeyFobAccess
23
     */
24
    private $keyFobAccess;
25
    /**
26
     * @var EquipmentLogRepository
27
     */
28
    private $equipmentLogRepository;
29
30
    function __construct(ACSNodeRepository $acsNodeRepository, ACSValidator $ACSValidator, \BB\Services\KeyFobAccess $keyFobAccess, EquipmentLogRepository $equipmentLogRepository) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
31
        $this->acsNodeRepository = $acsNodeRepository;
0 ignored issues
show
Bug introduced by
The property acsNodeRepository does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
32
        $this->ACSValidator     = $ACSValidator;
33
        $this->keyFobAccess     = $keyFobAccess;
34
        $this->equipmentLogRepository = $equipmentLogRepository;
35
    }
36
37
    public function get()
38
    {
39
40
    }
41
42
    public function store()
43
    {
44
        $data = \Request::only('device', 'service', 'message', 'tag', 'time', 'payload', 'signature', 'nonce');
45
46
        //device = the device id from the devices table - unique to each piece of hardware
47
        //service = what the request is for, entry, usage, consumable
48
        //message = system message, heartbeat, boot
49
        //tag = the keyfob id
50
        //time = the time of the action
51
        //payload = any extra data relavent to the request
52
        //signature = an encoded value generated using a secret key - oauth style
53
        //nonce = a unique value suitable to stop replay attacks
54
55
        $this->ACSValidator->validate($data);
56
57
58
        //System messages
59
        if (in_array($data['message'], ['boot', 'heartbeat'])) {
60
            return $this->handleSystemCheckIn($data['message'], $data['device'], $data['service']);
61
        }
62
63
64
        switch ($data['service']) {
65
            case 'entry':
66
                return $this->handleDoor($data);
67
            case 'usage':
68
                return $this->handleDevice($data);
69
            case 'consumable':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
70
71
                break;
72
            case 'shop':
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
73
74
                break;
75
            case 'status':
76
                return $this->returnMemberStatus($data);
77
78
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
79
            default:
80
                \Log::debug(json_encode($data));
81
        }
82
83
        $responseArray = [
84
            'time'      => time(),
85
            'command'   => null,      //stored command for the device to process
86
            'valid'     => true,      //member request
87
            'available' => true,      //device status - remote shutdown,
88
            'member'    => null,      //member name
89
        ];
90
91
    }
92
93
    private function handleDoor($data)
94
    {
95
        //Door entry is quite simple - this will just deal with lookups
96
97
        try {
98
            $this->keyFobAccess->verifyForEntry($data['tag'], 'main-door', $data['time']);
99
            $this->keyFobAccess->logSuccess();
100
        } catch (\Exception $e) {
101
            return $this->sendResponse(404, ['valid' => '0', 'cmd' => null]);
102
        }
103
104
        $cmd = $this->acsNodeRepository->popCommand($data['device']);
105
106
        $responseData = ['member' => $this->keyFobAccess->getMemberName(), 'valid' => '1', 'cmd' => $cmd];
107
        return $this->sendResponse(200, $responseData);
108
    }
109
110
    private function handleDevice($data)
111
    {
112
        $keyFob = $this->keyFobAccess->extendedKeyFobLookup($data['tag']);
113
114
        $node = ACSNode::where('device_id', $data['device'])->firstOrFail();
115
116
        try {
117
            if ($node->entry_device) {
118
                $this->keyFobAccess->verifyForEntry($data['tag'], $data['device'], $data['time']);
119
                $this->keyFobAccess->logSuccess();
120
            } else {
121
                $member     = $this->keyFobAccess->verifyForDevice($data['tag'], $data['device'], $data['time']);
122
                $activityId = $this->equipmentLogRepository->recordStartCloseExisting($keyFob->user->id, $keyFob->id,
123
                    $data['device']);
124
                event(new MemberActivity($keyFob, $data['device']));
125
            }
126
        } catch (ValidationException $e) {
127
            return $this->sendResponse(400, ['message' => $e->getMessage()]);
128
        }
129
130
        $deviceStatus = 'ok';
131
132
        $responseData = ['deviceStatus' => $deviceStatus];
133
134
        return $this->sendResponse(200, $responseData);
135
    }
136
137
138
    /**
139
     * System checkins are common across all devices
140
     * Record the time and return pending status messages
141
     *
142
     * @param $message
143
     * @param $device
144
     * @return Response
145
     */
146
    private function handleSystemCheckIn($message, $device, $service)
147
    {
148
        switch ($message) {
149
            case 'boot':
150
                $this->acsNodeRepository->logBoot($device);
151
                break;
152
            case 'heartbeat':
153
                $this->acsNodeRepository->logHeartbeat($device);
154
                break;
155
        }
156
157
        //The command comes from the database and will instruct the door entry system to clear its memory if set
158
        $cmd = $this->acsNodeRepository->popCommand($device);
159
160
        switch ($service) {
161
            case 'entry':
162
                //we don't have a system for this at the moment but could have a global shutdown option
163
                $deviceStatus = '1';
164
                break;
165
            case 'usage':
166
                //lookup the piece of equipment from the device id and get the status
167
                $deviceStatus = '1';
168
                break;
169
            default:
170
                $deviceStatus = '1';
171
        }
172
173
        $responseData = ['cmd' => $cmd, 'deviceStatus' => $deviceStatus];
174
175
        return $this->sendResponse(200, $responseData);
176
    }
177
178
    /**
179
     * Json encode the response data and return
180
     *
181
     * @param int   $statusCode
182
     * @param array $responseData
183
     *
184
     * @return \Response
185
     */
186
    private function sendResponse($statusCode = 200, array $responseData)
187
    {
188
        $responseData['time'] = time();
189
        $response = response()->json($responseData, $statusCode);
190
        $response->headers->set('Content-Length', strlen($response->getContent()));
191
        return $response;
192
    }
193
194
    private function returnMemberStatus($data)
195
    {
196
        try {
197
            $user = $this->keyFobAccess->verifyForEntry($data['tag'], 'main-door', $data['time']);
198
        } catch (\Exception $e) {
199
            $responseData = ['valid' => '0', 'cmd' => ''];
200
            return $this->sendResponse(404, $responseData);
201
        }
202
203
        $responseData = ['member' => $this->keyFobAccess->getMemberName(), 'valid' => '1', 'cmd' => ''];
204
205
        return $this->sendResponse(200, $responseData);
206
    }
207
208
} 
209