Passed
Push — master ( 1f91ec...0204e8 )
by Nils
04:11
created

ItemController::getAction()   B

Complexity

Conditions 11
Paths 82

Size

Total Lines 57
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 37
c 1
b 0
f 0
nc 82
nop 1
dl 0
loc 57
rs 7.3166

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Teampass - a collaborative passwords manager.
4
 * ---
5
 * This library is distributed in the hope that it will be useful,
6
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8
 * ---
9
 *
10
 * @project   Teampass
11
 * @version    API
12
 *
13
 * @file      ItemControler.php
14
 * ---
15
 *
16
 * @author    Nils Laumaillé ([email protected])
17
 *
18
 * @copyright 2009-2023 Teampass.net
19
 *
20
 * @license   https://spdx.org/licenses/GPL-3.0-only.html#licenseText GPL-3.0
21
 * ---
22
 *
23
 * @see       https://www.teampass.net
24
 */
25
class ItemController extends BaseController
26
{
27
28
29
    /**
30
     * Manage case inFolder - get items inside an array of folders
31
     *
32
     * @param array $userData
33
     */
34
    public function inFoldersAction(array $userData): void
35
    {
36
        $superGlobal = new protect\SuperGlobal\SuperGlobal();
37
        $strErrorDesc = '';
38
        $requestMethod = $superGlobal->get('REQUEST_METHOD', 'SERVER');
39
40
        // get parameters
41
        $arrQueryStringParams = $this->getQueryStringParams();
42
43
        if (strtoupper($requestMethod) === 'GET') {
44
            // define WHERE clause
45
            $sqlExtra = '';
46
            if (empty($userData['folders_list']) === false) {
47
                $userData['folders_list'] = explode(',', $userData['folders_list']);
48
            } else {
49
                $userData['folders_list'] = [];
50
            }
51
52
            // SQL where clause with folders list
53
            if (isset($arrQueryStringParams['folders']) === true) {
54
                // convert the folders to an array
55
                $arrQueryStringParams['folders'] = explode(',', str_replace( array('[',']') , ''  , $arrQueryStringParams['folders']));
56
57
                // ensure to only use the intersection
58
                $foldersList = implode(',', array_intersect($arrQueryStringParams['folders'], $userData['folders_list']));
59
60
                // build sql where clause
61
                if (!empty($foldersList)) {
62
                    // build sql where clause
63
                    $sqlExtra = ' WHERE id_tree IN ('.$foldersList.')';
64
                } else {
65
                    // Send error
66
                    $this->sendOutput(
67
                        json_encode(['error' => 'Folders are mandatory']),
68
                        ['Content-Type: application/json', 'HTTP/1.1 401 Expected parameters not provided']
69
                    );
70
                }
71
            } else {
72
                // Send error
73
                $this->sendOutput(
74
                    json_encode(['error' => 'Folders are mandatory']),
75
                    ['Content-Type: application/json', 'HTTP/1.1 401 Expected parameters not provided']
76
                );
77
            }
78
79
            // SQL LIMIT
80
            $intLimit = 0;
81
            if (isset($arrQueryStringParams['limit']) === true) {
82
                $intLimit = $arrQueryStringParams['limit'];
83
            }
84
85
            // send query
86
            try {
87
                $itemModel = new ItemModel();
88
89
                $arrItems = $itemModel->getItems($sqlExtra, $intLimit, $userData['private_key'], $userData['id']);
90
                if (!empty($arrItems)) {
91
                    $responseData = json_encode($arrItems);
92
                } else {
93
                    $strErrorDesc = 'No content for this label';
94
                    $strErrorHeader = 'HTTP/1.1 204 No Content';
95
                }
96
            } catch (Error $e) {
97
                $strErrorDesc = $e->getMessage().'. Something went wrong! Please contact support.';
98
                $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
99
            }
100
        } else {
101
            $strErrorDesc = 'Method not supported';
102
            $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
103
        }
104
105
        // send output
106
        if (empty($strErrorDesc) === true) {
107
            $this->sendOutput(
108
                $responseData,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $responseData does not seem to be defined for all execution paths leading up to this point.
Loading history...
109
                ['Content-Type: application/json', 'HTTP/1.1 200 OK']
110
            );
111
        } else {
112
            $this->sendOutput(
113
                json_encode(['error' => $strErrorDesc]), 
114
                ['Content-Type: application/json', $strErrorHeader]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $strErrorHeader does not seem to be defined for all execution paths leading up to this point.
Loading history...
115
            );
116
        }
117
    }
118
    //end InFoldersAction()
119
120
    /**
121
     * Manage case Add
122
     *
123
     * @param array $userData
124
     */
125
    public function addAction(array $userData)
126
    {
127
        $superGlobal = new protect\SuperGlobal\SuperGlobal();
128
        $strErrorDesc = '';
129
        $requestMethod = $superGlobal->get('REQUEST_METHOD', 'SERVER');
130
131
        if (strtoupper($requestMethod) === 'POST') {
132
            if (empty($userData['folders_list']) === false) {
133
                $userData['folders_list'] = explode(',', $userData['folders_list']);
134
            } else {
135
                $userData['folders_list'] = [];
136
            }
137
138
            $data = json_decode(file_get_contents("php://input"));
139
140
            if (in_array($data->folderId, $userData['folders_list'])) {
141
                // send query
142
                try {
143
                    $itemModel = new ItemModel();
144
145
                    $itemModel->addItem($data->folderId, $data->userName, $data->hostname, $data->password);
146
                } catch (Error $e) {
147
                    $strErrorDesc = $e->getMessage().'. Something went wrong! Please contact support.';
148
                    $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
149
                }
150
            } else {
151
                $strErrorDesc = 'Folders are mandatory';
152
                $strErrorHeader = 'HTTP/1.1 401 Expected parameters not provided';
153
            }
154
        } else {
155
            $strErrorDesc = 'Method not supported';
156
            $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
157
        }
158
159
        // send output
160
        if (empty($strErrorDesc) === true) {
161
            $this->sendOutput(
162
                "",
163
                ['Content-Type: application/json', 'HTTP/1.1 201 Created']
164
            );
165
166
            //$this->sendOutput(['HTTP/1.1 201 Created']);
167
        } else {
168
            $this->sendOutput(
169
                json_encode(['error' => $strErrorDesc]),
170
                ['Content-Type: application/json', $strErrorHeader]
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $strErrorHeader does not seem to be defined for all execution paths leading up to this point.
Loading history...
171
            );
172
        }
173
    }
174
    //end addAction()
175
176
177
    /**
178
     * Manage case get - get an item
179
     *
180
     * @param array $userData
181
     */
182
    public function getAction(array $userData): void
183
    {
184
        $superGlobal = new protect\SuperGlobal\SuperGlobal();
185
        $strErrorDesc = '';
186
        $sqlExtra = '';
187
        $responseData = '';
188
        $strErrorHeader = '';
189
        $requestMethod = $superGlobal->get('REQUEST_METHOD', 'SERVER');
190
        $sql_constraint = ' AND (i.id_tree IN ('.$userData['folders_list'].') OR i.id IN ('.$userData['restricted_items_list'].'))';
191
192
        // get parameters
193
        $arrQueryStringParams = $this->getQueryStringParams();
194
195
        if (strtoupper($requestMethod) === 'GET') {
196
            // SQL where clause with item id
197
            if (isset($arrQueryStringParams['id']) === true) {
198
                // build sql where clause by ID
199
                $sqlExtra = ' WHERE i.id = '.$arrQueryStringParams['id'] . $sql_constraint;
200
            } else if (isset($arrQueryStringParams['label']) === true) {
201
                // build sql where clause by LABEL
202
                $sqlExtra = ' WHERE i.label '.(isset($arrQueryStringParams['like']) === true && (int) $arrQueryStringParams['like'] === 1 ? ' LIKE '.$arrQueryStringParams['label'] : ' = '.$arrQueryStringParams['label']) . $sql_constraint;
203
            } else if (isset($arrQueryStringParams['description']) === true) {
204
                // build sql where clause by LABEL
205
                $sqlExtra = ' WHERE i.description '.(isset($arrQueryStringParams['like']) === true && (int) $arrQueryStringParams['like'] === 1 ? ' LIKE '.$arrQueryStringParams['description'] : ' = '.$arrQueryStringParams['description']).$sql_constraint;
206
            } else {
207
                // Send error
208
                $this->sendOutput(
209
                    json_encode(['error' => 'Item id, label or description is mandatory']),
210
                    ['Content-Type: application/json', 'HTTP/1.1 401 Expected parameters not provided']
211
                );
212
            }
213
214
            // send query
215
            try {
216
                $itemModel = new ItemModel();
217
218
                $arrItems = $itemModel->getItems($sqlExtra, 0, $userData['private_key'], $userData['id']);
219
                $responseData = json_encode($arrItems);
220
            } catch (Error $e) {
221
                $strErrorDesc = $e->getMessage().'. Something went wrong! Please contact support.';
222
                $strErrorHeader = 'HTTP/1.1 500 Internal Server Error';
223
            }
224
        } else {
225
            $strErrorDesc = 'Method not supported';
226
            $strErrorHeader = 'HTTP/1.1 422 Unprocessable Entity';
227
        }
228
229
        // send output
230
        if (empty($strErrorDesc) === true) {
231
            $this->sendOutput(
232
                $responseData,
233
                ['Content-Type: application/json', 'HTTP/1.1 200 OK']
234
            );
235
        } else {
236
            $this->sendOutput(
237
                json_encode(['error' => $strErrorDesc]), 
238
                ['Content-Type: application/json', $strErrorHeader]
239
            );
240
        }
241
    }
242
    //end getAction() 
243
}