Passed
Pull Request — master (#65)
by Rafael
09:35
created

UserLinkedSourcesController::detachDevice()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 42
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.4227

Importance

Changes 0
Metric Value
cc 6
eloc 21
nc 9
nop 2
dl 0
loc 42
ccs 17
cts 22
cp 0.7727
crap 6.4227
rs 8.9617
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gewaer\Api\Controllers;
6
7
use Gewaer\Models\UserLinkedSources;
8
use Baka\Auth\Models\Sources;
9
use Phalcon\Http\Response;
10
use Phalcon\Validation;
11
use Phalcon\Validation\Validator\PresenceOf;
12
use Gewaer\Exception\BadRequestHttpException;
13
use Gewaer\Exception\NotFoundHttpException;
14
use Gewaer\Exception\UnprocessableEntityHttpException;
15
16
/**
17
 * Class LanguagesController
18
 *
19
 * @package Gewaer\Api\Controllers
20
 * @property UserData $userData
21
 *
22
 */
23
class UserLinkedSourcesController extends BaseController
24
{
25
    /*
26
     * fields we accept to create
27
     *
28
     * @var array
29
     */
30
    protected $createFields = ['users_id', 'source_id', 'source_users_id', 'source_users_id_text', 'source_username'];
31
32
    /*
33
     * fields we accept to create
34
     *
35
     * @var array
36
     */
37
    protected $updateFields = ['users_id', 'source_id', 'source_users_id', 'source_users_id_text', 'source_username'];
38
39
    /**
40
     * set objects
41
     *
42
     * @return void
43
     */
44 3
    public function onConstruct()
45
    {
46 3
        $this->model = new UserLinkedSources();
47 3
        $this->additionalSearchFields = [
48
            ['is_deleted', ':', '0'],
49
        ];
50 3
    }
51
52
    /**
53
     * Associate a Device with the corrent loggedin user
54
     *
55
     * @url /users/{id}/device
56
     * @method POST
57
     * @return Response
58
     */
59 2
    public function devices() : Response
60
    {
61
        //Ok let validate user password
62 2
        $validation = new Validation();
63 2
        $validation->add('app', new PresenceOf(['message' => _('App name is required.')]));
64 2
        $validation->add('deviceId', new PresenceOf(['message' => _('device ID is required.')]));
65 2
        $msg = null;
66
67
        //validate this form for password
68 2
        $messages = $validation->validate($this->request->getPost());
69 2
        if (count($messages)) {
70
            foreach ($messages as $message) {
71
                throw new BadRequestHttpException((string)$message);
72
            }
73
        }
74
75 2
        $app = $this->request->getPost('app', 'string');
76 2
        $deviceId = $this->request->getPost('deviceId', 'string');
77
78
        //get the app source
79 2
        if ($source = Sources::getByTitle($app)) {
80 2
            $userSource = UserLinkedSources::findFirst([
81 2
                'conditions' => 'users_id = ?0 and source_users_id_text = ?1',
82 2
                'bind' => [$this->userData->getId(), $deviceId]
83
            ]);
84
85 2
            if (!is_object($userSource)) {
86 1
                $userSource = new UserLinkedSources();
87 1
                $userSource->users_id = $this->userData->getId();
88 1
                $userSource->source_id = $source->getId();
89 1
                $userSource->source_users_id = $this->userData->getId();
90 1
                $userSource->source_users_id_text = $deviceId;
91 1
                $userSource->source_username = $this->userData->displayname . ' ' . $app;
92 1
                $userSource->is_deleted = 0;
93
94 1
                if (!$userSource->save()) {
95
                    throw new UnprocessableEntityHttpException((string) current($userSource->getMessages()));
96
                }
97
98 1
                $msg = 'User Device Associated';
99
            } else {
100 1
                $msg = 'User Device Already Associated';
101
            }
102
        }
103
104
        //clean password @todo move this to a better place
105 2
        $this->userData->password = null;
106
107 2
        return $this->response([
108 2
            'msg' => $msg,
109 2
            'user' => $this->userData
110
        ]);
111
    }
112
113
    /**
114
     * Detach user's devices
115
     * @param integer $deviceId User's devices id
116
     * @return Response
117
     */
118 1
    public function detachDevice(int $id, int $deviceId): Response
119
    {
120
        //Validation
121 1
        $validation = new Validation();
122 1
        $validation->add('app', new PresenceOf(['message' => _('App name is required.')]));
123
124
        //validate this form for password
125 1
        $messages = $validation->validate($this->request->getPost());
126 1
        if (count($messages)) {
127
            foreach ($messages as $message) {
128
                throw new BadRequestHttpException((string)$message);
129
            }
130
        }
131
132 1
        $app = $this->request->getPost('app', 'string');
133
134
        //Get Source
135
136 1
        $source = Sources::getByTitle($app);
137
138 1
        if (!is_object($source)) {
139
            throw new NotFoundHttpException('Source not found');
140
        }
141
142 1
        $userSource = UserLinkedSources::findFirst([
143 1
                'conditions' => 'users_id = ?0 and source_id = ?1 and source_users_id_text = ?2 and is_deleted = 0',
144 1
                'bind' => [$this->userData->getId(), $source->getId(), $deviceId]
145
            ]);
146
147
        //Check if User Linked Sources exists by users_id and source_users_id_text
148 1
        if (!is_object($userSource)) {
149
            throw new NotFoundHttpException('User Linked Source not found');
150
        }
151
152 1
        $userSource->is_deleted = 1;
153 1
        if (!$userSource->update()) {
154
            throw new UnprocessableEntityHttpException((string) current($userSource->getMessages()));
155
        }
156
157 1
        return $this->response([
158 1
                'msg' => 'User Device detached',
159 1
                'user' => $this->userData
160
            ]);
161
    }
162
}
163