1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Zemit Framework. |
5
|
|
|
* |
6
|
|
|
* (c) Zemit Team <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE.txt |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Zemit\Mvc\Controller; |
13
|
|
|
|
14
|
|
|
use League\Csv\CharsetConverter; |
15
|
|
|
use League\Csv\Writer; |
16
|
|
|
use Phalcon\Events\Manager; |
17
|
|
|
use Phalcon\Exception; |
18
|
|
|
use Phalcon\Http\Response; |
19
|
|
|
use Phalcon\Http\ResponseInterface; |
20
|
|
|
use Phalcon\Mvc\Dispatcher; |
21
|
|
|
use Phalcon\Mvc\ModelInterface; |
22
|
|
|
use Phalcon\Version; |
23
|
|
|
use Zemit\Di\Injectable; |
24
|
|
|
use Zemit\Http\StatusCode; |
|
|
|
|
25
|
|
|
use Zemit\Utils; |
26
|
|
|
use Zemit\Utils\Slug; |
27
|
|
|
|
28
|
|
|
class Rest extends \Zemit\Mvc\Controller |
29
|
|
|
{ |
30
|
|
|
use Model; |
|
|
|
|
31
|
|
|
use Rest\Fractal; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @throws Exception |
35
|
|
|
*/ |
36
|
|
|
public function indexAction(?int $id = null) |
37
|
|
|
{ |
38
|
|
|
$this->restForwarding($id); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Rest bootstrap forwarding |
43
|
|
|
* @throws Exception |
44
|
|
|
*/ |
45
|
|
|
protected function restForwarding(?int $id = null): void |
46
|
|
|
{ |
47
|
|
|
$id ??= $this->getParam('id'); |
48
|
|
|
if ($this->request->isPost() || $this->request->isPut() || $this->request->isPatch()) { |
49
|
|
|
$this->dispatcher->forward(['action' => 'save']); |
50
|
|
|
} |
51
|
|
|
elseif ($this->request->isDelete()) { |
52
|
|
|
$this->dispatcher->forward(['action' => 'delete']); |
53
|
|
|
} |
54
|
|
|
elseif ($this->request->isGet()) { |
55
|
|
|
if (is_null($id)) { |
56
|
|
|
$this->dispatcher->forward(['action' => 'getList']); |
57
|
|
|
} |
58
|
|
|
else { |
59
|
|
|
$this->dispatcher->forward(['action' => 'get']); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Retrieving a single record |
66
|
|
|
* Alias of method getAction() |
67
|
|
|
* |
68
|
|
|
* @param null $id |
|
|
|
|
69
|
|
|
* @return bool|ResponseInterface |
70
|
|
|
* @deprecated Should use getAction() method instead |
71
|
|
|
*/ |
72
|
|
|
public function getSingleAction($id = null) |
73
|
|
|
{ |
74
|
|
|
return $this->getAction($id); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Retrieving a single record |
79
|
|
|
* |
80
|
|
|
* @param null $id |
|
|
|
|
81
|
|
|
* |
82
|
|
|
* @return bool|ResponseInterface |
83
|
|
|
*/ |
84
|
|
|
public function getAction($id = null) |
85
|
|
|
{ |
86
|
|
|
$modelName = $this->getModelClassName(); |
87
|
|
|
$single = $this->getSingle($id, $modelName, null); |
88
|
|
|
|
89
|
|
|
$ret = []; |
90
|
|
|
$ret['single'] = $single ? $this->expose($single) : false; |
91
|
|
|
$ret['model'] = $modelName; |
92
|
|
|
$ret['source'] = $single ? $single->getSource() : false; |
|
|
|
|
93
|
|
|
$this->view->setVars($ret); |
|
|
|
|
94
|
|
|
|
95
|
|
|
if (!$single) { |
96
|
|
|
$this->response->setStatusCode(404, 'Not Found'); |
97
|
|
|
return false; |
98
|
|
|
} |
99
|
|
|
|
100
|
|
|
return $this->setRestResponse((bool)$single); |
101
|
|
|
} |
102
|
|
|
|
103
|
|
|
/** |
104
|
|
|
* Retrieving a record list |
105
|
|
|
* Alias of method getListAction() |
106
|
|
|
* |
107
|
|
|
* @return ResponseInterface |
108
|
|
|
* @throws \Exception |
109
|
|
|
* @deprecated Should use getListAction() method instead |
110
|
|
|
*/ |
111
|
|
|
public function getAllAction() |
112
|
|
|
{ |
113
|
|
|
return $this->getListAction(); |
114
|
|
|
} |
115
|
|
|
|
116
|
|
|
/** |
117
|
|
|
* Retrieving a record list |
118
|
|
|
* |
119
|
|
|
* @return ResponseInterface |
120
|
|
|
* @throws \Exception |
121
|
|
|
*/ |
122
|
|
|
public function getListAction() |
123
|
|
|
{ |
124
|
|
|
$model = $this->getModelClassName(); |
125
|
|
|
|
126
|
|
|
$find = $this->getFind() ?: []; |
127
|
|
|
$with = $this->getListWith() ?: []; |
|
|
|
|
128
|
|
|
|
129
|
|
|
$resultset = $model::findWith($with, $find); |
130
|
|
|
$list = $this->listExpose($resultset); |
131
|
|
|
|
132
|
|
|
$ret = []; |
133
|
|
|
$ret['list'] = $list; |
134
|
|
|
$ret['listCount'] = count($list); |
135
|
|
|
$ret['totalCount'] = $model::find($this->getFindCount($find)); // @todo fix count to work with rollup when joins |
136
|
|
|
$ret['totalCount'] = is_int($ret['totalCount']) ? $ret['totalCount'] : count($ret['totalCount']); |
137
|
|
|
$ret['limit'] = $find['limit'] ?? null; |
138
|
|
|
$ret['offset'] = $find['offset'] ?? null; |
139
|
|
|
|
140
|
|
|
if ($this->isDebugEnabled()) { |
141
|
|
|
$ret['find'] = $find; |
142
|
|
|
$ret['with'] = $with; |
143
|
|
|
} |
144
|
|
|
|
145
|
|
|
$this->view->setVars($ret); |
146
|
|
|
|
147
|
|
|
return $this->setRestResponse((bool)$resultset); |
148
|
|
|
} |
149
|
|
|
|
150
|
|
|
/** |
151
|
|
|
* Exporting a record list into a CSV stream |
152
|
|
|
* |
153
|
|
|
* @return ResponseInterface|null |
154
|
|
|
* @throws \Exception |
155
|
|
|
*/ |
156
|
|
|
public function exportAction() |
157
|
|
|
{ |
158
|
|
|
$model = $this->getModelClassName(); |
159
|
|
|
$find = $this->getFind(); |
160
|
|
|
$with = $model::with($this->getExportWith() ?: [], $find ?: []); |
|
|
|
|
161
|
|
|
$list = $this->exportExpose($with); |
162
|
|
|
$this->flatternArrayForCsv($list); |
163
|
|
|
$this->formatColumnText($list); |
164
|
|
|
return $this->download($list); |
165
|
|
|
} |
166
|
|
|
|
167
|
|
|
/** |
168
|
|
|
* Download a JSON / CSV / XLSX |
169
|
|
|
* @param $list |
170
|
|
|
* @param $fileName |
171
|
|
|
* @param $contentType |
172
|
|
|
* @param $params |
173
|
|
|
* @return ResponseInterface|void |
174
|
|
|
* @throws \League\Csv\CannotInsertRecord |
175
|
|
|
* @throws \League\Csv\InvalidArgument |
176
|
|
|
* @throws \Zemit\Exception |
177
|
|
|
*/ |
178
|
|
|
public function download($list = [], $fileName = null, $contentType = null, $params = null) |
179
|
|
|
{ |
180
|
|
|
$params ??= $this->getParams(); |
181
|
|
|
$contentType ??= $this->getContentType(); |
182
|
|
|
$fileName ??= ucfirst(Slug::generate(basename(str_replace('\\', '/', $this->getModelClassName())))) . ' List (' . date('Y-m-d') . ')'; |
183
|
|
|
|
184
|
|
|
if ($contentType === 'json') { |
185
|
|
|
// $this->response->setJsonContent($list); |
186
|
|
|
$this->response->setContent(json_encode($list, JSON_PRETTY_PRINT, 2048)); |
187
|
|
|
$this->response->setContentType('application/json'); |
188
|
|
|
$this->response->setHeader('Content-disposition', 'attachment; filename="' . addslashes($fileName) . '.json"'); |
189
|
|
|
return $this->response->send(); |
190
|
|
|
} |
191
|
|
|
|
192
|
|
|
// CSV |
193
|
|
|
if ($contentType === 'csv') { |
194
|
|
|
|
195
|
|
|
// Get CSV custom request parameters |
196
|
|
|
$mode = $params['mode'] ?? null; |
197
|
|
|
$delimiter = $params['delimiter'] ?? null; |
198
|
|
|
$newline = $params['newline'] ?? null; |
199
|
|
|
$escape = $params['escape'] ?? null; |
200
|
|
|
$outputBOM = $params['outputBOM'] ?? null; |
201
|
|
|
$skipIncludeBOM = $params['skipIncludeBOM'] ?? null; |
202
|
|
|
|
203
|
|
|
// $csv = Writer::createFromFileObject(new \SplTempFileObject()); |
204
|
|
|
$csv = Writer::createFromStream(fopen('php://memory', 'r+')); |
205
|
|
|
|
206
|
|
|
// CSV - MS Excel on MacOS |
207
|
|
|
if ($mode === 'mac') { |
208
|
|
|
$csv->setOutputBOM(Writer::BOM_UTF16_LE); // utf-16 |
209
|
|
|
$csv->setDelimiter("\t"); // tabs separated |
210
|
|
|
$csv->setNewline("\r\n"); // new lines |
211
|
|
|
CharsetConverter::addTo($csv, 'UTF-8', 'UTF-16'); |
212
|
|
|
} |
213
|
|
|
|
214
|
|
|
// CSV - MS Excel on Windows |
215
|
|
|
else { |
216
|
|
|
$csv->setOutputBOM(Writer::BOM_UTF8); // utf-8 |
217
|
|
|
$csv->setDelimiter(','); // comma separated |
218
|
|
|
$csv->setNewline("\n"); // new line windows |
219
|
|
|
CharsetConverter::addTo($csv, 'UTF-8', 'UTF-8'); |
220
|
|
|
} |
221
|
|
|
|
222
|
|
|
// Apply forced params from request |
223
|
|
|
if (isset($outputBOM)) { |
224
|
|
|
$csv->setOutputBOM($outputBOM); |
225
|
|
|
} |
226
|
|
|
if (isset($delimiter)) { |
227
|
|
|
$csv->setDelimiter($delimiter); |
228
|
|
|
} |
229
|
|
|
if (isset($newline)) { |
230
|
|
|
$csv->setNewline($newline); |
231
|
|
|
} |
232
|
|
|
if (isset($escape)) { |
233
|
|
|
$csv->setEscape($escape); |
234
|
|
|
} |
235
|
|
|
if ($skipIncludeBOM) { |
236
|
|
|
$csv->skipInputBOM(); |
237
|
|
|
} |
238
|
|
|
else { |
239
|
|
|
$csv->includeInputBOM(); |
240
|
|
|
} |
241
|
|
|
|
242
|
|
|
// CSV |
243
|
|
|
if (isset($list[0])) { |
244
|
|
|
$csv->insertOne(array_keys($list[0])); |
245
|
|
|
$csv->insertAll($list); |
246
|
|
|
} |
247
|
|
|
$csv->output($fileName . '.csv'); |
248
|
|
|
die; |
|
|
|
|
249
|
|
|
} |
250
|
|
|
|
251
|
|
|
// XLSX |
252
|
|
|
if ($contentType === 'xlsx') { |
253
|
|
|
$xlsxArray = []; |
254
|
|
|
if (isset($list[0])) { |
255
|
|
|
$xlsxArray [] = array_keys($list[0]); |
256
|
|
|
} |
257
|
|
|
foreach ($list as $array) { |
258
|
|
|
$xlsxArray [] = array_values($array); |
259
|
|
|
} |
260
|
|
|
$xlsx = \SimpleXLSXGen::fromArray($xlsxArray); |
|
|
|
|
261
|
|
|
$xlsx->downloadAs($fileName . '.xlsx'); |
262
|
|
|
die; |
|
|
|
|
263
|
|
|
} |
264
|
|
|
|
265
|
|
|
// Something went wrong |
266
|
|
|
throw new \Exception('Failed to export `' . $this->getModelClassName() . '` using content-type `' . $contentType . '`', 400); |
267
|
|
|
} |
268
|
|
|
|
269
|
|
|
/** |
270
|
|
|
* Expose a single model |
271
|
|
|
*/ |
272
|
|
|
public function expose(ModelInterface $item, ?array $expose = null): array |
273
|
|
|
{ |
274
|
|
|
$expose ??= $this->getExpose(); |
|
|
|
|
275
|
|
|
return $item->expose($expose); |
|
|
|
|
276
|
|
|
} |
277
|
|
|
|
278
|
|
|
/** |
279
|
|
|
* Expose a list of model |
280
|
|
|
*/ |
281
|
|
|
public function listExpose(iterable $items, ?array $listExpose = null): array |
282
|
|
|
{ |
283
|
|
|
$listExpose ??= $this->getListExpose(); |
|
|
|
|
284
|
|
|
$ret = []; |
285
|
|
|
|
286
|
|
|
foreach ($items as $item) { |
287
|
|
|
$ret [] = $this->expose($item, $listExpose); |
288
|
|
|
} |
289
|
|
|
|
290
|
|
|
return $ret; |
291
|
|
|
} |
292
|
|
|
|
293
|
|
|
/** |
294
|
|
|
* Expose a list of model |
295
|
|
|
*/ |
296
|
|
|
public function exportExpose(iterable $items, $exportExpose = null): array |
297
|
|
|
{ |
298
|
|
|
$exportExpose ??= $this->getExportExpose(); |
|
|
|
|
299
|
|
|
return $this->listExpose($items, $exportExpose); |
300
|
|
|
} |
301
|
|
|
|
302
|
|
|
/** |
303
|
|
|
* @param array|null $array |
304
|
|
|
* |
305
|
|
|
* @return array|null |
306
|
|
|
*/ |
307
|
|
|
public function flatternArrayForCsv(?array &$list = null) |
308
|
|
|
{ |
309
|
|
|
|
310
|
|
|
foreach ($list as $listKey => $listValue) { |
311
|
|
|
foreach ($listValue as $column => $value) { |
312
|
|
|
if (is_array($value) || is_object($value)) { |
313
|
|
|
$value = $this->concatListFieldElementForCsv($value, ' '); |
|
|
|
|
314
|
|
|
$list[$listKey][$column] = $this->arrayFlatten($value, $column); |
315
|
|
|
if (is_array($list[$listKey][$column])) { |
316
|
|
|
foreach ($list[$listKey][$column] as $childKey => $childValue) { |
317
|
|
|
$list[$listKey][$childKey] = $childValue; |
318
|
|
|
unset($list[$listKey][$column]); |
319
|
|
|
} |
320
|
|
|
} |
321
|
|
|
} |
322
|
|
|
} |
323
|
|
|
} |
324
|
|
|
} |
325
|
|
|
|
326
|
|
|
public function concatListFieldElementForCsv(array $list = [], ?string $seperator = ' '): array |
327
|
|
|
{ |
328
|
|
|
foreach ($list as $valueKey => $element) { |
329
|
|
|
if (is_array($element) || is_object($element)) { |
330
|
|
|
$lastKey = array_key_last($list); |
331
|
|
|
if ($valueKey === $lastKey) { |
332
|
|
|
continue; |
333
|
|
|
} |
334
|
|
|
foreach ($element as $elKey => $elValue) { |
335
|
|
|
$list[$lastKey][$elKey] .= $seperator . $elValue; |
336
|
|
|
if ($lastKey != $valueKey) { |
337
|
|
|
unset($list[$valueKey]); |
338
|
|
|
} |
339
|
|
|
} |
340
|
|
|
} |
341
|
|
|
} |
342
|
|
|
|
343
|
|
|
return $list; |
344
|
|
|
} |
345
|
|
|
|
346
|
|
|
public function arrayFlatten(?array $array, ?string $alias = null): array |
347
|
|
|
{ |
348
|
|
|
$ret = []; |
349
|
|
|
foreach ($array as $key => $value) { |
350
|
|
|
if (is_array($value)) { |
351
|
|
|
$ret = array_merge($ret, $this->arrayFlatten($value, $alias)); |
352
|
|
|
} |
353
|
|
|
else { |
354
|
|
|
$ret[$alias . '.' . $key] = $value; |
355
|
|
|
} |
356
|
|
|
} |
357
|
|
|
return $ret; |
358
|
|
|
} |
359
|
|
|
|
360
|
|
|
/** |
361
|
|
|
* @param array|null $listValue |
362
|
|
|
* |
363
|
|
|
* @return array|null |
364
|
|
|
*/ |
365
|
|
|
public function mergeColumns(?array $listValue) |
366
|
|
|
{ |
367
|
|
|
$columnToMergeList = $this->getExportMergeColum(); |
|
|
|
|
368
|
|
|
if (!$columnToMergeList || empty($columnToMergeList)) { |
|
|
|
|
369
|
|
|
return $listValue; |
370
|
|
|
} |
371
|
|
|
|
372
|
|
|
$columnList = []; |
373
|
|
|
foreach ($columnToMergeList as $columnToMerge) { |
374
|
|
|
foreach ($columnToMerge['columns'] as $column) { |
375
|
|
|
if (isset($listValue[$column])) { |
376
|
|
|
$columnList[$columnToMerge['name']][] = $listValue[$column]; |
377
|
|
|
unset($listValue[$column]); |
378
|
|
|
} |
379
|
|
|
} |
380
|
|
|
$listValue[$columnToMerge['name']] = implode(' ', $columnList[$columnToMerge['name']] ?? []); |
381
|
|
|
} |
382
|
|
|
|
383
|
|
|
return $listValue; |
384
|
|
|
} |
385
|
|
|
|
386
|
|
|
/** |
387
|
|
|
* @param array|null $list |
388
|
|
|
* |
389
|
|
|
* @return array|null |
390
|
|
|
*/ |
391
|
|
|
public function formatColumnText(?array &$list) |
392
|
|
|
{ |
393
|
|
|
foreach ($list as $listKey => $listValue) { |
394
|
|
|
|
395
|
|
|
$mergeColumArray = $this->mergeColumns($listValue); |
396
|
|
|
if (!empty($mergeColumArray)) { |
397
|
|
|
$list[$listKey] = $mergeColumArray; |
398
|
|
|
} |
399
|
|
|
|
400
|
|
|
$formatArray = $this->getExportFormatFieldText($listValue); |
|
|
|
|
401
|
|
|
if ($formatArray) { |
402
|
|
|
$columNameList = array_keys($formatArray); |
|
|
|
|
403
|
|
|
foreach ($formatArray as $formatKey => $formatValue) { |
|
|
|
|
404
|
|
|
if (isset($formatValue['text'])) { |
405
|
|
|
$list[$listKey][$formatKey] = $formatValue['text']; |
406
|
|
|
} |
407
|
|
|
|
408
|
|
|
if (isset($formatValue['rename'])) { |
409
|
|
|
|
410
|
|
|
$list[$listKey][$formatValue['rename']] = $formatValue['text'] ?? ($list[$listKey][$formatKey] ?? null); |
411
|
|
|
if ($formatValue['rename'] !== $formatKey) { |
412
|
|
|
foreach ($columNameList as $columnKey => $columnValue) { |
413
|
|
|
|
414
|
|
|
if ($formatKey === $columnValue) { |
415
|
|
|
$columNameList[$columnKey] = $formatValue['rename']; |
416
|
|
|
} |
417
|
|
|
} |
418
|
|
|
|
419
|
|
|
unset($list[$listKey][$formatKey]); |
420
|
|
|
} |
421
|
|
|
} |
422
|
|
|
} |
423
|
|
|
|
424
|
|
|
if (isset($formatArray['reorderColumns']) && $formatArray['reorderColumns']) { |
425
|
|
|
$list[$listKey] = $this->arrayCustomOrder($list[$listKey], $columNameList); |
426
|
|
|
} |
427
|
|
|
} |
428
|
|
|
} |
429
|
|
|
|
430
|
|
|
return $list; |
431
|
|
|
} |
432
|
|
|
|
433
|
|
|
public function arrayCustomOrder(array $arrayToOrder, array $orderList): array |
434
|
|
|
{ |
435
|
|
|
$ordered = []; |
436
|
|
|
foreach ($orderList as $key) { |
437
|
|
|
if (array_key_exists($key, $arrayToOrder)) { |
438
|
|
|
$ordered[$key] = $arrayToOrder[$key]; |
439
|
|
|
} |
440
|
|
|
} |
441
|
|
|
return $ordered; |
442
|
|
|
} |
443
|
|
|
|
444
|
|
|
/** |
445
|
|
|
* Count a record list |
446
|
|
|
* @TODO add total count / deleted count / active count |
447
|
|
|
* |
448
|
|
|
* @return ResponseInterface |
449
|
|
|
*/ |
450
|
|
|
public function countAction() |
451
|
|
|
{ |
452
|
|
|
$model = $this->getModelClassName(); |
453
|
|
|
|
454
|
|
|
/** @var \Zemit\Mvc\Model $entity */ |
455
|
|
|
$entity = new $model(); |
456
|
|
|
|
457
|
|
|
$ret = []; |
458
|
|
|
$ret['totalCount'] = $model::count($this->getFindCount($this->getFind())); |
459
|
|
|
$ret['totalCount'] = is_int($ret['totalCount']) ? $ret['totalCount'] : count($ret['totalCount']); |
460
|
|
|
$ret['model'] = get_class($entity); |
461
|
|
|
$ret['source'] = $entity->getSource(); |
462
|
|
|
$this->view->setVars($ret); |
463
|
|
|
|
464
|
|
|
return $this->setRestResponse(); |
465
|
|
|
} |
466
|
|
|
|
467
|
|
|
/** |
468
|
|
|
* Prepare a new model for the frontend |
469
|
|
|
* |
470
|
|
|
* @return ResponseInterface |
471
|
|
|
*/ |
472
|
|
|
public function newAction() |
473
|
|
|
{ |
474
|
|
|
$model = $this->getModelClassName(); |
475
|
|
|
|
476
|
|
|
/** @var \Zemit\Mvc\Model $entity */ |
477
|
|
|
$entity = new $model(); |
478
|
|
|
$entity->assign($this->getParams(), $this->getWhiteList(), $this->getColumnMap()); |
|
|
|
|
479
|
|
|
|
480
|
|
|
$this->view->model = get_class($entity); |
481
|
|
|
$this->view->source = $entity->getSource(); |
482
|
|
|
$this->view->single = $this->expose($entity); |
483
|
|
|
|
484
|
|
|
return $this->setRestResponse(); |
485
|
|
|
} |
486
|
|
|
|
487
|
|
|
/** |
488
|
|
|
* Prepare a new model for the frontend |
489
|
|
|
* |
490
|
|
|
* @return ResponseInterface |
491
|
|
|
*/ |
492
|
|
|
public function validateAction($id = null) |
493
|
|
|
{ |
494
|
|
|
$model = $this->getModelClassName(); |
495
|
|
|
|
496
|
|
|
/** @var \Zemit\Mvc\Model $entity */ |
497
|
|
|
$entity = $this->getSingle($id); |
498
|
|
|
$new = !$entity; |
|
|
|
|
499
|
|
|
|
500
|
|
|
if ($new) { |
|
|
|
|
501
|
|
|
$entity = new $model(); |
502
|
|
|
} |
503
|
|
|
|
504
|
|
|
$entity->assign($this->getParams(), $this->getWhiteList(), $this->getColumnMap()); |
|
|
|
|
505
|
|
|
|
506
|
|
|
/** |
507
|
|
|
* Event to run |
508
|
|
|
* @see https://docs.phalcon.io/4.0/en/db-models-events |
509
|
|
|
*/ |
510
|
|
|
$events = [ |
511
|
|
|
'beforeCreate' => null, |
512
|
|
|
'beforeUpdate' => null, |
513
|
|
|
'beforeSave' => null, |
514
|
|
|
'beforeValidationOnCreate' => null, |
515
|
|
|
'beforeValidationOnUpdate' => null, |
516
|
|
|
'beforeValidation' => null, |
517
|
|
|
'prepareSave' => null, |
518
|
|
|
'validation' => null, |
519
|
|
|
'afterValidationOnCreate' => null, |
520
|
|
|
'afterValidationOnUpdate' => null, |
521
|
|
|
'afterValidation' => null, |
522
|
|
|
]; |
523
|
|
|
|
524
|
|
|
// run events, as it would normally |
525
|
|
|
foreach ($events as $event => $state) { |
526
|
|
|
$this->skipped = false; |
|
|
|
|
527
|
|
|
|
528
|
|
|
// skip depending wether it's a create or update |
529
|
|
|
if (strpos($event, $new ? 'Update' : 'Create') !== false) { |
530
|
|
|
continue; |
531
|
|
|
} |
532
|
|
|
|
533
|
|
|
// fire the event, allowing to fail or skip |
534
|
|
|
$events[$event] = $entity->fireEventCancel($event); |
535
|
|
|
if ($events[$event] === false) { |
536
|
|
|
// event failed |
537
|
|
|
break; |
538
|
|
|
} |
539
|
|
|
|
540
|
|
|
// event was skipped, just for consistencies purpose |
541
|
|
|
if ($this->skipped) { |
542
|
|
|
continue; |
543
|
|
|
} |
544
|
|
|
} |
545
|
|
|
|
546
|
|
|
$ret = []; |
547
|
|
|
$ret['model'] = get_class($entity); |
548
|
|
|
$ret['source'] = $entity->getSource(); |
549
|
|
|
$ret['single'] = $this->expose($entity); |
550
|
|
|
$ret['messages'] = $entity->getMessages(); |
551
|
|
|
$ret['events'] = $events; |
552
|
|
|
$ret['validated'] = empty($this->view->messages); |
553
|
|
|
$this->view->setVars($ret); |
554
|
|
|
|
555
|
|
|
return $this->setRestResponse($ret['validated']); |
556
|
|
|
} |
557
|
|
|
|
558
|
|
|
/** |
559
|
|
|
* Saving a record (create & update) |
560
|
|
|
*/ |
561
|
|
|
public function saveAction(?int $id = null): ?ResponseInterface |
562
|
|
|
{ |
563
|
|
|
$ret = $this->save($id); |
564
|
|
|
$this->view->setVars($ret); |
565
|
|
|
$saved = $this->saveResultHasKey($ret, 'saved'); |
566
|
|
|
$messages = $this->saveResultHasKey($ret, 'messages'); |
567
|
|
|
|
568
|
|
|
if (!$saved) { |
569
|
|
|
if (!$messages) { |
570
|
|
|
$this->response->setStatusCode(422, 'Unprocessable Entity'); |
571
|
|
|
} |
572
|
|
|
else { |
573
|
|
|
$this->response->setStatusCode(400, 'Bad Request'); |
574
|
|
|
} |
575
|
|
|
} |
576
|
|
|
|
577
|
|
|
return $this->setRestResponse($saved); |
578
|
|
|
} |
579
|
|
|
|
580
|
|
|
/** |
581
|
|
|
* Return true if the record or the records where saved |
582
|
|
|
* Return false if one record wasn't saved |
583
|
|
|
* Return null if nothing was saved |
584
|
|
|
*/ |
585
|
|
|
public function saveResultHasKey(array $array, string $key): bool |
586
|
|
|
{ |
587
|
|
|
$ret = $array[$key] ?? null; |
588
|
|
|
|
589
|
|
|
if (isset($array[0])) { |
590
|
|
|
foreach ($array as $k => $r) { |
591
|
|
|
if (isset($r[$key])) { |
592
|
|
|
if ($r[$key]) { |
593
|
|
|
$ret = true; |
594
|
|
|
} |
595
|
|
|
else { |
596
|
|
|
$ret = false; |
597
|
|
|
break; |
598
|
|
|
} |
599
|
|
|
} |
600
|
|
|
} |
601
|
|
|
} |
602
|
|
|
|
603
|
|
|
return (bool)$ret; |
604
|
|
|
} |
605
|
|
|
|
606
|
|
|
/** |
607
|
|
|
* Deleting a record |
608
|
|
|
*/ |
609
|
|
|
public function deleteAction(?int $id = null): ?ResponseInterface |
610
|
|
|
{ |
611
|
|
|
$entity = $this->getSingle($id); |
612
|
|
|
|
613
|
|
|
$ret = []; |
614
|
|
|
$ret['deleted'] = $entity && $entity->delete(); |
615
|
|
|
$ret['single'] = $entity ? $this->expose($entity) : false; |
616
|
|
|
$ret['messages'] = $entity ? $entity->getMessages() : false; |
617
|
|
|
$this->view->setVars($ret); |
618
|
|
|
|
619
|
|
|
if (!$entity) { |
620
|
|
|
$this->response->setStatusCode(404, 'Not Found'); |
621
|
|
|
} |
622
|
|
|
|
623
|
|
|
return $this->setRestResponse($ret['deleted']); |
624
|
|
|
} |
625
|
|
|
|
626
|
|
|
/** |
627
|
|
|
* Restoring record |
628
|
|
|
* |
629
|
|
|
* @param null $id |
|
|
|
|
630
|
|
|
* |
631
|
|
|
* @return bool|ResponseInterface |
632
|
|
|
*/ |
633
|
|
|
public function restoreAction($id = null) |
634
|
|
|
{ |
635
|
|
|
$entity = $this->getSingle($id); |
636
|
|
|
|
637
|
|
|
$ret = []; |
638
|
|
|
$ret['restored'] = $entity && $entity->restore(); |
|
|
|
|
639
|
|
|
$ret['single'] = $entity ? $this->expose($entity) : false; |
640
|
|
|
$ret['messages'] = $entity ? $entity->getMessages() : false; |
641
|
|
|
$this->view->setVars($ret); |
642
|
|
|
|
643
|
|
|
if (!$entity) { |
644
|
|
|
$this->response->setStatusCode(404, 'Not Found'); |
645
|
|
|
return false; |
646
|
|
|
} |
647
|
|
|
|
648
|
|
|
return $this->setRestResponse($ret['restored']); |
649
|
|
|
} |
650
|
|
|
|
651
|
|
|
/** |
652
|
|
|
* Re-ordering a position |
653
|
|
|
* |
654
|
|
|
* @param null $id |
|
|
|
|
655
|
|
|
* @param null $position |
|
|
|
|
656
|
|
|
* |
657
|
|
|
* @return bool|ResponseInterface |
658
|
|
|
*/ |
659
|
|
|
public function reorderAction($id = null, $position = null) |
660
|
|
|
{ |
661
|
|
|
$entity = $this->getSingle($id); |
662
|
|
|
$position = $this->getParam('position', 'int', $position); |
663
|
|
|
|
664
|
|
|
$ret = []; |
665
|
|
|
$ret['reordered'] = $entity ? $entity->reorder($position) : false; |
|
|
|
|
666
|
|
|
$ret['single'] = $entity ? $this->expose($entity) : false; |
667
|
|
|
$ret['messages'] = $entity ? $entity->getMessages() : false; |
668
|
|
|
$this->view->setVars($ret); |
669
|
|
|
|
670
|
|
|
if (!$entity) { |
671
|
|
|
$this->response->setStatusCode(404, 'Not Found'); |
672
|
|
|
return false; |
673
|
|
|
} |
674
|
|
|
|
675
|
|
|
return $this->setRestResponse($ret['reordered']); |
676
|
|
|
} |
677
|
|
|
|
678
|
|
|
/** |
679
|
|
|
* Sending an error as an http response |
680
|
|
|
* |
681
|
|
|
* @param null $error |
|
|
|
|
682
|
|
|
* @param null $response |
|
|
|
|
683
|
|
|
* |
684
|
|
|
* @return ResponseInterface |
685
|
|
|
*/ |
686
|
|
|
public function setRestErrorResponse($code = 400, $status = 'Bad Request', $response = null) |
687
|
|
|
{ |
688
|
|
|
return $this->setRestResponse($response, $code, $status); |
689
|
|
|
} |
690
|
|
|
|
691
|
|
|
/** |
692
|
|
|
* Sending rest response as an http response |
693
|
|
|
* |
694
|
|
|
* @param mixed $response |
695
|
|
|
* @param ?int $code |
696
|
|
|
* @param ?string $status |
697
|
|
|
* @param int $jsonOptions |
698
|
|
|
* @param int $depth |
699
|
|
|
* |
700
|
|
|
* @return ResponseInterface |
701
|
|
|
*/ |
702
|
|
|
public function setRestResponse($response = null, int $code = null, string $status = null, int $jsonOptions = 0, int $depth = 512): ResponseInterface |
703
|
|
|
{ |
704
|
|
|
$debug = $this->isDebugEnabled(); |
705
|
|
|
|
706
|
|
|
// keep forced status code or set our own |
707
|
|
|
$statusCode = $this->response->getStatusCode(); |
708
|
|
|
$reasonPhrase = $this->response->getReasonPhrase(); |
709
|
|
|
$code ??= (int)$statusCode ?: 200; |
710
|
|
|
$status ??= $reasonPhrase ?: StatusCode::getMessage($code); |
711
|
|
|
|
712
|
|
|
$view = $this->view->getParamsToView(); |
713
|
|
|
$hash = hash('sha512', json_encode($view)); |
714
|
|
|
|
715
|
|
|
// set response status code |
716
|
|
|
$this->response->setStatusCode($code, $code . ' ' . $status); |
717
|
|
|
|
718
|
|
|
// @todo handle this correctly |
719
|
|
|
// @todo private vs public cache type |
720
|
|
|
$cache = $this->getCache(); |
721
|
|
|
if (!empty($cache['lifetime'])) { |
722
|
|
|
if ($this->response->getStatusCode() === 200) { |
723
|
|
|
$this->response->setCache($cache['lifetime']); |
724
|
|
|
$this->response->setEtag($hash); |
725
|
|
|
} |
726
|
|
|
} |
727
|
|
|
else { |
728
|
|
|
$this->response->setCache(0); |
729
|
|
|
$this->response->setHeader('Cache-Control', 'no-cache, max-age=0'); |
730
|
|
|
} |
731
|
|
|
|
732
|
|
|
$ret = []; |
733
|
|
|
$ret['api'] = []; |
734
|
|
|
$ret['api']['version'] = ['0.1']; // @todo |
735
|
|
|
$ret['timestamp'] = date('c'); |
736
|
|
|
$ret['hash'] = $hash; |
737
|
|
|
$ret['status'] = $status; |
738
|
|
|
$ret['code'] = $code; |
739
|
|
|
$ret['response'] = $response; |
740
|
|
|
$ret['view'] = $view; |
741
|
|
|
|
742
|
|
|
if ($debug) { |
743
|
|
|
$ret['api']['php'] = phpversion(); |
744
|
|
|
$ret['api']['phalcon'] = Version::get(); |
745
|
|
|
$ret['api']['zemit'] = $this->config->path('core.version'); |
746
|
|
|
$ret['api']['core'] = $this->config->path('core.name'); |
747
|
|
|
$ret['api']['app'] = $this->config->path('app.version'); |
748
|
|
|
$ret['api']['name'] = $this->config->path('app.name'); |
749
|
|
|
|
750
|
|
|
$ret['identity'] = $this->identity ? $this->identity->getIdentity() : null; |
751
|
|
|
$ret['profiler'] = $this->profiler ? $this->profiler->toArray() : null; |
752
|
|
|
$ret['request'] = $this->request ? $this->request->toArray() : null; |
753
|
|
|
$ret['dispatcher'] = $this->dispatcher ? $this->dispatcher->toArray() : null; |
754
|
|
|
$ret['router'] = $this->router ? $this->router->toArray() : null; |
755
|
|
|
$ret['memory'] = Utils::getMemoryUsage(); |
756
|
|
|
} |
757
|
|
|
|
758
|
|
|
return $this->response->setJsonContent($ret, $jsonOptions, $depth); |
|
|
|
|
759
|
|
|
} |
760
|
|
|
|
761
|
|
|
public function beforeExecuteRoute(Dispatcher $dispatcher): void |
|
|
|
|
762
|
|
|
{ |
763
|
|
|
// @todo use eventsManager from service provider instead |
764
|
|
|
$this->eventsManager->enablePriorities(true); |
765
|
|
|
|
766
|
|
|
// @todo see if we can implement receiving an array of responses globally: V2 |
767
|
|
|
// $this->eventsManager->collectResponses(true); |
768
|
|
|
|
769
|
|
|
// retrieve events based on the config roles and features |
770
|
|
|
$permissions = $this->config->get('permissions')->toArray() ?? []; |
771
|
|
|
$featureList = $permissions['features'] ?? []; |
772
|
|
|
$roleList = $permissions['roles'] ?? []; |
773
|
|
|
|
774
|
|
|
foreach ($roleList as $role => $rolePermission) { |
775
|
|
|
|
776
|
|
|
if (isset($rolePermission['features'])) { |
777
|
|
|
foreach ($rolePermission['features'] as $feature) { |
778
|
|
|
$rolePermission = array_merge_recursive($rolePermission, $featureList[$feature] ?? []); |
779
|
|
|
// @todo remove duplicates |
780
|
|
|
} |
781
|
|
|
} |
782
|
|
|
|
783
|
|
|
$behaviorsContext = $rolePermission['behaviors'] ?? []; |
784
|
|
|
foreach ($behaviorsContext as $className => $behaviors) { |
785
|
|
|
if (is_int($className) || get_class($this) === $className) { |
786
|
|
|
$this->attachBehaviors($behaviors, 'rest'); |
787
|
|
|
} |
788
|
|
|
if ($this->getModelClassName() === $className) { |
789
|
|
|
$this->attachBehaviors($behaviors, 'model'); |
790
|
|
|
} |
791
|
|
|
} |
792
|
|
|
} |
793
|
|
|
} |
794
|
|
|
|
795
|
|
|
/** |
796
|
|
|
* Attach a new behavior |
797
|
|
|
* @todo review behavior type |
798
|
|
|
*/ |
799
|
|
|
public function attachBehavior(string $behavior, string $eventType = 'rest'): void |
800
|
|
|
{ |
801
|
|
|
$event = new $behavior(); |
802
|
|
|
|
803
|
|
|
// inject DI |
804
|
|
|
if ($event instanceof Injectable || method_exists($event, 'setDI')) { |
805
|
|
|
$event->setDI($this->getDI()); |
806
|
|
|
} |
807
|
|
|
|
808
|
|
|
// attach behavior |
809
|
|
|
$this->eventsManager->attach($event->eventType ?? $eventType, $event, $event->priority ?? Manager::DEFAULT_PRIORITY); |
|
|
|
|
810
|
|
|
} |
811
|
|
|
|
812
|
|
|
/** |
813
|
|
|
* Attach new behaviors |
814
|
|
|
*/ |
815
|
|
|
public function attachBehaviors(array $behaviors = [], string $eventType = 'rest'): void |
816
|
|
|
{ |
817
|
|
|
foreach ($behaviors as $behavior) { |
818
|
|
|
$this->attachBehavior($behavior, $eventType); |
819
|
|
|
} |
820
|
|
|
} |
821
|
|
|
|
822
|
|
|
/** |
823
|
|
|
* Handle rest response automagically |
824
|
|
|
*/ |
825
|
|
|
public function afterExecuteRoute(Dispatcher $dispatcher): void |
826
|
|
|
{ |
827
|
|
|
$response = $dispatcher->getReturnedValue(); |
828
|
|
|
|
829
|
|
|
// Avoid breaking default phalcon behaviour |
830
|
|
|
if ($response instanceof Response) { |
831
|
|
|
return; |
832
|
|
|
} |
833
|
|
|
|
834
|
|
|
// Merge response into view variables |
835
|
|
|
if (is_array($response)) { |
836
|
|
|
$this->view->setVars($response, true); |
837
|
|
|
} |
838
|
|
|
|
839
|
|
|
// Return our Rest normalized response |
840
|
|
|
$dispatcher->setReturnedValue($this->setRestResponse(is_array($response) ? null : $response)); |
841
|
|
|
} |
842
|
|
|
|
843
|
|
|
public function isDebugEnabled(): bool |
844
|
|
|
{ |
845
|
|
|
return $this->config->path('app.debug') ?? false; |
846
|
|
|
} |
847
|
|
|
} |
848
|
|
|
|
Let?s assume that you have a directory layout like this:
and let?s assume the following content of
Bar.php
:If both files
OtherDir/Foo.php
andSomeDir/Foo.php
are loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php
However, as
OtherDir/Foo.php
does not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php
, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: