Test Failed
Pull Request — master (#5)
by
unknown
04:14
created

Rest::mergeColumns()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 12
c 2
b 1
f 1
dl 0
loc 20
ccs 0
cts 13
cp 0
rs 8.8333
cc 7
nc 6
nop 1
crap 56
1
<?php
2
/**
3
 * This file is part of the Zemit Framework.
4
 *
5
 * (c) Zemit Team <[email protected]>
6
 *
7
 * For the full copyright and license information, please view the LICENSE.txt
8
 * file that was distributed with this source code.
9
 */
10
11
namespace Zemit\Mvc\Controller;
12
13
use League\Csv\CharsetConverter;
14
use Phalcon\Http\Response;
15
use Phalcon\Mvc\Dispatcher;
16
use Phalcon\Mvc\Model\Resultset;
17
use League\Csv\Writer;
18
use Phalcon\Version;
19
use Zemit\Db\Profiler;
20
use Zemit\Utils\Slug;
21
22
/**
23
 * Class Rest
24
 *
25
 * @author Julien Turbide <[email protected]>
26
 * @copyright Zemit Team <[email protected]>
27
 *
28
 * @since 1.0
29
 * @version 1.0
30
 *
31
 *
32
 * @property Profiler $profiler
33
 * @package Zemit\Mvc\Controller
34
 */
35
class Rest extends \Zemit\Mvc\Controller
36
{
37
    use Model;
0 ignored issues
show
Bug introduced by
The trait Zemit\Mvc\Controller\Model requires the property $loader which is not provided by Zemit\Mvc\Controller\Rest.
Loading history...
38
    
39
    /**
40
     * Rest Bootstrap
41
     */
42
    public function indexAction($id = null)
43
    {
44
        $this->restForwarding($id);
45
    }
46
    
47
    /**
48
     * Rest bootstrap forwarding
49
     *
50
     * @return \Phalcon\Http\ResponseInterface
51
     */
52
    protected function restForwarding($id = null)
53
    {
54
        $id ??= $this->getParam('id');
55
        
56
        if ($this->request->isPost() || $this->request->isPut()) {
57
            $this->dispatcher->forward(['action' => 'save']);
58
        }
59
        else if ($this->request->isDelete()) {
60
            $this->dispatcher->forward(['action' => 'delete']);
61
        }
62
        else if ($this->request->isGet()) {
63
            if (is_null($id)) {
64
                $this->dispatcher->forward(['action' => 'getList']);
65
            }
66
            else {
67
                $this->dispatcher->forward(['action' => 'get']);
68
            }
69
        }
70
        else if ($this->request->isOptions()) {
71
            
72
            // @TODO handle this correctly
73
            return $this->setRestResponse(['result' => 'OK']);
74
        }
75
    }
76
    
77
    /**
78
     * Retrieving a single record
79
     * Alias of method getAction()
80
     * @deprecated Should use getAction() method instead
81
     *
82
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
83
     *
84
     * @return bool|\Phalcon\Http\ResponseInterface
85
     */
86
    public function getSingleAction($id = null) {
87
        return $this->getAction($id);
88
    }
89
    
90
    /**
91
     * Retrieving a single record
92
     *
93
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
94
     *
95
     * @return bool|\Phalcon\Http\ResponseInterface
96
     */
97
    public function getAction($id = null)
98
    {
99
        $modelName = $this->getModelClassName();
100
        $single = $this->getSingle($id, $modelName, null);
101
        
102
        $this->view->single = $single ? $single->expose($this->getExpose()) : false;
0 ignored issues
show
Bug introduced by
The method expose() does not exist on Phalcon\Mvc\Model\Resultset. ( Ignorable by Annotation )

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

102
        $this->view->single = $single ? $single->/** @scrutinizer ignore-call */ expose($this->getExpose()) : false;

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...
Bug introduced by
Are you sure the usage of $this->getExpose() targeting Zemit\Mvc\Controller\Rest::getExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
103
        $this->view->model = $modelName;
104
        $this->view->source = $single ? $single->getSource() : false;
0 ignored issues
show
Bug introduced by
The method getSource() does not exist on Phalcon\Mvc\Model\Resultset. ( Ignorable by Annotation )

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

104
        $this->view->source = $single ? $single->/** @scrutinizer ignore-call */ getSource() : false;

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...
105
        
106
        if (!$single) {
107
            $this->response->setStatusCode(404, 'Not Found');
108
            
109
            return false;
110
        }
111
        
112
        return $this->setRestResponse();
113
    }
114
    
115
    /**
116
     * Retrieving a record list
117
     * Alias of method getListAction()
118
     * @deprecated Should use getListAction() method instead
119
     *
120
     * @return \Phalcon\Http\ResponseInterface
121
     */
122
    public function getAllAction() {
123
        return $this->getListAction();
124
    }
125
    
126
    /**
127
     * Retrieving a record list
128
     *
129
     * @return \Phalcon\Http\ResponseInterface
130
     * @throws \Exception
131
     */
132
    public function getListAction()
133
    {
134
        $model = $this->getModelClassName();
135
        
136
        /** @var Resultset $with */
137
        $find = $this->getFind();
138
        $with = $model::with($this->getListWith() ? : [], $find ? : []);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getListWith() targeting Zemit\Mvc\Controller\Rest::getListWith() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
139
        
140
        /**
141
         * Expose the list
142
         * @var int $key
143
         * @var \Zemit\Mvc\Model $item
144
         */
145
        $list = [];
146
        foreach ($with as $key => $item) {
147
            $list[$key] = $item->expose($this->getListExpose());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getListExpose() targeting Zemit\Mvc\Controller\Rest::getListExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
148
        }
149
        
150
        $list = is_array($list) ? array_values(array_filter($list)) : $list;
0 ignored issues
show
introduced by
The condition is_array($list) is always true.
Loading history...
151
        $this->view->list = $list;
152
        $this->view->listCount = count($list);
153
        $this->view->totalCount = $model::find($this->getFindCount($find));
154
        $this->view->totalCount = is_int($this->view->totalCount)? $this->view->totalCount : count($this->view->totalCount); // @todo fix count to work with rollup when joins
155
        $this->view->limit = $find['limit'] ?? false;
156
        $this->view->offset = $find['offset'] ?? false;
157
        $this->view->find = ($this->config->app->debug || $this->config->debug->enable) ? $find : false;
0 ignored issues
show
Bug Best Practice introduced by
The property app does not exist on Zemit\Bootstrap\Config. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property debug does not exist on Zemit\Bootstrap\Config. Since you implemented __get, consider adding a @property annotation.
Loading history...
158
        
159
        return $this->setRestResponse();
160
    }
161
    
162
    /**
163
     * Exporting a record list into a CSV stream
164
     *
165
     * @return \Phalcon\Http\ResponseInterface
166
     * @throws \League\Csv\CannotInsertRecord
167
     * @throws \Zemit\Exception
168
     */
169
    public function exportAction()
170
    {
171
        $model = $this->getModelClassName();
172
        $params = $this->view->getParamsToView();
173
        $contentType = $this->getContentType();
174
        $fileName = ucfirst(Slug::generate(basename(str_replace('\\', '/', $this->getModelClassName())))) . ' List (' . date('Y-m-d') . ')';
175
        
176
        /** @var Resultset $with */
177
        $find = $this->getFind();
178
        $with = $model::with($this->getListWith() ? : [], $find ? : []);
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getListWith() targeting Zemit\Mvc\Controller\Rest::getListWith() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
179
180
        /**
181
         * Expose the list
182
         * @var int $key
183
         * @var \Zemit\Mvc\Model $item
184
         */
185
        $list = [];
186
        foreach ($with as $key => $item) {
187
            $list[$key] = $item->expose($this->getExportExpose());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getExportExpose() targeting Zemit\Mvc\Controller\Rest::getExportExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
188
        }
189
190
        $list = is_array($list) ? array_values(array_filter($list)) : $list;
0 ignored issues
show
introduced by
The condition is_array($list) is always true.
Loading history...
191
        $this->flatternArrayForCsv($list);
192
193
        if ($contentType === 'json') {
194
//            $this->response->setJsonContent($list);
195
            $this->response->setContent(json_encode($list, JSON_PRETTY_PRINT, 2048));
196
            $this->response->setContentType('application/json');
197
            $this->response->setHeader('Content-disposition', 'attachment; filename="'.addslashes($fileName).'.json"');
198
            return $this->response->send();
199
        }
200
        
201
        // CSV
202
        if ($contentType === 'csv') {
203
            
204
            // Get CSV custom request parameters
205
            $mode = $params['mode'] ?? null;
206
            $delimiter = $params['delimiter'] ?? null;
207
            $newline = $params['newline'] ?? null;
208
            $escape = $params['escape'] ?? null;
209
            $outputBOM = $params['outputBOM'] ?? null;
210
            $skipIncludeBOM = $params['skipIncludeBOM'] ?? null;
211
            
212
//            $csv = Writer::createFromFileObject(new \SplTempFileObject());
213
            $csv = Writer::createFromStream(fopen('php://memory', 'r+'));
214
            
215
            // CSV - MS Excel on MacOS
216
            if ($mode === 'mac') {
217
                $csv->setOutputBOM(Writer::BOM_UTF16_LE); // utf-16
218
                $csv->setDelimiter("\t"); // tabs separated
219
                $csv->setNewline("\r\n"); // new lines
220
                CharsetConverter::addTo($csv, 'UTF-8', 'UTF-16');
221
            }
222
            
223
            // CSV - MS Excel on Windows
224
            else {
225
                $csv->setOutputBOM(Writer::BOM_UTF8); // utf-8
226
                $csv->setDelimiter(','); // comma separated
227
                $csv->setNewline("\n"); // new line windows
228
                CharsetConverter::addTo($csv, 'UTF-8', 'UTF-8');
229
            }
230
            
231
            // Apply forced params from request
232
            if (isset($outputBOM)) {
233
                $csv->setOutputBOM($outputBOM);
234
            }
235
            if (isset($delimiter)) {
236
                $csv->setDelimiter($delimiter);
237
            }
238
            if (isset($newline)) {
239
                $csv->setNewline($newline);
240
            }
241
            if (isset($escape)) {
242
                $csv->setEscape($escape);
243
            }
244
            if ($skipIncludeBOM) {
245
                $csv->skipInputBOM();
246
            }
247
            else {
248
                $csv->includeInputBOM();
249
            }
250
            
251
            // CSV
252
            $csv->insertOne(array_keys($list[0]));
253
            $csv->insertAll($list);
254
            $csv->output($fileName . '.csv');
255
            die;
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...
256
        }
257
        
258
        // XLSX
259
        if ($contentType === 'xlsx') {
260
            $xlsxArray = [];
261
            foreach ($list as $array) {
262
                if (empty($xlsxArray)) {
263
                    $xlsxArray []= array_keys($array);
264
                }
265
                $xlsxArray []= array_values($array);
266
            }
267
            $xlsx = \SimpleXLSXGen::fromArray($xlsxArray);
268
            $xlsx->downloadAs($fileName . '.xlsx');
269
            die;
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...
270
        }
271
        
272
        // Something went wrong
273
        throw new \Exception('Failed to export `' . $this->getModelClassName() . '` using content-type `' . $contentType . '`', 400);
274
    }
275
276
    /**
277
     * @param array|null $array
278
     *
279
     * @return array|null
280
     */
281
    public function flatternArrayForCsv(?array &$list = null) {
282
283
        foreach ($list as $listKey => $listValue) {
284
            foreach ($listValue as $column => $value) {
285
                if (is_array($value) || is_object($value)) {
286
                    $value = $this->concatListFieldElementForCsv($value, ' ');
287
                    $list[$listKey][$column] = $this->arrayFlatten($value , $column);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type object; however, parameter $array of Zemit\Mvc\Controller\Rest::arrayFlatten() does only seem to accept array|null, 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

287
                    $list[$listKey][$column] = $this->arrayFlatten(/** @scrutinizer ignore-type */ $value , $column);
Loading history...
Coding Style introduced by
Space found before comma in argument list
Loading history...
288
                    if (is_array($list[$listKey][$column])) {
289
                        foreach ($list[$listKey][$column] as $childKey => $childValue) {
290
                            $list[$listKey][$childKey] = $childValue;
291
                            unset ($list[$listKey][$column]);
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
292
                        }
293
                    }
294
                }
295
            }
296
        }
297
298
        $this->formatColumnText($list);
299
        return $this->mergeColumns($list);
300
    }
301
302
    /**
303
     * @param array|object $list
304
     * @param string|null $seperator
305
     *
306
     * @return array|object
307
     */
308
    public function concatListFieldElementForCsv($list, $seperator = ' ') {
309
        foreach ($list as $valueKey => $element) {
310
            if (is_array($element) || is_object($element)) {
311
                $lastKey = array_key_last($list);
0 ignored issues
show
Bug introduced by
It seems like $list can also be of type object; however, parameter $array of array_key_last() 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

311
                $lastKey = array_key_last(/** @scrutinizer ignore-type */ $list);
Loading history...
312
                if ($valueKey === $lastKey) {
313
                    continue;
314
                }
315
                foreach ($element as $elKey => $elValue) {
316
                    $list[$lastKey][$elKey] .= $seperator . $elValue;
317
                    if ($lastKey != $valueKey) {
318
                        unset($list[$valueKey]);
319
                    }
320
                }
321
            }
322
        }
323
324
        return $list;
325
    }
326
327
    /**
328
     * @param array|null $array
329
     * @param string|null $alias
330
     *
331
     * @return array|null
332
     */
333
    function arrayFlatten(?array $array, ?string $alias = null) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for arrayFlatten.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
334
        $return = array();
335
        foreach ($array as $key => $value) {
336
            if (is_array($value)) {
337
                $return = array_merge($return, $this->arrayFlatten($value, $alias));
338
            }
339
            else {
340
                $return[$alias . '.' . $key] = $value;
341
            }
342
        }
343
        return $return;
344
    }
345
346
    /**
347
     * @param array|null $list
348
     *
349
     * @return array|null
350
     */
351
    public function mergeColumns (?array &$list) {
0 ignored issues
show
Coding Style introduced by
Expected "function abc(...)"; found "function abc (...)"
Loading history...
Coding Style introduced by
Expected 0 spaces before opening parenthesis; 1 found
Loading history...
352
        $columnToMergeList = $this->getExportMergeColum ();
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
Bug introduced by
Are you sure the assignment to $columnToMergeList is correct as $this->getExportMergeColum() targeting Zemit\Mvc\Controller\Rest::getExportMergeColum() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
353
        if (!$columnToMergeList || empty($columnToMergeList)) {
0 ignored issues
show
introduced by
$columnToMergeList is of type null, thus it always evaluated to false.
Loading history...
354
            return  $list;
355
        }
356
357
        $columnList = [];
358
        foreach ($list as $listKey => $listValue) {
359
            foreach ($columnToMergeList as $columnToMerge) {
360
                foreach ($columnToMerge['columns'] as $column) {
361
                    if (isset($listValue[$column])) {
362
                        $columnList[$listKey][] = $listValue[$column];
363
                        unset($list[$listKey][$column]);
364
                    }
365
                }
366
                $list[$listKey][$columnToMerge['name']] = implode (' ', $columnList[$listKey] ?? []);
0 ignored issues
show
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
367
            }
368
        }
369
370
        return $list;
371
    }
372
373
    /**
374
     * @param array|null $list
375
     *
376
     * @return array|null
377
     */
378
    public function formatColumnText (?array &$list) {
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces before opening parenthesis; 1 found
Loading history...
Coding Style introduced by
Expected "function abc(...)"; found "function abc (...)"
Loading history...
379
        foreach ($list as $listKey => $listValue) {
380
            $formatArray = $this->getExportFormatFieldText ($listValue);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $formatArray is correct as $this->getExportFormatFieldText($listValue) targeting Zemit\Mvc\Controller\Res...ExportFormatFieldText() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Coding Style introduced by
Space before opening parenthesis of function call prohibited
Loading history...
381
            if ($formatArray) {
382
				$columNameList = array_keys($formatArray);
0 ignored issues
show
Bug introduced by
$formatArray of type void is incompatible with the type array expected by parameter $array of array_keys(). ( Ignorable by Annotation )

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

382
				$columNameList = array_keys(/** @scrutinizer ignore-type */ $formatArray);
Loading history...
383
                foreach ($formatArray as $formatKey => $formatValue) {
0 ignored issues
show
Bug introduced by
The expression $formatArray of type void is not traversable.
Loading history...
384
                    if (isset($formatValue['text'])) {
385
                        $list[$listKey][$formatKey] = $formatValue['text'];
386
                    }
387
388
                    if (isset($formatValue['rename'])) {
389
390
                        $list[$listKey][$formatValue['rename']] = $formatValue['text'] ?? ($list[$listKey][$formatKey] ?? null);
391
                        if ($formatValue['rename'] !== $formatKey) {
392
                            foreach ($columNameList as $columnKey => $columnValue) {
393
394
                                if ($formatKey === $columnValue) {
395
                                    $columNameList[$columnKey] = $formatValue['rename'];
396
                                }
397
                            }
398
399
                            unset($list[$listKey][$formatKey]);
400
                        }
401
                    }
402
                }
403
404
                if (isset($formatArray['reorder']) && $formatArray['reorder']) {
405
                    $list[$listKey] = $this->arrayCustomOrder($list[$listKey], $columNameList);
406
                }
407
            }
408
        }
409
410
        return $list;
411
    }
412
413
    /**
414
     * @param array $arrayToOrder
415
     * @param array $orderList
416
     *
417
     * @return array
418
     */
419
    function arrayCustomOrder($arrayToOrder, $orderList) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for arrayCustomOrder.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
420
        $ordered = array();
421
        foreach ($orderList as $key) {
422
            if (isset($arrayToOrder[$key])) {
423
                $ordered[$key] = $arrayToOrder[$key];
424
            }
425
        }
426
        return $ordered;
427
    }
