Test Failed
Pull Request — master (#164)
by Maximo
07:06
created

UserLinkedSourcesController::devices()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 46
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 28
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 46
ccs 0
cts 34
cp 0
crap 20
rs 9.472
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Canvas\Api\Controllers;
6
7
use Canvas\Models\UserLinkedSources;
8
use Baka\Auth\Models\Sources;
9
use Phalcon\Http\Response;
10
use Phalcon\Validation;
11
use Phalcon\Validation\Validator\PresenceOf;
0 ignored issues
show
Bug introduced by
The type Phalcon\Validation\Validator\PresenceOf was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
12
use Canvas\Exception\BadRequestHttpException;
13
use Canvas\Exception\NotFoundHttpException;
14
use Canvas\Exception\UnprocessableEntityHttpException;
15
use Canvas\Validation as CanvasValidation;
16
17
/**
18
 * Class LanguagesController.
19
 *
20
 * @package Canvas\Api\Controllers
21
 * @property UserData $userData
22
 *
23
 */
24
class UserLinkedSourcesController extends BaseController
25
{
26
    /*
27
     * fields we accept to create
28
     *
29
     * @var array
30
     */
31
    protected $createFields = ['users_id', 'source_id', 'source_users_id', 'source_users_id_text', 'source_username'];
32
33
    /*
34
     * fields we accept to create
35
     *
36
     * @var array
37
     */
38
    protected $updateFields = ['users_id', 'source_id', 'source_users_id', 'source_users_id_text', 'source_username'];
39
40
    /**
41
     * set objects.
42
     *
43
     * @return void
44
     */
45
    public function onConstruct()
46
    {
47
        $this->model = new UserLinkedSources();
48
        $this->softDelete = 1;
49
        $this->additionalSearchFields = [
50
            ['is_deleted', ':', '0'],
51
            ['users_id', ':', $this->userData->getId()],
52
        ];
53
    }
54
55
    /**
56
     * Associate a Device with the corrent loggedin user.
57
     *
58
     * @url /users/{id}/device
59
     * @method POST
60
     * @return Response
61
     */
62
    public function devices() : Response
63
    {
64
        //Ok let validate user password
65
        $validation = new CanvasValidation();
66
        $validation->add('app', new PresenceOf(['message' => _('App name is required.')]));
67
        $validation->add('deviceId', new PresenceOf(['message' => _('device ID is required.')]));
68
        $msg = null;
69
70
        //validate this form for password
71
        $validation->validate($this->request->getPost());
72
73
        $app = $this->request->getPost('app', 'string');
74
        $deviceId = $this->request->getPost('deviceId', 'string');
75
76
        //get the app source
77
        if ($source = Sources::getByTitle($app)) {
78
            $userSource = UserLinkedSources::findFirst([
79
                'conditions' => 'users_id = ?0 and source_users_id_text = ?1 and source_id = ?2',
80
                'bind' => [$this->userData->getId(), $deviceId, $source->getId()]
81
            ]);
82
83
            if (!is_object($userSource)) {
84
                $userSource = new UserLinkedSources();
85
                $userSource->users_id = $this->userData->getId();
86
                $userSource->source_id = $source->getId();
87
                $userSource->source_users_id = $this->userData->getId();
88
                $userSource->source_users_id_text = $deviceId;
89
                $userSource->source_username = $this->userData->displayname . ' ' . $app;
90
                $userSource->is_deleted = 0;
91
92
                if (!$userSource->save()) {
93
                    throw new UnprocessableEntityHttpException((string) current($userSource->getMessages()));
94
                }
95
96
                $msg = 'User Device Associated';
97
            } else {
98
                $msg = 'User Device Already Associated';
99
            }
100
        }
101
102
        //clean password @todo move this to a better place
103
        $this->userData->password = null;
104
105
        return $this->response([
106
            'msg' => $msg,
107
            'user' => $this->userData
108
        ]);
109
    }
110
111
    /**
112
     * Detach user's devices.
113
     * @param integer $deviceId User's devices id
114
     * @return Response
115
     */
116
    public function detachDevice(int $id, int $deviceId): Response
117
    {
118
        //$sourceId = $this->request->getPost('source_id', 'int');
119
        $userSource = UserLinkedSources::findFirst([
120
            'conditions' => 'users_id = ?0  and source_users_id_text = ?1    and is_deleted = 0',
121
            'bind' => [$this->userData->getId(), $deviceId]
122
        ]);
123
124
        //Check if User Linked Sources exists by users_id and source_users_id_text
125
        if (!is_object($userSource)) {
126
            throw new NotFoundHttpException('User Linked Source not found');
127
        }
128
129
        $userSource->softDelete();
130
131
        return $this->response([
132
            'msg' => 'User Device detached',
133
            'user' => $this->userData
134
        ]);
135
    }
136
}
137