-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathDtoMapper.php
More file actions
192 lines (173 loc) · 6.42 KB
/
DtoMapper.php
File metadata and controls
192 lines (173 loc) · 6.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 5.3.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM;
use Cake\ORM\Attribute\CollectionOf;
use ReflectionClass;
use ReflectionNamedType;
use ReflectionParameter;
/**
* Maps array data to DTO objects using reflection.
*
* This mapper enables the `projectAs()` query method to hydrate results
* directly into DTO objects instead of entities. It uses PHP 8 features:
*
* - **Type hints** on constructor parameters to detect nested DTOs
* - **#[CollectionOf]** attribute to specify DTO type for array collections
* - **Named arguments** for construction
*
* ### Example DTO
*
* ```php
* readonly class UserDto {
* public function __construct(
* public int $id,
* public string $username,
* public ?RoleDto $role = null,
* #[CollectionOf(CommentDto::class)]
* public array $comments = [],
* ) {}
* }
* ```
*
* ### Usage with Query
*
* ```php
* $users = $this->Users->find()
* ->contain(['Roles', 'Comments'])
* ->projectAs(UserDto::class)
* ->all();
* ```
*/
class DtoMapper
{
/**
* Cached reflection info per class.
*
* @var array<string, array{params: array<string, array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: class-string|null, collectionOf: class-string|null}>}>
*/
protected static array $cache = [];
/**
* Map array data to a DTO instance.
*
* @template T of object
* @param array<string, mixed> $data The source data (typically from ORM)
* @param class-string<T> $dtoClass The target DTO class
* @return T
*/
public function map(array $data, string $dtoClass): object
{
$info = $this->getClassInfo($dtoClass);
$args = [];
foreach ($info['params'] as $name => $paramInfo) {
// isset() is faster than array_key_exists(), check for null separately
if (isset($data[$name])) {
$value = $data[$name];
// Handle nested DTO (type hint is a class) - only map arrays, pass objects through
if ($paramInfo['dtoClass'] !== null && is_array($value)) {
$value = $this->map($value, $paramInfo['dtoClass']);
} elseif ($paramInfo['collectionOf'] !== null) {
// Handle collection - inline loop avoids closure creation overhead
$collectionClass = $paramInfo['collectionOf'];
$mapped = [];
foreach ($value as $item) {
$mapped[] = is_array($item) ? $this->map($item, $collectionClass) : $item;
}
$value = $mapped;
}
$args[$name] = $value;
} elseif (array_key_exists($name, $data)) {
// Value is explicitly null in data
$args[$name] = null;
} elseif ($paramInfo['hasDefault']) {
$args[$name] = $paramInfo['default'];
} elseif ($paramInfo['nullable']) {
$args[$name] = null;
}
// If required and not provided, let PHP throw the error
}
return new $dtoClass(...$args);
}
/**
* Get cached class info via reflection.
*
* @param class-string $class The class to analyze
* @return array{params: array<string, array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: class-string|null, collectionOf: class-string|null}>}
*/
protected function getClassInfo(string $class): array
{
if (isset(static::$cache[$class])) {
return static::$cache[$class];
}
$reflection = new ReflectionClass($class);
$constructor = $reflection->getConstructor();
$params = [];
if ($constructor !== null) {
foreach ($constructor->getParameters() as $param) {
$params[$param->getName()] = $this->analyzeParameter($param);
}
}
static::$cache[$class] = ['params' => $params];
return static::$cache[$class];
}
/**
* Analyze a constructor parameter for DTO mapping info.
*
* @param \ReflectionParameter $param The parameter to analyze
* @return array{name: string, nullable: bool, hasDefault: bool, default: mixed, dtoClass: class-string|null, collectionOf: class-string|null}
*/
protected function analyzeParameter(ReflectionParameter $param): array
{
$type = $param->getType();
$info = [
'name' => $param->getName(),
'nullable' => $param->allowsNull(),
'hasDefault' => $param->isDefaultValueAvailable(),
'default' => $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null,
'dtoClass' => null,
'collectionOf' => null,
];
// Check if type is a class (potential nested DTO)
if ($type instanceof ReflectionNamedType && !$type->isBuiltin()) {
$typeName = $type->getName();
// Exclude common non-DTO classes
if (
!in_array($typeName, ['DateTime', 'DateTimeImmutable', 'DateTimeInterface', 'stdClass'], true)
&& class_exists($typeName)
) {
$info['dtoClass'] = $typeName;
}
}
// Check for #[CollectionOf(SomeDto::class)] attribute
foreach ($param->getAttributes(CollectionOf::class) as $attr) {
/** @var class-string $collectionClass */
$collectionClass = $attr->getArguments()[0];
$info['collectionOf'] = $collectionClass;
$info['dtoClass'] = null; // Collection takes precedence
}
return $info;
}
/**
* Clear the reflection cache.
*
* Useful for testing or when classes are reloaded.
*
* @return void
*/
public static function clearCache(): void
{
static::$cache = [];
}
}