428
429
    /**
430
     * Count a record list
431
     * @TODO add total count / deleted count / active count
432
     *
433
     * @return \Phalcon\Http\ResponseInterface
434
     */
435
    public function countAction()
436
    {
437
        $model = $this->getModelClassName();
438
        
439
        /** @var \Zemit\Mvc\Model $entity */
440
        $entity = new $model();
441
        
442
        $this->view->totalCount = $model::count($this->getFindCount($this->getFind()));
443
        $this->view->totalCount = is_int($this->view->totalCount)? $this->view->totalCount : count($this->view->totalCount);
444
        $this->view->model = get_class($entity);
445
        $this->view->source = $entity->getSource();
446
        
447
        return $this->setRestResponse();
448
    }
449
    
450
    /**
451
     * Prepare a new model for the frontend
452
     *
453
     * @return \Phalcon\Http\ResponseInterface
454
     */
455
    public function newAction()
456
    {
457
        $model = $this->getModelClassName();
458
        
459
        /** @var \Zemit\Mvc\Model $entity */
460
        $entity = new $model();
461
        $entity->assign($this->getParams(), $this->getWhiteList(), $this->getColumnMap());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getColumnMap() targeting Zemit\Mvc\Controller\Rest::getColumnMap() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure the usage of $this->getWhiteList() targeting Zemit\Mvc\Controller\Rest::getWhiteList() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
462
        
463
        $this->view->model = get_class($entity);
464
        $this->view->source = $entity->getSource();
465
        $this->view->single = $entity->expose($this->getExpose());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getExpose() targeting Zemit\Mvc\Controller\Rest::getExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
466
        
467
        return $this->setRestResponse();
468
    }
