Completed
Branch develop (45fc57)
by
unknown
27:54
created

MyModuleApi::put()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 7
nop 2
dl 0
loc 24
rs 8.5125
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2015   Jean-François Ferry     <[email protected]>
3
 * Copyright (C) ---Put here your own copyright and developer email---
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 <http://www.gnu.org/licenses/>.
17
 */
18
19
use Luracast\Restler\RestException;
20
21
dol_include_once('/mymodule/class/myobject.class.php');
22
23
24
25
/**
26
 * \file    htdocs/modulebuilder/template/class/api_mymodule.class.php
27
 * \ingroup mymodule
28
 * \brief   File for API management of myobject.
29
 */
30
31
/**
32
 * API class for mymodule myobject
33
 *
34
 * @smart-auto-routing false
35
 * @access protected
36
 * @class  DolibarrApiAccess {@requires user,external}
37
 */
38
class MyModuleApi extends DolibarrApi
39
{
40
    /**
41
     * @var array   $FIELDS     Mandatory fields, checked when create and update object
42
     */
43
    static $FIELDS = array(
44
        'name'
45
    );
46
47
48
    /**
49
     * @var MyObject $myobject {@type MyObject}
50
     */
51
    public $myobject;
52
53
    /**
54
     * Constructor
55
     *
56
     * @url     GET /
57
     *
58
     */
59
    function __construct()
60
    {
61
		global $db, $conf;
62
		$this->db = $db;
63
        $this->myobject = new MyObject($this->db);
64
    }
65
66
    /**
67
     * Get properties of a myobject object
68
     *
69
     * Return an array with myobject informations
70
     *
71
     * @param 	int 	$id ID of myobject
72
     * @return 	array|mixed data without useless information
73
	 *
74
     * @url	GET myobjects/{id}
75
     * @throws 	RestException
76
     */
77
    function get($id)
78
    {
79
		if(! DolibarrApiAccess::$user->rights->myobject->read) {
80
			throw new RestException(401);
81
		}
82
83
        $result = $this->myobject->fetch($id);
84
        if( ! $result ) {
85
            throw new RestException(404, 'MyObject not found');
86
        }
87
88
		if( ! DolibarrApi::_checkAccessToResource('myobject',$this->myobject->id)) {
89
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
90
		}
91
92
		return $this->_cleanObjectDatas($this->myobject);
93
    }
94
95
96
    /**
97
     * List myobjects
98
     *
99
     * Get a list of myobjects
100
     *
101
     * @param string	       $sortfield	        Sort field
102
     * @param string	       $sortorder	        Sort order
103
     * @param int		       $limit		        Limit for list
104
     * @param int		       $page		        Page number
105
     * @param string           $sqlfilters          Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
106
     * @return  array                               Array of order objects
107
     *
108
     * @throws RestException
109
     *
110
     * @url	GET /myobjects/
111
     */
112
    function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') {
113
        global $db, $conf;
114
115
        $obj_ret = array();
116
117
        $socid = DolibarrApiAccess::$user->societe_id ? DolibarrApiAccess::$user->societe_id : '';
118
119
        // If the internal user must only see his customers, force searching by him
120
        if (! DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id;
121
122
        $sql = "SELECT s.rowid";
123
        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects)
0 ignored issues
show
Bug introduced by
The variable $search_sale does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
124
        $sql.= " FROM ".MAIN_DB_PREFIX."myobject as s";
125
126
        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale
127
        $sql.= ", ".MAIN_DB_PREFIX."c_stcomm as st";
128
        $sql.= " WHERE s.fk_stcomm = st.id";
129
130
		// Example of use $mode
131
        //if ($mode == 1) $sql.= " AND s.client IN (1, 3)";
132
        //if ($mode == 2) $sql.= " AND s.client IN (2, 3)";
133
134
        $sql.= ' AND s.entity IN ('.getEntity('myobject').')';
135
        if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql.= " AND s.fk_soc = sc.fk_soc";
136
        if ($socid) $sql.= " AND s.fk_soc = ".$socid;
137
        if ($search_sale > 0) $sql.= " AND s.rowid = sc.fk_soc";		// Join for the needed table to filter by sale
138
        // Insert sale filter
139
        if ($search_sale > 0)
140
        {
141
            $sql .= " AND sc.fk_user = ".$search_sale;
142
        }
143
        if ($sqlfilters)
144
        {
145
            if (! DolibarrApi::_checkFilters($sqlfilters))
146
            {
147
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
148
            }
149
	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
150
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
151
        }
152
153
        $sql.= $db->order($sortfield, $sortorder);
154
        if ($limit)	{
155
            if ($page < 0)
156
            {
157
                $page = 0;
158
            }
159
            $offset = $limit * $page;
160
161
            $sql.= $db->plimit($limit + 1, $offset);
162
        }
163
164
        $result = $db->query($sql);
165
        if ($result)
166
        {
167
            $num = $db->num_rows($result);
168
            while ($i < $num)
0 ignored issues
show
Bug introduced by
The variable $i does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
169
            {
170
                $obj = $db->fetch_object($result);
171
                $myobject_static = new MyObject($db);
172
                if($myobject_static->fetch($obj->rowid)) {
173
                    $obj_ret[] = parent::_cleanObjectDatas($myobject_static);
174
                }
175
                $i++;
176
            }
177
        }
178
        else {
179
            throw new RestException(503, 'Error when retrieve myobject list');
180
        }
181
        if( ! count($obj_ret)) {
182
            throw new RestException(404, 'No myobject found');
183
        }
184
		return $obj_ret;
185
    }
