Passed
Push — EXTRACT_CLASSES ( 231cec...0382f2 )
by Rafael
65:54 queued 05:18
created

Boms   F

Complexity

Total Complexity 85

Size/Duplication

Total Lines 568
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 252
dl 0
loc 568
rs 2
c 0
b 0
f 0
wmc 85

13 Methods

Rating   Name   Duplication   Size   Complexity  
B put() 0 41 11
A getLines() 0 20 5
A get() 0 16 4
B deleteLine() 0 37 8
A delete() 0 22 5
A postLine() 0 33 5
F index() 0 72 20
A __construct() 0 6 1
A _validate() 0 13 5
A putLine() 0 34 5
A post() 0 24 5
A checkRefNumbering() 0 14 6
B _cleanObjectDatas() 0 61 5

How to fix   Complexity   

Complex Class

Complex classes like Boms often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Boms, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2015       Jean-François Ferry         <[email protected]>
4
 * Copyright (C) 2019       Maxime Kohlhaas             <[email protected]>
5
 * Copyright (C) 2020-2024  Frédéric France		        <[email protected]>
6
 * Copyright (C) 2022		Christian Humpel		    <[email protected]>
7
 * Copyright (C) 2024       Rafael San José             <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 */
22
23
namespace Dolibarr\Code\Bom\Api;
24
25
use Dolibarr\Core\Base\DolibarrApi;
26
use Luracast\Restler\RestException;
27
28
require_once constant('DOL_DOCUMENT_ROOT') . '/bom/class/bom.class.php';
29
30
31
/**
32
 * \file    htdocs/bom/class/api_boms.class.php
33
 * \ingroup bom
34
 * \brief   File for API management of BOM.
35
 */
36
37
/**
38
 * API class for BOM
39
 *
40
 * @access protected
41
 * @class  DolibarrApiAccess {@requires user,external}
42
 */
43
class Boms extends DolibarrApi
44
{
45
    /**
46
     * @var BOM $bom {@type BOM}
47
     */
48
    public $bom;
49
50
    /**
51
     * Constructor
52
     */
53
    public function __construct()
54
    {
55
        global $db;
56
57
        $this->db = $db;
58
        $this->bom = new BOM($this->db);
59
    }
60
61
    /**
62
     * Get properties of a bom object
63
     *
64
     * Return an array with bom information
65
     *
66
     * @param   int     $id             ID of bom
67
     * @return  Object                  Object with cleaned properties
68
     *
69
     * @url GET {id}
70
     *
71
     * @throws  RestException   403     Access denied
72
     * @throws  RestException   404     BOM not found
73
     */
74
    public function get($id)
75
    {
76
        if (!DolibarrApiAccess::$user->hasRight('bom', 'read')) {
77
            throw new RestException(403);
78
        }
79
80
        $result = $this->bom->fetch($id);
81
        if (!$result) {
82
            throw new RestException(404, 'BOM not found');
83
        }
84
85
        if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
86
            throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
87
        }
88
89
        return $this->_cleanObjectDatas($this->bom);
90
    }
91
92
93
    /**
94
     * List boms
95
     *
96
     * Get a list of boms
97
     *
98
     * @param string           $sortfield           Sort field
99
     * @param string           $sortorder           Sort order
100
     * @param int              $limit               Limit for list
101
     * @param int              $page                Page number
102
     * @param string           $sqlfilters          Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
103
     * @param string           $properties          Restrict the data returned to these properties. Ignored if empty. Comma separated list of properties names
104
     * @return  array                               Array of order objects
105
     *
106
     * @throws  RestException   400     Bad sqlfilters
107
     * @throws  RestException   403     Access denied
108
     * @throws  RestException   503     Error retrieving list of boms
109
     */
110
    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
