|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Canvas\Contracts\Controllers; |
|
6
|
|
|
|
|
7
|
|
|
use Canvas\Exception\ServerErrorHttpException; |
|
8
|
|
|
use AutoMapperPlus\DataType; |
|
9
|
|
|
use StdClass; |
|
10
|
|
|
|
|
11
|
|
|
trait ProcessOutputMapperTrait |
|
12
|
|
|
{ |
|
13
|
|
|
protected $dto = null; |
|
14
|
|
|
protected $dtoMapper = null; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* Format Controller Result base on a Mapper. |
|
18
|
|
|
* |
|
19
|
|
|
* @param mixed $results |
|
20
|
|
|
* @return void |
|
21
|
|
|
*/ |
|
22
|
|
|
protected function processOutput($results) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->canUseMapper(); |
|
25
|
|
|
|
|
26
|
|
|
//if we have relationships we use StdClass to allow use to overwrite the array as we see fit in the Dto |
|
27
|
|
|
if ($this->request->hasQuery('relationships')) { |
|
28
|
|
|
$mapperModel = DataType::ARRAY; |
|
29
|
|
|
$this->dto = StdClass::class; |
|
30
|
|
|
} else { |
|
31
|
|
|
$mapperModel = get_class($this->model); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
$this->dtoConfig->registerMapping($mapperModel, $this->dto) |
|
35
|
|
|
->useCustomMapper($this->dtoMapper); |
|
36
|
|
|
|
|
37
|
|
|
if (is_array($results) && isset($results['data'])) { |
|
38
|
|
|
$results['data'] = $this->mapper->mapMultiple($results['data'], $this->dto); |
|
39
|
|
|
return $results; |
|
|
|
|
|
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* If position 0 is array or object it means is a result set from normal query |
|
44
|
|
|
* or with relationships therefore we use multimap. |
|
45
|
|
|
*/ |
|
46
|
|
|
return is_iterable($results) && (is_array(current($results)) || is_object(current($results))) ? |
|
47
|
|
|
$this->mapper->mapMultiple($results, $this->dto, $this->getMapperOptions()) |
|
48
|
|
|
: $this->mapper->map($results, $this->dto, $this->getMapperOptions()); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
/** |
|
52
|
|
|
* Can we use the mapper on this request? |
|
53
|
|
|
* |
|
54
|
|
|
* @return boolean |
|
55
|
|
|
*/ |
|
56
|
|
|
protected function canUseMapper(): bool |
|
57
|
|
|
{ |
|
58
|
|
|
if (!is_object($this->model) || empty($this->dto)) { |
|
59
|
|
|
throw new ServerErrorHttpException('No Mapper configured on this controller ' . get_class($this)); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
return true; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* If we have relationships send them as addicontal context to the mapper. |
|
67
|
|
|
* |
|
68
|
|
|
* @return array |
|
69
|
|
|
*/ |
|
70
|
|
|
protected function getMapperOptions(): array |
|
71
|
|
|
{ |
|
72
|
|
|
if ($this->request->hasQuery('relationships')) { |
|
73
|
|
|
return [ |
|
74
|
|
|
'relationships' => explode(',', $this->request->getQuery('relationships')) |
|
75
|
|
|
]; |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
|
|
return []; |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|