Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
*/
public const PRESERVE_EMPTY_OBJECTS = 'preserve_empty_objects';

/**
* When true, elements of scalar collections (int[], float[], bool[], string[])
* are safely cast to their target builtin type during denormalization.
*/
public const CAST_SCALAR_COLLECTIONS = 'cast_scalar_collections';

protected ?ClassDiscriminatorResolverInterface $classDiscriminatorResolver;

/**
Expand Down Expand Up @@ -537,6 +543,19 @@ private function validateAndDenormalize(Type $type, string $currentClass, string
$class = $collectionValueBaseType->getClassName().'[]';
$context['key_type'] = $collectionKeyType;
$context['value_type'] = $collectionValueType;
} elseif (
!empty($context[self::CAST_SCALAR_COLLECTIONS])
&& $type instanceof CollectionType
&& $type->isList()
&& $collectionValueBaseType instanceof BuiltinType
&& \is_array($data)
) {
$data = $this->castScalarCollectionElements(
$data,
$collectionValueType, // original (possibly wrapped) value type
$collectionValueBaseType, // unwrapped BuiltinType: int/float/bool/string
(bool) ($context[self::DISABLE_TYPE_ENFORCEMENT] ?? false) // loose mode
);
} elseif ($collectionValueBaseType instanceof BuiltinType && TypeIdentifier::ARRAY === $collectionValueBaseType->getTypeIdentifier()) {
// get inner type for any nested array
$innerType = $collectionValueType;
Expand Down Expand Up @@ -927,4 +946,129 @@ private function getMappedClass(array $data, string $class, array $context): str

return $mappedClass;
}

/**
* Cast each element of a scalar collection (int/float/bool/string) according to the element type.
*
* @param array<int|string,mixed> $data
*
* @return array<int|string,mixed>
*/
private function castScalarCollectionElements(
array $data,
Type $valueType,
BuiltinType $baseType,
bool $isDisabledTypeEnforcement,
): array {
$nullable = false; // Determine element nullability by unwrapping NullableType/WrappingTypeInterface layers
$candidateType = $valueType;
while ($candidateType instanceof WrappingTypeInterface) {
if ($candidateType instanceof NullableType) {
$nullable = true;
break;
}
$candidateType = $candidateType->getWrappedType();
}
$collectionItemTypeIdentifier = $baseType->getTypeIdentifier(); // INT/FLOAT/BOOL/STRING
// Cast function preserves array keys to avoid breaking associative collections
$cast = static function (mixed $v) use (
$collectionItemTypeIdentifier,
$nullable,
$isDisabledTypeEnforcement
) {
// Null handling
if (null === $v) {
if ($nullable || $isDisabledTypeEnforcement) {
return null;
}

throw NotNormalizableValueException::createForUnexpectedDataType('Null is not allowed for a non-nullable collection element.', $v, [$collectionItemTypeIdentifier->name]);
}

switch ($collectionItemTypeIdentifier) {
case TypeIdentifier::INT:
if (\is_int($v)) {
return $v;
}
// Strict, safe integer-string (no spaces, no decimals, optional sign)
if (\is_string($v) && preg_match('/^[+-]?\d+$/', $v)) {
return (int) $v;
}
// Non-strict: allow scalar coercion only (avoid arrays/objects)
if ($isDisabledTypeEnforcement && \is_scalar($v)) {
return (int) $v; // e.g. "12abc"→12, true→1, 3.7→3, "abc"→0
}
break;

case TypeIdentifier::FLOAT:
if (\is_float($v)) {
return $v;
}
if (\is_int($v)) {
return (float) $v;
}
// Strict: numeric strings (accepts "1", "2.5", "-0.75", "1e3")
if (\is_string($v) && is_numeric($v)) {
return (float) $v;
}
// Non-strict: allow scalar coercion only
if ($isDisabledTypeEnforcement && \is_scalar($v)) {
return (float) $v; // e.g. "abc"→0.0, true→1.0
}
break;

case TypeIdentifier::BOOL:
// Accept real booleans in any mode
if (\is_bool($v)) {
return $v;
}

// Accept int 0/1 even in strict mode
if (0 === $v || 1 === $v) {
return (bool) $v;
}

// Non-strict mode: allow common string synonyms and scalar coercion
if ($isDisabledTypeEnforcement) {
if (\is_string($v)) {
$v = strtolower(trim($v));
if (\in_array($v, ['1', 'true', 'on', 'yes'], true)) {
return true;
}
if (\in_array($v, ['0', 'false', 'off', 'no'], true)) {
return false;
}
}
// Last-chance scalar coercion (e.g., "abc"->true, ""->false)
if (\is_scalar($v)) {
return (bool) $v;
}

// Arrays/objects remain invalid even in non-strict mode
throw NotNormalizableValueException::createForUnexpectedDataType('Cannot coerce non-scalar value to bool.', $v, ['bool', 'int', 'string']);
}
break;

case TypeIdentifier::STRING:
if (\is_string($v)) {
return $v;
}
if (!$isDisabledTypeEnforcement) {
break;
}
if (\is_scalar($v)) {
return (string) $v;
}
break;
}

throw NotNormalizableValueException::createForUnexpectedDataType('Failed to denormalize scalar collection element.', $v, [$collectionItemTypeIdentifier->name]);
};

foreach ($data as $k => $elm) {
$data[$k] = $cast($elm); // preserve keys
}

return $data;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Serializer\Tests\Dummy;

class DummyCollectionDTO
{
/**
* @param array<int> $intValues
* @param array<string> $stringValues
* @param array<float> $floatValues
* @param array<bool> $boolValues
*/
public function __construct(
public array $intValues,
public array $mixedValues,
public array $stringValues,
public array $floatValues,
public array $boolValues,
public array $wrappedValues,
public array $mixedWrappedValues,
) {
}
}
Loading
Loading