469
    
470
    /**
471
     * Prepare a new model for the frontend
472
     *
473
     * @return \Phalcon\Http\ResponseInterface
474
     */
475
    public function validateAction($id = null)
476
    {
477
        $model = $this->getModelClassName();
478
        
479
        /** @var \Zemit\Mvc\Model $entity */
480
        $entity = $this->getSingle($id);
481
        $new = !$entity;
0 ignored issues
show
introduced by
$entity is of type Zemit\Mvc\Model, thus it always evaluated to true.
Loading history...
482
        
483
        if ($new) {
0 ignored issues
show
introduced by
The condition $new is always false.
Loading history...
484
            $entity = new $model();
485
        }
486
        
487
        $entity->assign($this->getParams(), $this->getWhiteList(), $this->getColumnMap());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getWhiteList() targeting Zemit\Mvc\Controller\Rest::getWhiteList() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Bug introduced by
Are you sure the usage of $this->getColumnMap() targeting Zemit\Mvc\Controller\Rest::getColumnMap() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
488
        
489
        /**
490
         * Event to run
491
         * @see https://docs.phalcon.io/4.0/en/db-models-events
492
         */
493
        $events = [
494
            'beforeCreate' => null,
495
            'beforeUpdate' => null,
496
            'beforeSave' => null,
497
            'beforeValidationOnCreate' => null,
498
            'beforeValidationOnUpdate' => null,
499
            'beforeValidation' => null,
500
            'prepareSave' => null,
501
            'validation' => null,
502
            'afterValidationOnCreate' => null,
503
            'afterValidationOnUpdate' => null,
504
            'afterValidation' => null,
505
        ];
506
        
507
        // run events, as it would normally
508
        foreach ($events as $event => $state) {
509
            $this->skipped = false;
0 ignored issues
show
Bug Best Practice introduced by
The property skipped does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
510
            
511
            // skip depending wether it's a create or update
512
            if (strpos($event, $new ? 'Update' : 'Create') !== false) {
513
                continue;
514
            }
515
            
516
            // fire the event, allowing to fail or skip
517
            $events[$event] = $entity->fireEventCancel($event);
518
            if ($events[$event] === false) {
519
                // event failed
520
                break;
521
            }
522
            
523
            // event was skipped, just for consistencies purpose
524
            if ($this->skipped) {
525
                continue;
526
            }
527
        }
528
        
529
        $this->view->model = get_class($entity);
530
        $this->view->source = $entity->getSource();
531
        $this->view->single = $entity->expose($this->getExpose());
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getExpose() targeting Zemit\Mvc\Controller\Rest::getExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
532
        $this->view->messages = $entity->getMessages();
533
        $this->view->events = $events;
534
        $this->view->validated = empty($this->view->messages);
535
        
536
        return $this->setRestResponse($this->view->validated);
0 ignored issues
show
Bug introduced by
$this->view->validated of type boolean is incompatible with the type array|null expected by parameter $response of Zemit\Mvc\Controller\Rest::setRestResponse(). ( Ignorable by Annotation )

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

536
        return $this->setRestResponse(/** @scrutinizer ignore-type */ $this->view->validated);
Loading history...
537
    }