111
    {
112
        if (!DolibarrApiAccess::$user->hasRight('bom', 'read')) {
113
            throw new RestException(403);
114
        }
115
116
        $obj_ret = array();
117
        $tmpobject = new BOM($this->db);
118
119
        $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : '';
120
121
        $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
122
123
        // If the internal user must only see his customers, force searching by him
124
        $search_sale = 0;
125
        if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
126
            $search_sale = DolibarrApiAccess::$user->id;
127
        }
128
129
        $sql = "SELECT t.rowid";
130
        $sql .= " FROM " . MAIN_DB_PREFIX . $tmpobject->table_element . " AS t";
131
        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $tmpobject->table_element . "_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
132
        $sql .= " WHERE 1 = 1";
133
        if ($tmpobject->ismultientitymanaged) {
134
            $sql .= ' AND t.entity IN (' . getEntity($tmpobject->element) . ')';
135
        }
136
        if ($restrictonsocid && $socid) {
137
            $sql .= " AND t.fk_soc = " . ((int) $socid);
138
        }
139
        // Search on sale representative
140
        if ($search_sale && $search_sale != '-1') {
141
            if ($search_sale == -2) {
142
                $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
143
            } elseif ($search_sale > 0) {
144
                $sql .= " AND EXISTS (SELECT sc.fk_soc FROM " . MAIN_DB_PREFIX . "societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = " . ((int) $search_sale) . ")";
145
            }
146
        }
147
        if ($sqlfilters) {
148
            $errormessage = '';
149
            $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
150
            if ($errormessage) {
151
                throw new RestException(400, 'Error when validating parameter sqlfilters -> ' . $errormessage);
152
            }
153
        }
154
155
        $sql .= $this->db->order($sortfield, $sortorder);
156
        if ($limit) {
157
            if ($page < 0) {
158
                $page = 0;
159
            }
160
            $offset = $limit * $page;
161
162
            $sql .= $this->db->plimit($limit + 1, $offset);
163
        }
164
165
        $result = $this->db->query($sql);
166
        if ($result) {
167
            $num = $this->db->num_rows($result);
168
            $i = 0;
169
            while ($i < $num) {
170
                $obj = $this->db->fetch_object($result);
171
                $bom_static = new BOM($this->db);
172
                if ($bom_static->fetch($obj->rowid)) {
173
                    $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($bom_static), $properties);
174
                }
175
                $i++;
176
            }
177
        } else {
178
            throw new RestException(503, 'Error when retrieve bom list');
179
        }
180
181
        return $obj_ret;
182
    }
183
184
    /**
185
     * Create bom object
186
     *
187
     * @param array $request_data   Request datas
188
     * @return int                  ID of bom
189
     *
190
     * @throws  RestException   403     Access denied
191
     * @throws  RestException   500     Error retrieving list of boms
192
     */
193
    public function post($request_data = null)
194
    {
195
        if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
196
            throw new RestException(403);
197
        }
198
        // Check mandatory fields
199
        $result = $this->_validate($request_data);
200
201
        foreach ($request_data as $field => $value) {
202
            if ($field === 'caller') {
203
                // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
204
                $this->bom->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
205
                continue;
206
            }
207
208
            $this->bom->$field = $this->_checkValForAPI($field, $value, $this->bom);
209
        }
210
211
        $this->checkRefNumbering();
212
213
        if (!$this->bom->create(DolibarrApiAccess::$user)) {
214
            throw new RestException(500, "Error creating BOM", array_merge(array($this->bom->error), $this->bom->errors));
215
        }
216
        return $this->bom->id;
217
    }
218
219
    /**
220
     * Update bom
221
     *
222
     * @param   int         $id             Id of bom to update
223
     * @param   array       $request_data   Datas
224
     * @return  Object                      Object after update
225
     *
226
     * @throws  RestException   403     Access denied
227
     * @throws  RestException   404     BOM not found
228
     * @throws  RestException   500     Error updating bom
229
     */
230
    public function put($id, $request_data = null)
231
    {
232
        if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
233
            throw new RestException(403);
234
        }
