-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsModel.php
More file actions
380 lines (339 loc) · 12.1 KB
/
IsModel.php
File metadata and controls
380 lines (339 loc) · 12.1 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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
<?php
declare(strict_types=1);
namespace ComplexHeart\Domain\Model;
use ComplexHeart\Domain\Model\Traits\HasAttributes;
use ComplexHeart\Domain\Model\Traits\HasInvariants;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionParameter;
use ReflectionUnionType;
use ComplexHeart\Domain\Model\Exceptions\InstantiationException;
use TypeError;
/**
* Trait IsModel
*
* Provides type-safe object instantiation with automatic invariant checking.
*
* Key improvements in this version:
* - Type-safe make() method with validation
* - Automatic invariant checking after construction
* - Constructor as single source of truth
* - Better error messages
*
* @author Unay Santisteban <usantisteban@othercode.io>
*/
trait IsModel
{
use HasAttributes;
use HasInvariants;
/**
* Create instance with type-safe validation.
*
* This method:
* 1. Validates parameter types against constructor signature
* 2. Creates instance through constructor (type-safe)
* 3. Invariants are checked automatically after construction
*
* @param mixed ...$params Constructor parameters
* @return static
* @throws InvalidArgumentException When required parameters are missing
* @throws TypeError When parameter types don't match
*/
final public static function make(mixed ...$params): static
{
$reflection = new ReflectionClass(static::class);
$constructor = $reflection->getConstructor();
if (!$constructor) {
throw new InstantiationException(
sprintf('%s must have a constructor to use make()', static::class)
);
}
// Handle named parameters if provided
if (self::hasNamedParameters($params)) {
$params = self::mapNamedToPositional($constructor, $params);
}
// Validate parameters against constructor signature
// array_values ensures we have a proper indexed array
self::validateConstructorParameters($constructor, array_values($params));
// Create instance through constructor (PHP handles type enforcement)
// @phpstan-ignore-next-line - new static() is safe here as we validated the constructor
$instance = new static(...$params);
// Auto-check invariants if enabled
$instance->autoCheckInvariants();
return $instance;
}
/**
* Alias for make() method - more idiomatic for domain objects.
*
* Example: Customer::new(id: $id, name: 'John Doe')
*
* @param mixed ...$params Constructor parameters
* @return static
* @throws InvalidArgumentException When required parameters are missing
* @throws TypeError When parameter types don't match
*/
final public static function new(mixed ...$params): static
{
return static::make(...$params);
}
/**
* Validate parameters match constructor signature.
*
* @param ReflectionMethod $constructor
* @param array<int, mixed> $params
* @return void
* @throws InvalidArgumentException
* @throws TypeError
*/
private static function validateConstructorParameters(
ReflectionMethod $constructor,
array $params
): void {
$constructorParams = $constructor->getParameters();
$required = $constructor->getNumberOfRequiredParameters();
// Check parameter count
if (count($params) < $required) {
$missing = array_slice($constructorParams, count($params), $required - count($params));
$names = array_map(fn ($p) => $p->getName(), $missing);
throw new InvalidArgumentException(
sprintf(
'%s::make() missing required parameters: %s',
basename(str_replace('\\', '/', static::class)),
implode(', ', $names)
)
);
}
// Validate types for each parameter
foreach ($constructorParams as $index => $param) {
if (isset($params[$index])) {
self::validateParameterType($param, $params[$index]);
}
}
}
/**
* Validate a single parameter's type.
*
* @param ReflectionParameter $param
* @param mixed $value
* @return void
* @throws TypeError
*/
private static function validateParameterType(ReflectionParameter $param, mixed $value): void
{
$type = $param->getType();
if ($type === null) {
return; // No type hint
}
if ($type instanceof ReflectionNamedType) {
// Single type
$isValid = self::validateType($value, $type->getName(), $type->allowsNull());
$expectedTypes = $type->getName();
} elseif ($type instanceof ReflectionUnionType) {
// Union type (e.g., int|float|string)
$isValid = self::validateUnionType($value, $type);
$expectedTypes = implode('|', array_map(
fn ($t) => $t instanceof ReflectionNamedType ? $t->getName() : 'mixed',
$type->getTypes()
));
} else {
return; // Intersection types or other complex types not supported yet
}
if (!$isValid) {
throw new TypeError(
sprintf(
'%s::make() parameter "%s" must be of type %s, %s given',
basename(str_replace('\\', '/', static::class)),
$param->getName(),
$expectedTypes,
get_debug_type($value)
)
);
}
}
/**
* Validate a value matches expected type.
*
* @param mixed $value
* @param string $typeName
* @param bool $allowsNull
* @return bool
*/
private static function validateType(mixed $value, string $typeName, bool $allowsNull): bool
{
if ($value === null) {
return $allowsNull;
}
return match($typeName) {
'int' => is_int($value),
'float' => is_float($value) || is_int($value), // Allow int for float
'string' => is_string($value),
'bool' => is_bool($value),
'array' => is_array($value),
'object' => is_object($value),
'callable' => is_callable($value),
'iterable' => is_iterable($value),
'mixed' => true,
default => $value instanceof $typeName
};
}
/**
* Validate a value matches one of the types in a union type.
*
* @param mixed $value
* @param ReflectionUnionType $unionType
* @return bool
*/
private static function validateUnionType(mixed $value, ReflectionUnionType $unionType): bool
{
// Check if null is allowed in the union
$allowsNull = $unionType->allowsNull();
if ($value === null) {
return $allowsNull;
}
// Try to match against each type in the union
foreach ($unionType->getTypes() as $type) {
if (!$type instanceof ReflectionNamedType) {
continue; // Skip non-named types (shouldn't happen in practice)
}
$typeName = $type->getName();
// Skip 'null' type as we already handled it
if ($typeName === 'null') {
continue;
}
// If value matches this type, union is satisfied
if (self::validateType($value, $typeName, false)) {
return true;
}
}
// Value didn't match any type in the union
return false;
}
/**
* Check if parameters include named parameters.
*
* @param array<int|string, mixed> $params
* @return bool
*/
private static function hasNamedParameters(array $params): bool
{
if (empty($params)) {
return false;
}
// Named parameters have string keys
// Positional parameters have sequential integer keys [0, 1, 2, ...]
return array_keys($params) !== range(0, count($params) - 1);
}
/**
* Map named parameters to positional parameters based on constructor signature.
*
* Supports three scenarios:
* 1. Pure named parameters: make(value: 'test')
* 2. Pure positional parameters: make('test')
* 3. Mixed parameters: make(1, name: 'test', description: 'desc')
*
* @param ReflectionMethod $constructor
* @param array<int|string, mixed> $params
* @return array<int, mixed>
* @throws InvalidArgumentException When required named parameter is missing
*/
private static function mapNamedToPositional(
ReflectionMethod $constructor,
array $params
): array {
$positional = [];
$constructorParams = $constructor->getParameters();
foreach ($constructorParams as $index => $param) {
$name = $param->getName();
// Check if parameter was provided positionally (by index)
if (array_key_exists($index, $params)) {
$positional[$index] = $params[$index];
}
// Check if parameter was provided by name
elseif (array_key_exists($name, $params)) {
$positional[$index] = $params[$name];
}
// Check if parameter has a default value
elseif ($param->isDefaultValueAvailable()) {
$positional[$index] = $param->getDefaultValue();
}
// Check if parameter is required
elseif (!$param->isOptional()) {
throw new InvalidArgumentException(
sprintf(
'%s::make() missing required parameter: %s',
basename(str_replace('\\', '/', static::class)),
$name
)
);
}
// else: optional parameter without default (e.g., nullable), will be handled by PHP
}
return $positional;
}
/**
* Determine if invariants should be checked automatically after construction.
*
* Override this method in your class to disable auto-check:
*
* protected function shouldAutoCheckInvariants(): bool
* {
* return false;
* }
*
* @return bool
*/
protected function shouldAutoCheckInvariants(): bool
{
return false; // Disabled by default for backward compatibility
}
/**
* Called after construction to auto-check invariants.
*
* This method is automatically called after the constructor completes
* if shouldAutoCheckInvariants() returns true.
*
* @return void
*/
private function autoCheckInvariants(): void
{
if ($this->shouldAutoCheckInvariants()) {
$this->check();
}
}
/**
* Initialize the Model (legacy method - DEPRECATED).
*
* @deprecated Use constructor with make() factory method instead.
* This method will be removed in v1.0.0
*
* @param array<int|string, mixed> $source
* @param string|callable $onFail
* @return static
*/
protected function initialize(array $source, string|callable $onFail = 'invariantHandler'): static
{
$this->hydrate($this->prepareAttributes($source));
$this->check($onFail);
return $this;
}
/**
* Transform an indexed array into assoc array (legacy method - DEPRECATED).
*
* @deprecated This method will be removed in v1.0.0
* @param array<int|string, mixed> $source
* @return array<string, mixed>
*/
private function prepareAttributes(array $source): array
{
// check if the array is indexed or associative.
$isIndexed = fn ($source): bool => ([] !== $source) && array_keys($source) === range(0, count($source) - 1);
/** @var array<string, mixed> $source */
return $isIndexed($source)
// combine the attributes keys with the provided source values.
? array_combine(array_slice(static::attributes(), 0, count($source)), $source)
// return the already mapped array source.
: $source;
}
}