538
    
539
    /**
540
     * Saving a record
541
     * - Create
542
     * - Update
543
     *
544
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
545
     *
546
     * @return array
547
     */
548
    public function saveAction($id = null)
549
    {
550
        $this->view->setVars($this->save($id));
0 ignored issues
show
Bug introduced by
The method setVars() does not exist on Phalcon\Mvc\ViewInterface. Did you maybe mean setVar()? ( Ignorable by Annotation )

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

550
        $this->view->/** @scrutinizer ignore-call */ 
551
                     setVars($this->save($id));

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...
551
        
552
        return $this->setRestResponse($this->view->saved);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->setRestResponse($this->view->saved) returns the type Phalcon\Http\ResponseInterface which is incompatible with the documented return type array.
Loading history...
553
    }
554
    
555
    /**
556
     * Deleting a record
557
     *
558
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
559
     *
560
     * @return bool
561
     */
562
    public function deleteAction($id = null)
563
    {
564
        $single = $this->getSingle($id);
565
        
566
        $this->view->deleted = $single ? $single->delete() : false;
567
        $this->view->single = $single ? $single->expose($this->getExpose()) : false;
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getExpose() targeting Zemit\Mvc\Controller\Rest::getExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
568
        $this->view->messages = $single ? $single->getMessages() : false;
569
        
570
        if (!$single) {
571
            $this->response->setStatusCode(404, 'Not Found');
572
            
573
            return false;
574
        }
575
        
576
        return $this->setRestResponse($this->view->deleted);
0 ignored issues
show
Bug introduced by
$this->view->deleted of type boolean is incompatible with the type array|null expected by parameter $response of Zemit\Mvc\Controller\Rest::setRestResponse(). ( Ignorable by Annotation )

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

576
        return $this->setRestResponse(/** @scrutinizer ignore-type */ $this->view->deleted);
Loading history...
Bug Best Practice introduced by
The expression return $this->setRestRes...e($this->view->deleted) returns the type Phalcon\Http\ResponseInterface which is incompatible with the documented return type boolean.
Loading history...
577
    }