235
236
        $result = $this->bom->fetch($id);
237
        if (!$result) {
238
            throw new RestException(404, 'BOM not found');
239
        }
240
241
        if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
242
            throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
243
        }
244
245
        foreach ($request_data as $field => $value) {
246
            if ($field == 'id') {
247
                continue;
248
            }
249
            if ($field === 'caller') {
250
                // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
251
                $this->bom->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
252
                continue;
253
            }
254
255
            if ($field == 'array_options' && is_array($value)) {
256
                foreach ($value as $index => $val) {
257
                    $this->bom->array_options[$index] = $this->_checkValForAPI('extrafields', $val, $this->bom);
258
                }
259
                continue;
260
            }
261
262
            $this->bom->$field = $this->_checkValForAPI($field, $value, $this->bom);
263
        }
264
265
        $this->checkRefNumbering();
266
267
        if ($this->bom->update(DolibarrApiAccess::$user) > 0) {
268
            return $this->get($id);
269
        } else {
270
            throw new RestException(500, $this->bom->error);
271
        }
272
    }
273
274
    /**
275
     * Delete bom
276
     *
277
     * @param   int     $id   BOM ID
278
     * @return  array
279
     *
280
     * @throws  RestException   403     Access denied
281
     * @throws  RestException   404     BOM not found
282
     * @throws  RestException   500     Error deleting bom
283
     */
284
    public function delete($id)
285
    {
286
        if (!DolibarrApiAccess::$user->hasRight('bom', 'delete')) {
287
            throw new RestException(403);
288
        }
289
        $result = $this->bom->fetch($id);
290
        if (!$result) {
291
            throw new RestException(404, 'BOM not found');
292
        }
293
294
        if (!DolibarrApi::_checkAccessToResource('bom', $this->bom->id, 'bom_bom')) {
295
            throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
296
        }
297
298
        if (!$this->bom->delete(DolibarrApiAccess::$user)) {
299
            throw new RestException(500, 'Error when deleting BOM : ' . $this->bom->error);
300
        }
301
302
        return array(
303
            'success' => array(
304
                'code' => 200,
305
                'message' => 'BOM deleted'
306
            )
307
        );
308
    }
309
310
    /**
311
     * Get lines of an BOM
312
     *
313
     * @param int   $id             Id of BOM
314
     *
315
     * @url GET {id}/lines
316
     *
317
     * @return array
318
     *
319
     * @throws  RestException   403     Access denied
320
     * @throws  RestException   404     BOM not found
321
     */
322
    public function getLines($id)
323
    {
324
        if (!DolibarrApiAccess::$user->hasRight('bom', 'read')) {
325
            throw new RestException(403);
326
        }
327
328
        $result = $this->bom->fetch($id);
329
        if (!$result) {
330
            throw new RestException(404, 'BOM not found');
331
        }
332
333
        if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
334
            throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
335
        }
336
        $this->bom->getLinesArray();
337
        $result = array();
338
        foreach ($this->bom->lines as $line) {
339
            array_push($result, $this->_cleanObjectDatas($line));
340
        }
341
        return $result;
342
    }
343
344
    /**
345
     * Add a line to given BOM
346
     *
347
     * @param int   $id             Id of BOM to update
348
     * @param array $request_data   BOMLine data
349
     *
350
     * @url POST {id}/lines
351
     *
352
     * @return int
353
     *
354
     * @throws  RestException   403     Access denied
355
     * @throws  RestException   404     BOM not found
356
     * @throws  RestException   500     Error adding bom line
357
     */
358
    public function postLine($id, $request_data = null)
359
    {
360
        if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
361
            throw new RestException(403);
362
        }
363
364
        $result = $this->bom->fetch($id);
365
        if (!$result) {
366
            throw new RestException(404, 'BOM not found');
367
        }
368
369
        if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
370
            throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
371
        }
372
373
        $request_data = (object) $request_data;
