Passed
Pull Request — master (#65)
by Rafael
04:59
created

UserLinkedSourcesController   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 137
Duplicated Lines 0 %

Test Coverage

Coverage 85.96%

Importance

Changes 0
Metric Value
eloc 58
dl 0
loc 137
ccs 49
cts 57
cp 0.8596
rs 10
c 0
b 0
f 0
wmc 13

3 Methods

Rating   Name   Duplication   Size   Complexity  
B detachDevice() 0 42 6
B devices() 0 51 6
A onConstruct() 0 5 1
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
 *
21
 */
22
class UserLinkedSourcesController extends BaseController
23
{
24
    /*
25
     * fields we accept to create
26
     *
27
     * @var array
28
     */
29
    protected $createFields = ['users_id', 'source_id', 'source_users_id', 'source_users_id_text', 'source_username'];
30
31
    /*
32
     * fields we accept to create
33
     *
34
     * @var array
35
     */
36
    protected $updateFields = ['users_id', 'source_id', 'source_users_id', 'source_users_id_text', 'source_username'];
37
38
    /**
39
     * set objects
40
     *
41
     * @return void
42
     */
43 3
    public function onConstruct()
44
    {
45 3
        $this->model = new UserLinkedSources();
46 3
        $this->additionalSearchFields = [
47
            ['is_deleted', ':', '0'],
48
        ];
49 3
    }
50
51
    /**
52
     * Associate a Device with the corrent loggedin user
53
     *
54
     * @url /users/{id}/device
55
     * @method POST
56
     * @return Response
57
     */
58 2
    public function devices() : Response
59
    {
60
        //Ok let validate user password
61 2
        $validation = new Validation();
62 2
        $validation->add('app', new PresenceOf(['message' => _('App name is required.')]));
63 2
        $validation->add('deviceId', new PresenceOf(['message' => _('device ID is required.')]));
64 2
        $msg = null;
65
66
        //validate this form for password
67 2
        $messages = $validation->validate($this->request->getPost());
68 2
        if (count($messages)) {
69
            foreach ($messages as $message) {
70
                throw new BadRequestHttpException((string)$message);
71
            }
72
        }
73
74 2
        $app = $this->request->getPost('app', 'string');
75 2
        $deviceId = $this->request->getPost('deviceId', 'string');
76
77
        //get the app source
78 2
        if ($source = Sources::getByTitle($app)) {
79 2
            $userSource = UserLinkedSources::findFirst([
80 2
                'conditions' => 'users_id = ?0 and source_users_id_text = ?1',
81 2
                'bind' => [$this->userData->getId(), $deviceId]
0 ignored issues
show
Bug Best Practice introduced by
The property userData does not exist on Gewaer\Api\Controllers\UserLinkedSourcesController. Since you implemented __get, consider adding a @property annotation.
Loading history...
82
            ]);
83
84 2
            if (!is_object($userSource)) {
85 1
                $userSource = new UserLinkedSources();
86 1
                $userSource->users_id = $this->userData->getId();
87 1
                $userSource->source_id = $source->getId();
88 1
                $userSource->source_users_id = $this->userData->getId();
89 1
                $userSource->source_users_id_text = $deviceId;
90 1
                $userSource->source_username = $this->userData->displayname . ' ' . $app;
91 1
                $userSource->is_deleted = 0;
92
93 1
                if (!$userSource->save()) {
94
                    throw new UnprocessableEntityHttpException((string) current($userSource->getMessages()));
95
                }
96
97 1
                $msg = 'User Device Associated';
98
            } else {
99 1
                $msg = 'User Device Already Associated';
100
            }
101
        }
102
103
        //clean password @todo move this to a better place
104 2
        $this->userData->password = null;
105
106 2
        return $this->response([
107 2
            'msg' => $msg,
108 2
            'user' => $this->userData
109
        ]);
110
    }
111
112
    /**
113
     * Detach user's devices
114
     * @param integer $deviceId User's devices id
115
     * @return Response
116
     */
117 1
    public function detachDevice(int $id, int $deviceId): Response
118
    {
119
        //Validation
120 1
        $validation = new Validation();
121 1
        $validation->add('app', new PresenceOf(['message' => _('App name is required.')]));
122
123
        //validate this form for password
124 1
        $messages = $validation->validate($this->request->getPost());
125 1
        if (count($messages)) {
126
            foreach ($messages as $message) {
127
                throw new BadRequestHttpException((string)$message);
128
            }
129
        }
130
131 1
        $app = $this->request->getPost('app', 'string');
132
133
        //Get Source
134
135 1
        $source = Sources::getByTitle($app);
136
137 1
        if (!is_object($source)) {
138
            throw new NotFoundHttpException('Source not found');
139
        }
140
141 1
        $userSource = UserLinkedSources::findFirst([
142 1
                'conditions' => 'users_id = ?0 and source_id = ?1 and source_users_id_text = ?2 and is_deleted = 0',
143 1
                'bind' => [$this->userData->getId(), $source->getId(), $deviceId]
0 ignored issues
show
Bug Best Practice introduced by
The property userData does not exist on Gewaer\Api\Controllers\UserLinkedSourcesController. Since you implemented __get, consider adding a @property annotation.
Loading history...
144
            ]);
145
146
        //Check if User Linked Sources exists by users_id and source_users_id_text
147 1
        if (!is_object($userSource)) {
148
            throw new NotFoundHttpException('User Linked Source not found');
149
        }
150
151 1
        $userSource->is_deleted = 1;
152 1
        if (!$userSource->update()) {
153
            throw new UnprocessableEntityHttpException((string) current($userSource->getMessages()));
154
        }
155
156 1
        return $this->response([
157 1
                'msg' => 'User Device detached',
158 1
                'user' => $this->userData
159
            ]);
160
    }
161
}
162