GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Push — master ( 173d59...ae9f57 )
by Steeven
02:22
created

Restful::index()   D

Complexity

Conditions 19
Paths 81

Size

Total Lines 71
Code Lines 51

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 19
eloc 51
c 3
b 0
f 0
nc 81
nop 0
dl 0
loc 71
rs 4.5166

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
 * This file is part of the O2System Framework package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 *
8
 * @author         Steeve Andrian Salim
9
 * @copyright      Copyright (c) Steeve Andrian Salim
10
 */
11
12
// ------------------------------------------------------------------------
13
14
namespace O2System\Framework\Http\Controllers;
15
16
// ------------------------------------------------------------------------
17
18
use O2System\Cache\Item;
19
use O2System\Framework\Http\Controller;
20
use O2System\Framework\Models\Sql\Model;
21
use O2System\Psr\Http\Header\ResponseFieldInterface;
22
use O2System\Security\Filters\Rules;
23
use O2System\Spl\Exceptions\Logic\OutOfRangeException;
24
25
/**
26
 * Class Restful
27
 *
28
 * @package O2System\Framework\Http\Controllers
29
 */
30
class Restful extends Controller
31
{
32
    /**
33
     * Push headers flag
34
     *
35
     * Used for push default headers by controller.
36
     * Set to FALSE if you want to set default headers on the web-server configuration.
37
     *
38
     * APACHE via .htaccess
39
     * IIS via .webconfig
40
     * Nginx via config
41
     *
42
     * @type string
43
     */
44
    protected $pushDefaultHeaders = false;
45
46
    /**
47
     * Access-Control-Allow-Origin
48
     *
49
     * Used for indicates whether a resource can be shared based by
50
     * returning the value of the Origin request header, "*", or "null" in the response.
51
     *
52
     * @type string
53
     */
54
    protected $accessControlAllowOrigin = '*';
55
56
    /**
57
     * Access-Control-Allow-Credentials
58
     *
59
     * Used for indicates whether the response to request can be exposed when the omit credentials flag is unset.
60
     * When part of the response to a preflight request it indicates that the actual request can include user
61
     * credentials.
62
     *
63
     * @type bool
64
     */
65
    protected $accessControlAllowCredentials = true;
66
67
    /**
68
     * Access-Control-Method
69
     *
70
     * @var string
71
     */
72
    protected $accessControlMethod = 'GET';
73
74
    /**
75
     * Access-Control-Params
76
     *
77
     * @var array
78
     */
79
    protected $accessControlParams = [];
80
81
    /**
82
     * Access-Control-Allow-Methods
83
     *
84
     * Used for indicates, as part of the response to a preflight request,
85
     * which methods can be used during the actual request.
86
     *
87
     * @type array
88
     */
89
    protected $accessControlAllowMethods = [
90
        'GET', // common request
91
        'POST', // used for create, update request
92
        //'PUT', // used for upload files request
93
        //'DELETE', // used for delete request
94
        'OPTIONS', // used for preflight request
95
    ];
96
97
    /**
98
     * Access-Control-Allow-Headers
99
     *
100
     * Used for indicates, as part of the response to a preflight request,
101
     * which header field names can be used during the actual request.
102
     *
103
     * @type int
104
     */
105
    protected $accessControlAllowHeaders = [
106
        'Origin',
107
        'Access-Control-Request-Method',
108
        'Access-Control-Request-Headers',
109
        'X-Api-Authenticate', // API-Authenticate: api_key="xxx", api_secret="xxx", api_signature="xxx"
110
        'X-Api-Token',
111
        'X-Web-Token', // X-Web-Token: xxx (json-web-token)
112
        'X-Csrf-Token',
113
        'X-Xss-Token',
114
        'X-Request-ID',
115
        'X-Requested-With',
116
        'X-Requested-Result',
117
    ];
118
119
    /**
120
     * Access-Control-Allow-Headers
121
     *
122
     * Used for indicates, as part of the response to a preflight request,
123
     * which header field names can be used during the actual request.
124
     *
125
     * @type array
126
     */
127
    protected $accessControlAllowContentTypes = [
128
        'text/html',
129
        'application/json',
130
        'application/xml',
131
    ];
132
133
    /**
134
     * Access-Control-Max-Age
135
     *
136
     * Used for indicates how long the results of a preflight request can be cached in a preflight result cache
137
     *
138
     * @type int
139
     */
140
    protected $accessControlMaxAge = 86400;
141
142
    /**
143
     * Restful::$ajaxOnly
144
     *
145
     * @var bool
146
     */
147
    protected $ajaxOnly = false;
148
149
    /**
150
     * Restful::$model
151
     *
152
     * @var \O2System\Framework\Models\Sql\Model|\O2System\Framework\Models\NoSql\Model|\O2System\Framework\Models\Files\Model
153
     */
154
    public $model;
155
156
    /**
157
     * Restful::$params
158
     *
159
     * @var array
160
     */
161
    public $params = [];
162
163
    /**
164
     * Restful::$paramsWithRules
165
     *
166
     * @var array
167
     */
168
    public $paramsWithRules = [];
169
170
    /**
171
     * Restful::$fillableColumns
172
     *
173
     * @var array
174
     */
175
    public $fillableColumns = [];
176
177
    /**
178
     * Restful::$fillableColumnsWithRules
179
     *
180
     * @var array
181
     */
182
    public $fillableColumnsWithRules = [];
183
184
    // ------------------------------------------------------------------------
185
186
    /**
187
     * Restful::__construct
188
     */
189
    public function __construct()
190
    {
191
        if (services()->has('presenter')) {
192
            presenter()->setTheme(false);
0 ignored issues
show
Bug introduced by
false of type false is incompatible with the type string expected by parameter $theme of O2System\Framework\Http\Presenter::setTheme(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

192
            presenter()->setTheme(/** @scrutinizer ignore-type */ false);
Loading history...
193
        }
194
195
        if (is_ajax()) {
196
            output()->setContentType('application/json');
0 ignored issues
show
Bug introduced by
The method setContentType() does not exist on O2System\Kernel\Cli\Output. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

196
            output()->/** @scrutinizer ignore-call */ setContentType('application/json');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
197
        } elseif ($this->ajaxOnly === false) {
198
            output()->setContentType('application/json');
199
        } else {
200
            output()->setContentType('text/html');
201
        }
202
203
        if ($contentType = input()->server('HTTP_X_REQUESTED_CONTENT_TYPE')) {
204
            if (in_array($contentType, $this->accessControlAllowContentTypes)) {
205
                output()->setContentType($contentType);
206
            }
207
        }
208
209
        if ($this->pushDefaultHeaders) {
210
211
            $origin = input()->server('HTTP_ORIGIN');
212
213
            /**
214
             * Prepare for preflight modern browser request
215
             *
216
             * Since some server cannot use 'Access-Control-Allow-Origin: *'
217
             * the Access-Control-Allow-Origin will be defined based on requested origin
218
             */
219
            if ($this->accessControlAllowOrigin === '*') {
220
                output()->addHeader(ResponseFieldInterface::RESPONSE_ACCESS_CONTROL_ALLOW_ORIGIN, $origin);
0 ignored issues
show
Bug introduced by
The method addHeader() does not exist on O2System\Kernel\Cli\Output. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

220
                output()->/** @scrutinizer ignore-call */ addHeader(ResponseFieldInterface::RESPONSE_ACCESS_CONTROL_ALLOW_ORIGIN, $origin);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
221
            }
222
223
            // Set response access control allowed credentials
224
            if ($this->accessControlAllowCredentials === false) {
225
                output()->addHeader(ResponseFieldInterface::RESPONSE_ACCESS_CONTROL_ALLOW_CREDENTIALS, 'false');
226
            }
227
228
            // Set response access control allowed methods header
229
            if (count($this->accessControlAllowMethods)) {
230
                output()->addHeader(
231
                    ResponseFieldInterface::RESPONSE_ACCESS_CONTROL_ALLOW_METHODS,
232
                    implode(', ', $this->accessControlAllowMethods)
233
                );
234
            }
235
236
            // Set response access control allowed headers header
237
            if (count($this->accessControlAllowHeaders)) {
0 ignored issues
show
Bug introduced by
$this->accessControlAllowHeaders of type integer is incompatible with the type Countable|array expected by parameter $var of count(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

237
            if (count(/** @scrutinizer ignore-type */ $this->accessControlAllowHeaders)) {
Loading history...
238
                output()->addHeader(
239
                    ResponseFieldInterface::RESPONSE_ACCESS_CONTROL_ALLOW_HEADERS,
240
                    implode(', ', $this->accessControlAllowHeaders)
0 ignored issues
show
Bug introduced by
$this->accessControlAllowHeaders of type integer is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

240
                    implode(', ', /** @scrutinizer ignore-type */ $this->accessControlAllowHeaders)
Loading history...
241
                );
242
            }
243
244
            // Set response access control allowed content types header
245
            if (count($this->accessControlAllowContentTypes)) {
246
                output()->addHeader(
247
                    ResponseFieldInterface::RESPONSE_ACCESS_CONTROL_ALLOW_CONTENT_TYPES,
248
                    implode(', ', $this->accessControlAllowContentTypes)
249
                );
250
            }
251
252
            // Set response access control max age header
253
            if ($this->accessControlMaxAge > 0) {
254
                output()->addHeader(ResponseFieldInterface::RESPONSE_ACCESS_CONTROL_MAX_AGE,
255
                    $this->accessControlMaxAge);
256
            }
257
        }
258
259
        if (input()->server('REQUEST_METHOD') === 'OPTIONS') {
260
            exit(EXIT_SUCCESS);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
261
        } elseif ( ! in_array(input()->server('REQUEST_METHOD'), $this->accessControlAllowMethods)) {
262
            $this->sendError(405);
263
        } elseif (count($this->accessControlParams)) {
264
            if ($this->accessControlMethod === 'GET') {
265
                if (empty($_GET)) {
266
                    $this->sendError(400);
267
                }
268
            } elseif ($this->accessControlMethod === 'POST') {
269
                if (empty($_POST)) {
270
                    $this->sendError(400);
271
                }
272
            } elseif (in_array($this->accessControlMethod, ['GETPOST', 'POSTGET'])) {
273
                if (empty($_REQUEST)) {
274
                    $this->sendError(400);
275
                }
276
            }
277
        }
278
279
        if (empty($this->model)) {
280
            $controllerClassName = get_called_class();
281
            $modelClassName = str_replace('Controllers', 'Models', $controllerClassName);
282
283
            if (class_exists($modelClassName)) {
284
                $this->model = new $modelClassName();
285
            }
286
        } elseif (class_exists($this->model)) {
0 ignored issues
show
Bug introduced by
$this->model of type O2System\Framework\Model...mework\Models\Sql\Model is incompatible with the type string expected by parameter $class_name of class_exists(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

286
        } elseif (class_exists(/** @scrutinizer ignore-type */ $this->model)) {
Loading history...
287
            $this->model = new $this->model();
288
        }
289
    }
290
291
    // ------------------------------------------------------------------------
292
293
    /**
294
     * Restful::index
295
     */
296
    public function index()
297
    {
298
        if(empty($this->model)) {
299
            output()->sendError(204);
300
        } else {
301
            if ( ! $this->model instanceof Model) {
302
                $this->sendError(503, 'Model is not exists!');
303
            }
304
305
            if ( ! $this->model instanceof Model) {
0 ignored issues
show
introduced by
$this->model is always a sub-type of O2System\Framework\Models\Sql\Model.
Loading history...
306
                $this->sendError(503, 'Model is not exists!');
307
            }
308
309
            if (count($this->params)) {
310
                if ($get = input()->get()) {
311
                    if (false !== ($result = $this->model->withPaging()->findWhere($get->getArrayCopy()))) {
312
                        if ($result->count()) {
313
                            $this->sendPayload($result);
314
                        } else {
315
                            $this->sendError(204);
316
                        }
317
                    } else {
318
                        $this->sendError(204);
319
                    }
320
                } else {
321
                    $this->sendError(400, 'Get parameters cannot be empty!');
322
                }
323
            } elseif (count($this->paramsWithRules)) {
324
                if ($get = input()->get()) {
325
                    $rules = new Rules($get);
0 ignored issues
show
Bug introduced by
$get of type O2System\Spl\DataStructures\SplArrayObject is incompatible with the type array expected by parameter $sourceVars of O2System\Security\Filters\Rules::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

325
                    $rules = new Rules(/** @scrutinizer ignore-type */ $get);
Loading history...
326
                    $rules->sets($this->paramsWithRules);
327
328
                    if ( ! $rules->validate()) {
329
                        $this->sendError(400, implode(', ', $rules->displayErrors(true)));
0 ignored issues
show
Bug introduced by
It seems like $rules->displayErrors(true) can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

329
                        $this->sendError(400, implode(', ', /** @scrutinizer ignore-type */ $rules->displayErrors(true)));
Loading history...
Unused Code introduced by
The call to O2System\Security\Filters\Rules::displayErrors() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

329
                        $this->sendError(400, implode(', ', $rules->/** @scrutinizer ignore-call */ displayErrors(true)));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
330
                    } else {
331
                        $conditions = [];
332
333
                        foreach ($this->paramsWithRules as $param) {
334
                            if ($get->offsetExists($param[ 'field' ])) {
335
                                $conditions[ $param[ 'field' ] ] = $get->offsetGet($param[ 'field' ]);
336
                            }
337
                        }
338
339
                        if (false !== ($result = $this->model->withPaging()->findWhere($conditions))) {
340
                            if ($result->count()) {
341
                                $this->sendPayload($result);
342
                            } else {
343
                                $this->sendError(204);
344
                            }
345
                        } else {
346
                            $this->sendError(204);
347
                        }
348
                    }
349
                } else {
350
                    $this->sendError(400, 'Get parameters cannot be empty!');
351
                }
352
            } elseif ($get = input()->get()) {
353
                if (false !== ($result = $this->model->withPaging()->findWhere($get->getArrayCopy()))) {
354
                    if ($result->count()) {
355
                        $this->sendPayload($result);
356
                    } else {
357
                        $this->sendError(204);
358
                    }
359
                } else {
360
                    $this->sendError(204);
361
                }
362
            } else {
363
                if (false !== ($result = $this->model->allWithPaging())) {
364
                    $this->sendPayload($result);
365
                } else {
366
                    $this->sendError(204);
367
                }
368
            }
369
        }
370
    }
371
372
    // ------------------------------------------------------------------------
373
374
    public function sendError($code, $message = null)
375
    {
376
        if ($this->ajaxOnly === false) {
377
            output()->setContentType('application/json');
378
        }
379
380
        if (is_array($code)) {
381
            if (is_numeric(key($code))) {
382
                $message = reset($code);
383
                $code = key($code);
384
            } elseif (isset($code[ 'code' ])) {
385
                $code = $code[ 'code' ];
386
                $message = $code[ 'message' ];
387
            }
388
        }
389
390
        output()->sendError($code, $message);
391
    }
392
393
    // ------------------------------------------------------------------------
394
395
    /**
396
     * Restful::sendPayload
397
     *
398
     * @param mixed $data        The payload data to-be send.
399
     * @param bool  $longPooling Long pooling flag mode.
400
     *
401
     * @throws \Exception
402
     */
403
    public function sendPayload($data, $longPooling = false)
404
    {
405
        if ($longPooling === false) {
406
            if ($this->ajaxOnly) {
407
                if (is_ajax()) {
408
                    output()->send($data);
0 ignored issues
show
Bug introduced by
The method send() does not exist on O2System\Kernel\Cli\Output. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

408
                    output()->/** @scrutinizer ignore-call */ send($data);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
409
                } else {
410
                    output()->sendError(403);
411
                }
412
            } else {
413
                output()->send($data);
414
            }
415
        } elseif (is_ajax()) {
416
            /**
417
             * Server-side file.
418
             * This file is an infinitive loop. Seriously.
419
             * It gets the cache created timestamp, checks if this is larger than the timestamp of the
420
             * AJAX-submitted timestamp (time of last ajax request), and if so, it sends back a JSON with the data from
421
             * data.txt (and a timestamp). If not, it waits for one seconds and then start the next while step.
422
             *
423
             * Note: This returns a JSON, containing the content of data.txt and the timestamp of the last data.txt change.
424
             * This timestamp is used by the client's JavaScript for the next request, so THIS server-side script here only
425
             * serves new content after the last file change. Sounds weird, but try it out, you'll get into it really fast!
426
             */
427
428
            // set php runtime to unlimited
429
            set_time_limit(0);
430
431
            $longPoolingCacheKey = 'long-pooling-' . session()->get('id');
0 ignored issues
show
Bug introduced by
Are you sure session()->get('id') of type false|mixed can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

431
            $longPoolingCacheKey = 'long-pooling-' . /** @scrutinizer ignore-type */ session()->get('id');
Loading history...
432
            $longPoolingCacheData = null;
433
434
            if ( ! cache()->hasItem($longPoolingCacheKey)) {
435
                cache()->save(new Item($longPoolingCacheKey, $data));
436
            }
437
438
            // main loop
439
            while (true) {
440
                // if ajax request has send a timestamp, then $lastCallTimestamp = timestamp, else $last_call = null
441
                $lastCallTimestamp = (int)input()->getPost('last_call_timestamp');
0 ignored issues
show
Bug introduced by
The method getPost() does not exist on O2System\Kernel\Cli\Input. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

441
                $lastCallTimestamp = (int)input()->/** @scrutinizer ignore-call */ getPost('last_call_timestamp');

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
442
443
                // PHP caches file data, like requesting the size of a file, by default. clearstatcache() clears that cache
444
                clearstatcache();
445
446
                if (cache()->hasItem($longPoolingCacheKey)) {
447
                    $longPoolingCacheData = cache()->getItem($longPoolingCacheKey);
448
                }
449
450
                // get timestamp of when file has been changed the last time
451
                $longPoolingCacheMetadata = $longPoolingCacheData->getMetadata();
452
453
                // if no timestamp delivered via ajax or data.txt has been changed SINCE last ajax timestamp
454
                if ($lastCallTimestamp == null || $longPoolingCacheMetadata[ 'ctime' ] > $lastCallTimestamp) {
455
                    output()->send([
456
                        'timestamp' => $longPoolingCacheMetadata,
457
                        'data'      => $data,
458
                    ]);
459
                } else {
460
                    // wait for 1 sec (not very sexy as this blocks the PHP/Apache process, but that's how it goes)
461
                    sleep(1);
462
                    continue;
463
                }
464
            }
465
        } else {
466
            output()->sendError(501);
467
        }
468
    }
469
470
    /**
471
     * Controller::create
472
     *
473
     * @throws \O2System\Spl\Exceptions\Logic\BadFunctionCall\BadDependencyCallException
474
     * @throws \O2System\Spl\Exceptions\Logic\OutOfRangeException
475
     */
476
    public function create()
477
    {
478
        if ($post = input()->post()) {
479
            if (count($this->fillableColumnsWithRules)) {
480
                $rules = new Rules($post);
0 ignored issues
show
Bug introduced by
$post of type O2System\Spl\DataStructures\SplArrayObject is incompatible with the type array expected by parameter $sourceVars of O2System\Security\Filters\Rules::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

480
                $rules = new Rules(/** @scrutinizer ignore-type */ $post);
Loading history...
481
                $rules->sets($this->fillableColumnsWithRules);
482
                if ( ! $rules->validate()) {
483
                    $this->sendError(400, $rules->displayErrors(true));
0 ignored issues
show
Unused Code introduced by
The call to O2System\Security\Filters\Rules::displayErrors() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

483
                    $this->sendError(400, $rules->/** @scrutinizer ignore-call */ displayErrors(true));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
484
                }
485
            }
486
487
            if ( ! $this->model instanceof Model) {
488
                $this->sendError(503, 'Model is not ready');
489
            }
490
491
            $data = [];
492
493
            if (count($this->fillableColumnsWithRules)) {
494
                foreach ($this->fillableColumnsWithRules as $column) {
495
                    if ($post->offsetExists($column[ 'field' ])) {
496
                        $data[ $column[ 'field' ] ] = $post->offsetGet($column[ 'field' ]);
497
                    }
498
                }
499
            } elseif (count($this->fillableColumns)) {
500
                foreach ($this->fillableColumns as $column) {
501
                    if ($post->offsetExists($column[ 'field' ])) {
502
                        $data[ $column[ 'field' ] ] = $post->offsetGet($column[ 'field' ]);
503
                    }
504
                }
505
            } else {
506
                $data = $post->getArrayCopy();
507
            }
508
509
            if (count($data)) {
510
                $data[ 'record_create_timestamp' ] = $data[ 'record_update_timestamp' ] = timestamp();
511
                $data[ 'record_create_user' ] = $data[ 'record_update_user' ] = globals()->account->id;
0 ignored issues
show
Bug Best Practice introduced by
The property account does not exist on O2System\Framework\Containers\Globals. Since you implemented __get, consider adding a @property annotation.
Loading history...
512
513
                if ($this->model->insert($data)) {
514
                    $data[ 'id' ] = $this->model->db->getLastInsertId();
515
                    $this->sendPayload([
516
                        'code' => 201,
517
                        'Successful insert request',
518
                        'data' => $data,
519
                    ]);
520
                } else {
521
                    $this->sendError(501, 'Failed update request');
522
                }
523
            } else {
524
                $this->sendError(400, 'Post parameters cannot be empty!');
525
            }
526
        } else {
527
            $this->sendError(400);
528
        }
529
    }
530
531
    // ------------------------------------------------------------------------
532
533
    /**
534
     * Restful::update
535
     *
536
     * @throws \O2System\Spl\Exceptions\Logic\BadFunctionCall\BadDependencyCallException
537
     * @throws \O2System\Spl\Exceptions\Logic\OutOfRangeException
538
     */
539
    public function update()
540
    {
541
        if ($post = input()->post()) {
542
            $conditions = [];
543
544
            if (count($this->fillableColumnsWithRules)) {
545
                $rules = new Rules($post);
0 ignored issues
show
Bug introduced by
$post of type O2System\Spl\DataStructures\SplArrayObject is incompatible with the type array expected by parameter $sourceVars of O2System\Security\Filters\Rules::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

545
                $rules = new Rules(/** @scrutinizer ignore-type */ $post);
Loading history...
546
                $rules->sets($this->fillableColumnsWithRules);
547
                
548
                if(count($this->model->primaryKeys)) {
0 ignored issues
show
Bug Best Practice introduced by
The property primaryKeys does not exist on O2System\Framework\Models\Files\Model. Since you implemented __get, consider adding a @property annotation.
Loading history...
549
                    foreach($this->model->primaryKeys as $primaryKey) {
550
                        $rules->add($primaryKey, language('LABEL_' . strtoupper($primaryKey)), 'required', 'this field cannot be empty!');
0 ignored issues
show
Bug introduced by
language('LABEL_' . strtoupper($primaryKey)) of type O2System\Framework\Servi...ernel\Services\Language is incompatible with the type string expected by parameter $label of O2System\Security\Filters\Rules::add(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

550
                        $rules->add($primaryKey, /** @scrutinizer ignore-type */ language('LABEL_' . strtoupper($primaryKey)), 'required', 'this field cannot be empty!');
Loading history...
Bug introduced by
'this field cannot be empty!' of type string is incompatible with the type array expected by parameter $messages of O2System\Security\Filters\Rules::add(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

550
                        $rules->add($primaryKey, language('LABEL_' . strtoupper($primaryKey)), 'required', /** @scrutinizer ignore-type */ 'this field cannot be empty!');
Loading history...
551
                    }
552
                } else {
553
                    $primaryKey = empty($this->model->primaryKey) ? 'id' : $this->model->primaryKey;
554
                    $conditions = [$primaryKey => $post->offsetGet($primaryKey)];
555
                    $rules->add($primaryKey, language('LABEL_' . strtoupper($primaryKey)), 'required', 'this field cannot be empty!');
556
                }
557
558
                if ( ! $rules->validate()) {
559
                    $this->sendError(400, implode(', ', $rules->displayErrors(true)));
0 ignored issues
show
Bug introduced by
It seems like $rules->displayErrors(true) can also be of type string; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

559
                    $this->sendError(400, implode(', ', /** @scrutinizer ignore-type */ $rules->displayErrors(true)));
Loading history...
Unused Code introduced by
The call to O2System\Security\Filters\Rules::displayErrors() has too many arguments starting with true. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

559
                    $this->sendError(400, implode(', ', $rules->/** @scrutinizer ignore-call */ displayErrors(true)));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
560
                }
561
            }
562
563
            if ( ! $this->model instanceof Model) {
564
                $this->sendError(503, 'Model is not ready');
565
            }
566
567
            $data = [];
568
569
            if (count($this->fillableColumnsWithRules)) {
570
                foreach ($this->fillableColumnsWithRules as $column) {
571
                    if ($post->offsetExists($column[ 'field' ])) {
572
                        $data[ $column[ 'field' ] ] = $post->offsetGet($column[ 'field' ]);
573
                    }
574
                }
575
            } elseif (count($this->fillableColumns)) {
576
                foreach ($this->fillableColumns as $column) {
577
                    if ($post->offsetExists($column[ 'field' ])) {
578
                        $data[ $column[ 'field' ] ] = $post->offsetGet($column[ 'field' ]);
579
                    }
580
                }
581
            } else {
582
                $data = $post->getArrayCopy();
583
            }
584
585
            if (count($data)) {
586
                $data[ 'record_update_timestamp' ] = timestamp();
587
                $data[ 'record_update_user' ] = globals()->account->id;
0 ignored issues
show
Bug Best Practice introduced by
The property account does not exist on O2System\Framework\Containers\Globals. Since you implemented __get, consider adding a @property annotation.
Loading history...
588
589
590
591
                if ($this->model->update($data, $conditions)) {
592
                    $this->sendError(201, 'Successful update request');
593
                } else {
594
                    $this->sendError(501, 'Failed update request');
595
                }
596
            } else {
597
                $this->sendError(400, 'Post parameters cannot be empty!');
598
            }
599
        } else {
600
            $this->sendError(400);
601
        }
602
    }
603
604
    // ------------------------------------------------------------------------
605
606
    /**
607
     * Restful::delete
608
     *
609
     * @throws \O2System\Spl\Exceptions\Logic\OutOfRangeException
610
     * @throws \O2System\Spl\Exceptions\RuntimeException
611
     * @throws \Psr\Cache\InvalidArgumentException
612
     */
613
    public function delete()
614
    {
615
        if ($post = input()->post()) {
616
            $rules = new Rules($post);
0 ignored issues
show
Bug introduced by
$post of type O2System\Spl\DataStructures\SplArrayObject is incompatible with the type array expected by parameter $sourceVars of O2System\Security\Filters\Rules::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

616
            $rules = new Rules(/** @scrutinizer ignore-type */ $post);
Loading history...
617
            $rules->add('id', 'ID', 'required', 'ID field cannot be empty!');
0 ignored issues
show
Bug introduced by
'ID field cannot be empty!' of type string is incompatible with the type array expected by parameter $messages of O2System\Security\Filters\Rules::add(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

617
            $rules->add('id', 'ID', 'required', /** @scrutinizer ignore-type */ 'ID field cannot be empty!');
Loading history...
618
619
            if ( ! $rules->validate()) {
620
                $this->sendError(400, implode(', ', $rules->getErrors()));
621
            }
622
623
            if ( ! $this->model instanceof Model) {
624
                $this->sendError(503, 'Model is not ready');
625
            }
626
627
            if ($this->model->delete($post->id)) {
628
                $this->sendError(201, 'Successful delete request');
629
            } else {
630
                $this->sendError(501, 'Failed delete request');
631
            }
632
        } else {
633
            $this->sendError(400);
634
        }
635
    }
636
637
    // ------------------------------------------------------------------------
638
639
    /**
640
     * Restful::publish
641
     *
642
     * @throws OutOfRangeException
643
     */
644
    public function publish()
645
    {
646
        if ($post = input()->post()) {
647
            $rules = new Rules($post);
0 ignored issues
show
Bug introduced by
$post of type O2System\Spl\DataStructures\SplArrayObject is incompatible with the type array expected by parameter $sourceVars of O2System\Security\Filters\Rules::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

647
            $rules = new Rules(/** @scrutinizer ignore-type */ $post);
Loading history...
648
            $rules->add('id', 'ID', 'required', 'ID field cannot be empty!');
0 ignored issues
show
Bug introduced by
'ID field cannot be empty!' of type string is incompatible with the type array expected by parameter $messages of O2System\Security\Filters\Rules::add(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

648
            $rules->add('id', 'ID', 'required', /** @scrutinizer ignore-type */ 'ID field cannot be empty!');
Loading history...
649
650
            if ( ! $rules->validate()) {
651
                $this->sendError(400, implode(', ', $rules->getErrors()));
652
            }
653
654
            if ( ! $this->model instanceof Model) {
655
                $this->sendError(503, 'Model is not ready');
656
            }
657
658
            if ($this->model->publish($post->id)) {
659
                $this->sendError(201, 'Successful publish request');
660
            } else {
661
                $this->sendError(501, 'Failed publish request');
662
            }
663
        } else {
664
            $this->sendError(400);
665
        }
666
    }
667
668
    // ------------------------------------------------------------------------
669
670
    /**
671
     * Restful::unpublish
672
     *
673
     * @throws OutOfRangeException
674
     */
675
    public function unpublish()
676
    {
677
        if ($post = input()->post()) {
678
            $rules = new Rules($post);
0 ignored issues
show
Bug introduced by
$post of type O2System\Spl\DataStructures\SplArrayObject is incompatible with the type array expected by parameter $sourceVars of O2System\Security\Filters\Rules::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

678
            $rules = new Rules(/** @scrutinizer ignore-type */ $post);
Loading history...
679
            $rules->add('id', 'ID', 'required', 'ID field cannot be empty!');
0 ignored issues
show
Bug introduced by
'ID field cannot be empty!' of type string is incompatible with the type array expected by parameter $messages of O2System\Security\Filters\Rules::add(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

679
            $rules->add('id', 'ID', 'required', /** @scrutinizer ignore-type */ 'ID field cannot be empty!');
Loading history...
680
681
            if ( ! $rules->validate()) {
682
                $this->sendError(400, implode(', ', $rules->getErrors()));
683
            }
684
685
            if ( ! $this->model instanceof Model) {
686
                $this->sendError(503, 'Model is not ready');
687
            }
688
689
            if ($this->model->unpublish($post->id)) {
690
                $this->sendError(201, 'Successful unpublish request');
691
            } else {
692
                $this->sendError(501, 'Failed unpublish request');
693
            }
694
        } else {
695
            $this->sendError(400);
696
        }
697
    }
698
699
    // ------------------------------------------------------------------------
700
701
    /**
702
     * Controller::archive
703
     *
704
     * @throws OutOfRangeException
705
     */
706
    public function archive()
707
    {
708
        if ($post = input()->post()) {
709
            $rules = new Rules($post);
0 ignored issues
show
Bug introduced by
$post of type O2System\Spl\DataStructures\SplArrayObject is incompatible with the type array expected by parameter $sourceVars of O2System\Security\Filters\Rules::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

709
            $rules = new Rules(/** @scrutinizer ignore-type */ $post);
Loading history...
710
            $rules->add('id', 'ID', 'required', 'ID field cannot be empty!');
0 ignored issues
show
Bug introduced by
'ID field cannot be empty!' of type string is incompatible with the type array expected by parameter $messages of O2System\Security\Filters\Rules::add(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

710
            $rules->add('id', 'ID', 'required', /** @scrutinizer ignore-type */ 'ID field cannot be empty!');
Loading history...
711
712
            if ( ! $rules->validate()) {
713
                $this->sendError(400, implode(', ', $rules->getErrors()));
714
            }
715
716
            if ( ! $this->model instanceof Model) {
717
                $this->sendError(503, 'Model is not ready');
718
            }
719
720
            if ($this->model->unpublish($post->id)) {
721
                $this->sendError(201, 'Successful archived request');
722
            } else {
723
                $this->sendError(501, 'Failed archived request');
724
            }
725
        } else {
726
            $this->sendError(400);
727
        }
728
    }
729
}