374
375
        $updateRes = $this->bom->addLine(
376
            $request_data->fk_product,
377
            $request_data->qty,
378
            $request_data->qty_frozen,
379
            $request_data->disable_stock_change,
380
            $request_data->efficiency,
381
            $request_data->position,
382
            $request_data->fk_bom_child,
383
            $request_data->import_key,
384
            $request_data->fk_unit
385
        );
386
387
        if ($updateRes > 0) {
388
            return $updateRes;
389
        } else {
390
            throw new RestException(500, $this->bom->error);
391
        }
392
    }
393
394
    /**
395
     * Update a line to given BOM
396
     *
397
     * @param int   $id             Id of BOM to update
398
     * @param int   $lineid         Id of line to update
399
     * @param array $request_data   BOMLine data
400
     *
401
     * @url PUT {id}/lines/{lineid}
402
     *
403
     * @return object|bool
404
     *
405
     * @throws  RestException   403     Access denied
406
     * @throws  RestException   404     BOM not found
407
     */
408
    public function putLine($id, $lineid, $request_data = null)
409
    {
410
        if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
411
            throw new RestException(403);
412
        }
413
414
        $result = $this->bom->fetch($id);
415
        if (!$result) {
416
            throw new RestException(404, 'BOM not found');
417
        }
418
419
        if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
420
            throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
421
        }
422
423
        $request_data = (object) $request_data;
424
425
        $updateRes = $this->bom->updateLine(
426
            $lineid,
427
            $request_data->qty,
428
            $request_data->qty_frozen,
429
            $request_data->disable_stock_change,
430
            $request_data->efficiency,
431
            $request_data->position,
432
            $request_data->import_key,
433
            $request_data->fk_unit
434
        );
435
436
        if ($updateRes > 0) {
437
            $result = $this->get($id);
438
            unset($result->line);
439
            return $this->_cleanObjectDatas($result);
440
        }
441
        return false;
442
    }
443
444
    /**
445
     * Delete a line to given BOM
446
     *
447
     *
448
     * @param int   $id             Id of BOM to update
449
     * @param int   $lineid         Id of line to delete
450
     *
451
     * @url DELETE {id}/lines/{lineid}
452
     *
453
     * @return array
454
     *
455
     * @throws  RestException   403     Access denied
456
     * @throws  RestException   404     BOM not found
457
     * @throws  RestException   500     Error deleting bom line
458
     */
459
    public function deleteLine($id, $lineid)
