Passed
Branch develop (01f96b)
by
unknown
30:45
created

Members::index()   F

Complexity

Conditions 14
Paths 345

Size

Total Lines 71
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 14
eloc 41
c 2
b 0
f 0
nc 345
nop 7
dl 0
loc 71
rs 3.6208

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
/* Copyright (C) 2016	Xebax Christy	<[email protected]>
3
 * Copyright (C) 2017	Regis Houssin	<[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
 */
18
19
use Luracast\Restler\RestException;
20
21
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
22
require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
23
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
24
25
/**
26
 * API class for members
27
 *
28
 * @access protected
29
 * @class  DolibarrApiAccess {@requires user,external}
30
 */
31
class Members extends DolibarrApi
32
{
33
    /**
34
     * @var array   $FIELDS     Mandatory fields, checked when create and update object
35
     */
36
    static $FIELDS = array(
37
        'morphy',
38
        'typeid'
39
    );
40
41
    /**
42
     * Constructor
43
     */
44
    public function __construct()
45
    {
46
        global $db, $conf;
47
        $this->db = $db;
48
    }
49
50
    /**
51
     * Get properties of a member object
52
     *
53
     * Return an array with member informations
54
     *
55
     * @param     int     $id ID of member
56
     * @return    array|mixed data without useless information
57
     *
58
     * @throws    RestException
59
     */
60
    public function get($id)
61
    {
62
        if (!DolibarrApiAccess::$user->rights->adherent->lire) {
63
            throw new RestException(401);
64
        }
65
66
        $member = new Adherent($this->db);
67
        $result = $member->fetch($id);
68
        if (!$result) {
69
            throw new RestException(404, 'member not found');
70
        }
71
72
        if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
73
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
74
        }
75
76
        return $this->_cleanObjectDatas($member);
77
    }
78
79
    /**
80
     * List members
81
     *
82
     * Get a list of members
83
     *
84
     * @param string    $sortfield  Sort field
85
     * @param string    $sortorder  Sort order
86
     * @param int       $limit      Limit for list
87
     * @param int       $page       Page number
88
     * @param string    $typeid     ID of the type of member
89
	 * @param  int    $category   Use this param to filter list by category
90
     * @param string    $sqlfilters Other criteria to filter answers separated by a comma.
91
     *                              Example: "(t.ref:like:'SO-%') and ((t.date_creation:<:'20160101') or (t.nature:is:NULL))"
92
     * @return array                Array of member objects
93
     *
94
     * @throws RestException
95
     */
96
    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $typeid = '', $category = 0, $sqlfilters = '')
97
    {
98
        global $db, $conf;
99
100
        $obj_ret = array();
101
102
        if (!DolibarrApiAccess::$user->rights->adherent->lire) {
103
            throw new RestException(401);
104
        }
105
106
        $sql = "SELECT t.rowid";
107
        $sql .= " FROM ".MAIN_DB_PREFIX."adherent as t";
108
    	if ($category > 0) {
109
			$sql .= ", ".MAIN_DB_PREFIX."categorie_member as c";
110
    	}
111
        $sql .= ' WHERE t.entity IN ('.getEntity('adherent').')';
112
        if (!empty($typeid))
113
        {
114
            $sql .= ' AND t.fk_adherent_type='.$typeid;
115
        }
116
    	// Select members of given category
117
    	if ($category > 0) {
118
			$sql .= " AND c.fk_categorie = ".$db->escape($category);
119
			$sql .= " AND c.fk_member = t.rowid ";
120
    	}
121
        // Add sql filters
122
        if ($sqlfilters)
123
        {
124
            if (!DolibarrApi::_checkFilters($sqlfilters))
125
            {
126
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
127
            }
128
	        $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
129
            $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
130
        }
131
132
        $sql .= $db->order($sortfield, $sortorder);
133
        if ($limit) {
134
            if ($page < 0)
135
            {
136
                $page = 0;
137
            }
138
            $offset = $limit * $page;
139
140
            $sql .= $db->plimit($limit + 1, $offset);
141
        }
142
143
        $result = $db->query($sql);
144
        if ($result)
145
        {
146
            $i = 0;
147
            $num = $db->num_rows($result);
148
            $min = min($num, ($limit <= 0 ? $num : $limit));
149
            while ($i < $min)
150
            {
151
            	$obj = $db->fetch_object($result);
152
                $member = new Adherent($this->db);
153
                if ($member->fetch($obj->rowid)) {
154
                    $obj_ret[] = $this->_cleanObjectDatas($member);
155
                }
156
                $i++;
157
            }
158
        }
159
        else {
160
            throw new RestException(503, 'Error when retrieve member list : '.$db->lasterror());
161
        }
162
        if (!count($obj_ret)) {
163
            throw new RestException(404, 'No member found');
164
        }
165
166
        return $obj_ret;
167
    }
