Skip to content

Commit 1aabc8e

Browse files
committed
Improve class to array type logic
1 parent 05259f9 commit 1aabc8e

File tree

1 file changed

+31
-7
lines changed

1 file changed

+31
-7
lines changed

src/Type/ClassTypeToArrayType.php

Lines changed: 31 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,10 @@ public function cast(mixed $value, Context $context): object|array
3838
{
3939
$className = $this->metadata->name;
4040

41+
/**
42+
* Do not allow non-compatible types: The `$value` instance
43+
* must be compatible with declared type.
44+
*/
4145
if (!$value instanceof $className) {
4246
throw InvalidValueOfTypeException::createFromContext(
4347
expected: $this->metadata->getTypeStatement($context, read: true),
@@ -46,16 +50,36 @@ public function cast(mixed $value, Context $context): object|array
4650
);
4751
}
4852

49-
// Subtype normalization
53+
/**
54+
* Force subtype normalization in case of:
55+
*
56+
* ```php
57+
* public AbstractClass $obj = new ClassImpl();
58+
* ```
59+
*
60+
* Then the `$className` will contain `AbstractClass`,
61+
* and `$value::class` will contain `ClassImpl`.
62+
*/
5063
if ($value::class !== $className) {
51-
/** @var object|array<array-key, mixed> */
52-
return $context->getTypeByValue($value)
53-
->cast($value, $context);
64+
$type = $context->getTypeByValue($value);
65+
66+
/**
67+
* Most likely, the `$type` will return the same result as the
68+
* current type.
69+
*
70+
* However, this is not guaranteed.
71+
*
72+
* @var object|array<array-key, mixed>
73+
*/
74+
return $type->cast($value, $context);
5475
}
5576

56-
$entrance = $context->enter($value, new ObjectEntry($this->metadata->name));
77+
$entrance = $context->enter(
78+
value: $value,
79+
entry: new ObjectEntry($this->metadata->name),
80+
);
5781

58-
$result = $this->normalizeObject($value, $entrance);
82+
$result = $this->normalize($value, $entrance);
5983

6084
if ($this->metadata->isNormalizeAsArray ?? $context->isObjectAsArray()) {
6185
return $result;
@@ -69,7 +93,7 @@ public function cast(mixed $value, Context $context): object|array
6993
* @throws InvalidObjectValueException in case the value of a certain field is incorrect
7094
* @throws \Throwable in case of internal error occurs
7195
*/
72-
protected function normalizeObject(object $object, Context $context): array
96+
protected function normalize(object $object, Context $context): array
7397
{
7498
$result = [];
7599

0 commit comments

Comments
 (0)