Completed
Push — master ( c356f0...560007 )
by Arthur
03:01
created

ACSController::handleStatus()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
dl 11
loc 11
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
1
<?php namespace BB\Http\Controllers;
2
3
use BB\Entities\ACSNode;
4
use BB\Entities\DetectedDevice;
5
use BB\Entities\User;
6
use BB\Events\MemberActivity;
7
use BB\Exceptions\ValidationException;
8
use BB\Repo\ACSNodeRepository;
9
use BB\Repo\EquipmentLogRepository;
10
use BB\Validators\ACSValidator;
11
use Exception;
12
13
class ACSController extends Controller
14
{
15
16
    /**
17
     * @var ACSNodeRepository
18
     */
19
    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...
20
    /**
21
     * @var ACSValidator
22
     */
23
    private $ACSValidator;
24
    /**
25
     * @var \BB\Services\KeyFobAccess
26
     */
27
    private $keyFobAccess;
28
    /**
29
     * @var EquipmentLogRepository
30
     */
31
    private $equipmentLogRepository;
32
33
    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...
34
        $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...
35
        $this->ACSValidator     = $ACSValidator;
36
        $this->keyFobAccess     = $keyFobAccess;
37
        $this->equipmentLogRepository = $equipmentLogRepository;
38
    }
39
40
    public function store()
41
    {
42
        $data = \Request::only('device', 'service', 'message', 'tag', 'time', 'payload', 'signature', 'nonce', 'session_id');
43
44
        //device = the node id from the acs table - unique to each acs
45
        //service = what the request is for, entry, usage, consumable
46
        //message = system message, heartbeat, boot
47
        //tag = the keyfob id
48
        //time = the time of the action
49
        //payload = any extra data relavent to the request
50
        //signature = an encoded value generated using a secret key - oauth style
51
        //nonce = a unique value suitable to stop replay attacks
52
        //session_id = the id of the current session the user is maintaining
53
54
        $this->ACSValidator->validate($data);
55
56
57
        //System messages
58
        if (in_array($data['message'], ['boot', 'heartbeat'])) {
59
            return $this->handleSystemCheckIn($data['message'], $data['device'], $data['service']);
60
        }
61
62
63
        switch ($data['service']) {
64
            case 'entry':
65
                return $this->handleDoor($data);
66
            case 'usage':
67
                return $this->handleDevice($data);
68
            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...
69
70
                break;
71
            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...
72
73
                break;
74
            case 'status':
75
                return $this->handleStatus($data);
76
77
                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...
78
            default:
79
                \Log::debug(json_encode($data));
80
        }
81
82
    }
83
84 View Code Duplication
    private function handleStatus($data)
85
    {
86
        try {
87
            /** @var User $user */
88
            $user = $this->keyFobAccess->verifyForEntry($data['tag'], 'main-door', $data['time']);
89
        } catch (\Exception $e) {
90
            return $this->sendResponse(404, []);
91
        }
92
93
        return $this->sendResponse(200, ['member' => $user->given_name]);
94
    }
95
96 View Code Duplication
    private function handleDoor($data)
97
    {
98
        //Door entry is quite simple - this will just deal with lookups
99
100
        try {
101
            /** @var User $user */
102
            $user = $this->keyFobAccess->verifyForEntry($data['tag'], 'main-door', $data['time']);
103
            $this->keyFobAccess->logSuccess();
104
        } catch (\Exception $e) {
105
            return $this->sendResponse(404, []);
106
        }
107
108
        return $this->sendResponse(200, ['member' => $user->given_name]);
109
    }
110
111
112
    private function handleDevice($data)
113
    {
114
        $sessionId = null;
115
        try {
116
            $device = ACSNode::where('device_id', $data['device'])->firstOrFail();
117
            if ($device->entry_device) {
118
                return $this->sendResponse(400, ['message' => 'This is an entry device only']);
119
            } else {
120
                $member = $this->keyFobAccess->verifyForDevice($data['tag'], $data['device'], $data['time']);
121
                $keyFob = $this->keyFobAccess->getKeyFob();
122
123
                if ($data['message'] == 'start') {
124
                    $sessionId = $this->equipmentLogRepository->recordStartCloseExisting($keyFob->user->id, $keyFob->id, $data['device']);
125
                    event(new MemberActivity($keyFob, $data['device']));
126
                } elseif ($data['message'] == 'stop') {
127
                    $this->equipmentLogRepository->endSession($data['session_id']);
128
                }
129
            }
130
        } catch (ValidationException $e) {
131
            return $this->sendResponse(400, ['message' => $e->getMessage()]);
132
        }
133
        return $this->sendResponse(200, ['member' => $member->given_name, 'session_id' => $sessionId]);
134
    }
135
136
    /**
137
     * System checkins are common across all devices
138
     * Record the time and return pending status messages
139
     *
140
     * @param $message
141
     * @param $device
142
     * @return Response
143
     */
144
    private function handleSystemCheckIn($message, $device, $service)
145
    {
146
        switch ($message) {
147
            case 'boot':
148
                $this->acsNodeRepository->logBoot($device);
149
                break;
150
            case 'heartbeat':
151
                $this->acsNodeRepository->logHeartbeat($device);
152
                break;
153
        }
154
155
        //The command comes from the database and will instruct the door entry system to clear its memory if set
156
        $cmd = $this->acsNodeRepository->popCommand($device);
157
158
        switch ($service) {
159
            case 'entry':
160
                //we don't have a system for this at the moment but could have a global shutdown option
161
                $deviceStatus = '1';
162
                break;
163
            case 'usage':
164
                //lookup the piece of equipment from the device id and get the status
165
                $deviceStatus = '1';
166
                break;
167
            default:
168
                $deviceStatus = '1';
169
        }
170
171
        $responseData = ['cmd' => $cmd, 'deviceStatus' => $deviceStatus];
172
173
        return $this->sendResponse(200, $responseData);
174
    }
175
176
    /**
177
     * Json encode the response data and return
178
     *
179
     * @param int   $statusCode
180
     * @param array $responseData
181
     *
182
     * @return \Response
183
     */
184
    private function sendResponse($statusCode = 200, array $responseData)
185
    {
186
        $responseData['time'] = time();
187
        $response = response()->json($responseData, $statusCode);
188
        $response->headers->set('Content-Length', strlen($response->getContent()));
189
        return $response;
190
    }
191
192
} 
193