578
    
579
    /**
580
     * Restoring record
581
     *
582
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
583
     *
584
     * @return bool
585
     */
586
    public function restoreAction($id = null)
587
    {
588
        $single = $this->getSingle($id);
589
        
590
        $this->view->restored = $single ? $single->restore() : false;
0 ignored issues
show
Bug introduced by
The method restore() does not exist on Phalcon\Mvc\Model\Resultset. ( Ignorable by Annotation )

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

590
        $this->view->restored = $single ? $single->/** @scrutinizer ignore-call */ restore() : false;

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...
591
        $this->view->single = $single ? $single->expose($this->getExpose()) : false;
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getExpose() targeting Zemit\Mvc\Controller\Rest::getExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
592
        $this->view->messages = $single ? $single->getMessages() : false;
593
        
594
        if (!$single) {
595
            $this->response->setStatusCode(404, 'Not Found');
596
            
597
            return false;
598
        }
599
        
600
        return $this->setRestResponse($this->view->restored);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->setRestRes...($this->view->restored) returns the type Phalcon\Http\ResponseInterface which is incompatible with the documented return type boolean.
Loading history...
Bug introduced by
It seems like $this->view->restored can also be of type false; however, parameter $response of Zemit\Mvc\Controller\Rest::setRestResponse() does only seem to accept array|null, 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

600
        return $this->setRestResponse(/** @scrutinizer ignore-type */ $this->view->restored);
Loading history...
601
    }