168
169
    /**
170
     * Create member object
171
     *
172
     * @param array $request_data   Request data
173
     * @return int  ID of member
174
     */
175
    public function post($request_data = null)
176
    {
177
        if (!DolibarrApiAccess::$user->rights->adherent->creer) {
178
            throw new RestException(401);
179
        }
180
        // Check mandatory fields
181
        $result = $this->_validate($request_data);
182
183
        $member = new Adherent($this->db);
184
        foreach ($request_data as $field => $value) {
185
            $member->$field = $value;
186
        }
187
        if ($member->create(DolibarrApiAccess::$user) < 0) {
188
            throw new RestException(500, 'Error creating member', array_merge(array($member->error), $member->errors));
189
        }
190
        return $member->id;
191
    }
192
193
    /**
194
     * Update member
195
     *
196
     * @param int   $id             ID of member to update
197
     * @param array $request_data   Datas
198
     * @return int
199
     */
200
    public function put($id, $request_data = null)
201
    {
202
        if (!DolibarrApiAccess::$user->rights->adherent->creer) {
203
            throw new RestException(401);
204
        }
205
206
        $member = new Adherent($this->db);
207
        $result = $member->fetch($id);
208
        if (!$result) {
209
            throw new RestException(404, 'member not found');
210
        }
211
212
        if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
213
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
214
        }
215
216
        foreach ($request_data as $field => $value) {
217
            if ($field == 'id') continue;
218
            // Process the status separately because it must be updated using
219
            // the validate() and resiliate() methods of the class Adherent.
220
            if ($field == 'statut') {
221
                if ($value == '0') {
222
                    $result = $member->resiliate(DolibarrApiAccess::$user);
223
                    if ($result < 0) {
224
                        throw new RestException(500, 'Error when resiliating member: '.$member->error);
225
                    }
226
                } elseif ($value == '1') {
227
                    $result = $member->validate(DolibarrApiAccess::$user);
228
                    if ($result < 0) {
229
                        throw new RestException(500, 'Error when validating member: '.$member->error);
230
                    }
231
                }
232
            } else {
233
                $member->$field = $value;
234
            }
235
        }
236
237
        // If there is no error, update() returns the number of affected rows
238
        // so if the update is a no op, the return value is zero.
239
        if ($member->update(DolibarrApiAccess::$user) >= 0)
240
        {
241
            return $this->get($id);
242
        }
243
        else
244
        {
245
        	throw new RestException(500, $member->error);
246
        }
247
    }
248
249
    /**
250
     * Delete member
251
     *
252
     * @param int $id   member ID
253
     * @return array
254
     */
255
    public function delete($id)
256
    {
257
        if (!DolibarrApiAccess::$user->rights->adherent->supprimer) {
258
            throw new RestException(401);
259
        }
260
        $member = new Adherent($this->db);
261
        $result = $member->fetch($id);
262
        if (!$result) {
263
            throw new RestException(404, 'member not found');
264
        }
265
266
        if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
267
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
268
        }
269
270
        if (!$member->delete($member->id, DolibarrApiAccess::$user)) {
271
            throw new RestException(401, 'error when deleting member');
272
        }
273
274
        return array(
275
            'success' => array(
276
                'code' => 200,
277
                'message' => 'member deleted'
278
            )
279
        );
280
    }