460
    {
461
        if (!DolibarrApiAccess::$user->hasRight('bom', 'write')) {
462
            throw new RestException(403);
463
        }
464
465
        $result = $this->bom->fetch($id);
466
        if (!$result) {
467
            throw new RestException(404, 'BOM not found');
468
        }
469
470
        if (!DolibarrApi::_checkAccessToResource('bom_bom', $this->bom->id)) {
471
            throw new RestException(403, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
472
        }
473
474
        //Check the rowid is a line of current bom object
475
        $lineIdIsFromObject = false;
476
        foreach ($this->bom->lines as $bl) {
477
            if ($bl->id == $lineid) {
478
                $lineIdIsFromObject = true;
479
                break;
480
            }
481
        }
482
        if (!$lineIdIsFromObject) {
483
            throw new RestException(500, 'Line to delete (rowid: ' . $lineid . ') is not a line of BOM (id: ' . $this->bom->id . ')');
484
        }
485
486
        $updateRes = $this->bom->deleteLine(DolibarrApiAccess::$user, $lineid);
487
        if ($updateRes > 0) {
488
            return array(
489
                'success' => array(
490
                    'code' => 200,
491
                    'message' => 'line ' . $lineid . ' deleted'
492
                )
493
            );
494
        } else {
495
            throw new RestException(500, $this->bom->error);
496
        }
497
    }
498
499
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
500
    /**
501
     * Clean sensible object datas
502
     *
503
     * @param   Object  $object     Object to clean
504
     * @return  Object              Object with cleaned properties
505
     */
506
    protected function _cleanObjectDatas($object)
507
    {
508
		// phpcs:enable
509
        $object = parent::_cleanObjectDatas($object);
510
511
        unset($object->rowid);
512
        unset($object->canvas);
513
514
        unset($object->name);
515
        unset($object->lastname);
516
        unset($object->firstname);
517
        unset($object->civility_id);
518
        unset($object->statut);
519
        unset($object->state);
520
        unset($object->state_id);
521
        unset($object->state_code);
522
        unset($object->region);
523
        unset($object->region_code);
524
        unset($object->country);
525
        unset($object->country_id);
526
        unset($object->country_code);
527
        unset($object->barcode_type);
528
        unset($object->barcode_type_code);
529
        unset($object->barcode_type_label);
530
        unset($object->barcode_type_coder);
531
        unset($object->total_ht);
532
        unset($object->total_tva);
533
        unset($object->total_localtax1);
534
        unset($object->total_localtax2);
535
        unset($object->total_ttc);
536
        unset($object->fk_account);
537
        unset($object->comments);
538
        unset($object->note);
539
        unset($object->mode_reglement_id);
540
        unset($object->cond_reglement_id);
541
        unset($object->cond_reglement);
542
        unset($object->shipping_method_id);
543
        unset($object->fk_incoterms);
544
        unset($object->label_incoterms);
545
        unset($object->location_incoterms);
546
        unset($object->multicurrency_code);
547
        unset($object->multicurrency_tx);
548
        unset($object->multicurrency_total_ht);
549
        unset($object->multicurrency_total_ttc);
550
        unset($object->multicurrency_total_tva);
551
        unset($object->multicurrency_total_localtax1);
552
        unset($object->multicurrency_total_localtax2);
553
554
555
        // If object has lines, remove $db property
556
        if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
557
            $nboflines = count($object->lines);
558
            for ($i = 0; $i < $nboflines; $i++) {
559
                $this->_cleanObjectDatas($object->lines[$i]);
560
561
                unset($object->lines[$i]->lines);
562
                unset($object->lines[$i]->note);
563
            }
564
        }
565
566
        return $object;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $object also could return the type object which is incompatible with the documented return type object.
Loading history...
567
    }
568
569
    /**
570
     * Validate fields before create or update object
571
     *
572
     * @param   array       $data   Array of data to validate
573
     * @return  array
574
     *
575
     * @throws  RestException
576
     */
577
    private function _validate($data)
578
    {
579
        $myobject = array();
580
        foreach ($this->bom->fields as $field => $propfield) {
581
            if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) {
582
                continue; // Not a mandatory field
583
            }
584
            if (!isset($data[$field])) {
585
                throw new RestException(400, "$field field missing");
586
            }
587
            $myobject[$field] = $data[$field];
588
        }
589
        return $myobject;
590
    }
591
592
    /**
593
     * Validate the ref field and get the next Number if it's necessary.
594
     *
595
     * @return void
596
     */
597
    private function checkRefNumbering()
598
    {
599
        $ref = substr($this->bom->ref, 1, 4);
600
        if ($this->bom->status > 0 && $ref == 'PROV') {
601
            throw new RestException(400, "Wrong naming scheme '(PROV%)' is only allowed on 'DRAFT' status. For automatic increment use 'auto' on the 'ref' field.");
602
        }
603
604
        if (strtolower($this->bom->ref) == 'auto') {
605
            if (empty($this->bom->id) && $this->bom->status == 0) {
606
                $this->bom->ref = ''; // 'ref' will auto incremented with '(PROV' + newID + ')'
607
            } else {
608
                $this->bom->fetch_product();
609
                $numref = $this->bom->getNextNumRef($this->bom->product);
610
                $this->bom->ref = $numref;
611
            }
612
        }
613
    }
614
}
615