602
    
603
    /**
604
     * Re-ordering a position
605
     *
606
     * @param null $id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $id is correct as it would always require null to be passed?
Loading history...
607
     * @param null $position
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $position is correct as it would always require null to be passed?
Loading history...
608
     *
609
     * @return bool|\Phalcon\Http\ResponseInterface
610
     */
611
    public function reorderAction($id = null)
612
    {
613
        $single = $this->getSingle($id);
614
        
615
        $position = $this->getParam('position', 'int');
616
        
617
        $this->view->reordered = $single ? $single->reorder($position) : false;
0 ignored issues
show
Bug introduced by
The method reorder() does not exist on Phalcon\Mvc\Model\Resultset. ( Ignorable by Annotation )

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

617
        $this->view->reordered = $single ? $single->/** @scrutinizer ignore-call */ reorder($position) : false;

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...
618
        $this->view->single = $single ? $single->expose($this->getExpose()) : false;
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->getExpose() targeting Zemit\Mvc\Controller\Rest::getExpose() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
619
        $this->view->messages = $single ? $single->getMessages() : false;
620
        
621
        if (!$single) {
622
            $this->response->setStatusCode(404, 'Not Found');
623
            
624
            return false;
625
        }
626
        
627
        return $this->setRestResponse($this->view->reordered);
0 ignored issues
show
Bug introduced by
It seems like $this->view->reordered can also be of type false; however, parameter $response of Zemit\Mvc\Controller\Rest::setRestResponse() does only seem to accept array|null, 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

627
        return $this->setRestResponse(/** @scrutinizer ignore-type */ $this->view->reordered);
Loading history...
628
    }