281
282
    /**
283
     * Validate fields before creating an object
284
     *
285
     * @param array|null    $data   Data to validate
286
     * @return array
287
     *
288
     * @throws RestException
289
     */
290
    private function _validate($data)
291
    {
292
        $member = array();
293
        foreach (Members::$FIELDS as $field) {
294
            if (!isset($data[$field]))
295
                throw new RestException(400, "$field field missing");
296
            $member[$field] = $data[$field];
297
        }
298
        return $member;
299
    }
300
301
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
302
    /**
303
     * Clean sensible object datas
304
     *
305
     * @param   object  $object    Object to clean
306
     * @return    array    Array of cleaned object properties
307
     */
308
    protected function _cleanObjectDatas($object)
309
    {
310
        // phpcs:enable
311
        $object = parent::_cleanObjectDatas($object);
312
313
        // Remove the subscriptions because they are handled as a subresource.
314
        unset($object->subscriptions);
315
        unset($object->fk_incoterms);
316
        unset($object->label_incoterms);
317
        unset($object->location_incoterms);
318
        unset($object->fk_delivery_address);
319
        unset($object->shipping_method_id);
320
321
        unset($object->total_ht);
322
        unset($object->total_ttc);
323
        unset($object->total_tva);
324
        unset($object->total_localtax1);
325
        unset($object->total_localtax2);
326
327
        return $object;
328
    }
329
330
    /**
331
     * List subscriptions of a member
332
     *
333
     * Get a list of subscriptions
334
     *
335
     * @param int $id ID of member
336
     * @return array Array of subscription objects
337
     *
338
     * @throws RestException
339
     *
340
     * @url GET {id}/subscriptions
341
     */
342
    public function getSubscriptions($id)
343
    {
344
        $obj_ret = array();
345
346
        if (!DolibarrApiAccess::$user->rights->adherent->cotisation->lire) {
347
            throw new RestException(401);
348
        }
349
350
        $member = new Adherent($this->db);
351
        $result = $member->fetch($id);
352
        if (!$result) {
353
            throw new RestException(404, 'member not found');
354
        }
355
356
        $obj_ret = array();
357
        foreach ($member->subscriptions as $subscription) {
358
            $obj_ret[] = $this->_cleanObjectDatas($subscription);
359
        }
360
        return $obj_ret;
361
    }
362
363
    /**
364
     * Add a subscription for a member
365
     *
366
     * @param int $id               ID of member
367
     * @param int $start_date       Start date {@from body} {@type timestamp}
368
     * @param int $end_date         End date {@from body} {@type timestamp}
369
     * @param float $amount         Amount (may be 0) {@from body}
370
     * @param string $label         Label {@from body}
371
     * @return int  ID of subscription
372
     *
373
     * @url POST {id}/subscriptions
374
     */
375
    public function createSubscription($id, $start_date, $end_date, $amount, $label = '')
376
    {
377
        if (!DolibarrApiAccess::$user->rights->adherent->cotisation->creer) {
378
            throw new RestException(401);
379
        }
380
381
        $member = new Adherent($this->db);
382
        $result = $member->fetch($id);
383
        if (!$result) {
384
            throw new RestException(404, 'member not found');
385
        }
386
387
        return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date);
388
    }
389
390
    /**
391
     * Get categories for a member
392
     *
393
     * @param int		$id         ID of member
394
     * @param string		$sortfield	Sort field
395
     * @param string		$sortorder	Sort order
396
     * @param int		$limit		Limit for list
397
     * @param int		$page		Page number
398
     *
399
     * @return mixed
400
     *
401
     * @url GET {id}/categories
402
     */
403
	public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
404
	{
405
		if (!DolibarrApiAccess::$user->rights->categorie->lire) {
406
			throw new RestException(401);
407
		}
408
409
		$categories = new Categorie($this->db);
410
411
		$result = $categories->getListForItem($id, 'member', $sortfield, $sortorder, $limit, $page);
412
413
		if (empty($result)) {
414
			throw new RestException(404, 'No category found');
415
		}
416
417
		if ($result < 0) {
418
			throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
419
		}
420
421
		return $result;
422
	}
423
}
424