186
187
    /**
188
     * Create myobject object
189
     *
190
     * @param array $request_data   Request datas
191
     * @return int  ID of myobject
192
     *
193
     * @url	POST myobjects/
194
     */
195
    function post($request_data = NULL)
196
    {
197
        if(! DolibarrApiAccess::$user->rights->myobject->create) {
198
			throw new RestException(401);
199
		}
200
        // Check mandatory fields
201
        $result = $this->_validate($request_data);
202
203
        foreach($request_data as $field => $value) {
204
            $this->myobject->$field = $value;
205
        }
206
        if( ! $this->myobject->create(DolibarrApiAccess::$user)) {
207
            throw new RestException(500);
208
        }
209
        return $this->myobject->id;
210
    }
211
212
    /**
213
     * Update myobject
214
     *
215
     * @param int   $id             Id of myobject to update
216
     * @param array $request_data   Datas
217
     * @return int
218
     *
219
     * @url	PUT myobjects/{id}
220
     */
221
    function put($id, $request_data = NULL)
222
    {
223
        if(! DolibarrApiAccess::$user->rights->myobject->create) {
224
			throw new RestException(401);
225
		}
226
227
        $result = $this->myobject->fetch($id);
228
        if( ! $result ) {
229
            throw new RestException(404, 'MyObject not found');
230
        }
231
232
		if( ! DolibarrApi::_checkAccessToResource('myobject',$this->myobject->id)) {
233
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
234
		}
235
236
        foreach($request_data as $field => $value) {
237
            $this->myobject->$field = $value;
238
        }
239
240
        if($this->myobject->update($id, DolibarrApiAccess::$user))
241
            return $this->get($id);
242
243
        return false;
244
    }
245
246
    /**
247
     * Delete myobject
248
     *
249
     * @param   int     $id   MyObject ID
250
     * @return  array
251
     *
252
     * @url	DELETE myobject/{id}
253
     */
254
    function delete($id)
255
    {
256
        if(! DolibarrApiAccess::$user->rights->myobject->supprimer) {
257
			throw new RestException(401);
258
		}
259
        $result = $this->myobject->fetch($id);
260
        if( ! $result ) {
261
            throw new RestException(404, 'MyObject not found');
262
        }
263
264
		if( ! DolibarrApi::_checkAccessToResource('myobject',$this->myobject->id)) {
265
			throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
266
		}
267
268
        if( !$this->myobject->delete($id))
269
        {
270
            throw new RestException(500);
271
        }
272
273
         return array(
274
            'success' => array(
275
                'code' => 200,
276
                'message' => 'MyObject deleted'
277
            )
278
        );
279
280
    }
281
282
    /**
283
     * Validate fields before create or update object
284
     *
285
     * @param array $data   Data to validate
286
     * @return array
287
     *
288
     * @throws RestException
289
     */
290
    function _validate($data)
291
    {
292
        $myobject = array();
293
        foreach (MyObjectApi::$FIELDS as $field) {
294
            if (!isset($data[$field]))
295
                throw new RestException(400, "$field field missing");
296
            $myobject[$field] = $data[$field];
297
        }
298
        return $myobject;
299
    }
300
}
301