629
    
630
    /**
631
     * Sending an error as an http response
632
     *
633
     * @param null $error
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $error is correct as it would always require null to be passed?
Loading history...
634
     * @param null $response
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $response is correct as it would always require null to be passed?
Loading history...
635
     *
636
     * @return \Phalcon\Http\ResponseInterface
637
     */
638
    public function setRestErrorResponse($code = 400, $status = 'Bad Request', $response = null)
639
    {
640
        return $this->setRestResponse($response, $code, $status);
641
    }
642
    
643
    /**
644
     * Sending rest response as an http response
645
     *
646
     * @param array|null $response
647
     * @param null $status
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $status is correct as it would always require null to be passed?
Loading history...
648
     * @param null $code
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $code is correct as it would always require null to be passed?
Loading history...
649
     * @param int $jsonOptions
650
     * @param int $depth
651
     *
652
     * @return \Phalcon\Http\ResponseInterface
653
     */
654
    public function setRestResponse($response = null, $code = null, $status = null, $jsonOptions = 0, $depth = 512)
655
    {
656
        $debug = $this->config->app->debug ?? false;
0 ignored issues
show
Bug Best Practice introduced by
The property app does not exist on Zemit\Bootstrap\Config. Since you implemented __get, consider adding a @property annotation.
Loading history...
657
        
658
        // keep forced status code or set our own
659
        $responseStatusCode = $this->response->getStatusCode();
660
        $reasonPhrase = $this->response->getReasonPhrase();
661
        $status ??= $reasonPhrase ? : 'OK';
662
        $code ??= (int)$responseStatusCode ? : 200;
663
        $view = $this->view->getParamsToView();
664
        $hash = hash('sha512', json_encode($view));
665
        
666
        /**
667
         * Debug section
668
         * - Versions
669
         * - Request
670
         * - Identity
671
         * - Profiler
672
         * - Dispatcher
673
         * - Router
674
         */
675
        $request = $debug ? $this->request->toArray() : null;
0 ignored issues
show
Bug introduced by
The method toArray() does not exist on Phalcon\Http\RequestInterface. It seems like you code against a sub-type of Phalcon\Http\RequestInterface such as Zemit\Http\Request. ( Ignorable by Annotation )

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

675
        $request = $debug ? $this->request->/** @scrutinizer ignore-call */ toArray() : null;
Loading history...
introduced by
The method toArray() does not exist on Phalcon\Http\Request. Are you sure you never get this type here, but always one of the subclasses? ( Ignorable by Annotation )

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

675
        $request = $debug ? $this->request->/** @scrutinizer ignore-call */ toArray() : null;
Loading history...
676
        $identity = $debug ? $this->identity->getIdentity() : null;
677
        $profiler = $debug && $this->profiler ? $this->profiler->toArray() : null;
678
        $dispatcher = $debug ? $this->dispatcher->toArray() : null;
679
        $router = $debug ? $this->router->toArray() : null;
680
        
681
        $api = $debug ? [
682
            'php' => phpversion(),
683
            'phalcon' => Version::get(),
684
            'zemit' => $this->config->core->version,
0 ignored issues
show
Bug Best Practice introduced by
The property core does not exist on Zemit\Bootstrap\Config. Since you implemented __get, consider adding a @property annotation.
Loading history...
685
            'core' => $this->config->core->name,
686
            'app' => $this->config->app->version,
687
            'name' => $this->config->app->name,
688
        ] : [];
689
        $api['version'] = '0.1';
690
        
691
        $this->response->setStatusCode($code, $code . ' ' . $status);
692
        
693
        // @todo handle this correctly
694
        // @todo private vs public cache type
695
        $cache = $this->getCache();
696
        if (!empty($cache['lifetime'])) {
697
            if ($this->response->getStatusCode() === 200) {
698
                $this->response->setCache($cache['lifetime']);
699
                $this->response->setEtag($hash);
700
            }
701
        } else {
702
            $this->response->setCache(0);
703
            $this->response->setHeader('Cache-Control', 'no-cache, max-age=0');
704
        }
705
        
706
        return $this->response->setJsonContent(array_merge([
707
            'api' => $api,
708
            'timestamp' => date('c'),
709
            'hash' => $hash,
710
            'status' => $status,
711
            'code' => $code,
712
            'response' => $response,
713
            'view' => $view,
714
        ], $debug ? [
715
            'identity' => $identity,
716
            'profiler' => $profiler,
717
            'request' => $request,
718
            'dispatcher' => $dispatcher,
719
            'router' => $router,
720
        ] : []), $jsonOptions, $depth);
0 ignored issues
show
Unused Code introduced by
The call to Phalcon\Http\ResponseInterface::setJsonContent() has too many arguments starting with $jsonOptions. ( Ignorable by Annotation )

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

720
        return $this->response->/** @scrutinizer ignore-call */ setJsonContent(array_merge([

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...
721
    }
722
    
723
    /**
724
     * Handle rest response automagically
725
     *
726
     * @param Dispatcher $dispatcher
727
     */
728
    public function afterExecuteRoute(Dispatcher $dispatcher)
729
    {
730
        $response = $dispatcher->getReturnedValue();
731
        
732
        // Avoid breaking default phalcon behaviour
733
        if ($response instanceof Response) {
734
            return;
735
        }
736
        
737
        // Merge response into view variables
738
        if (is_array($response)) {
739
            $this->view->setVars($response, true);
740
        }
741
        
742
        // Return our Rest normalized response
743
        $dispatcher->setReturnedValue($this->setRestResponse(is_array($response) ? null : $response));
744
    }
745
}
746