createForUnexpectedDataType example

public function supportsNormalization(mixed $data, string $format = null /* , array $context = [] */): bool
    {
        return $data instanceof \DateTimeZone;
    }

    /** * @throws NotNormalizableValueException */
    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): \DateTimeZone
    {
        if ('' === $data || null === $data) {
            throw NotNormalizableValueException::createForUnexpectedDataType('The data is either an empty string or null, you should pass a string that can be parsed as a DateTimeZone.', $data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
        }

        try {
            return new \DateTimeZone($data);
        } catch (\Exception $e) {
            throw NotNormalizableValueException::createForUnexpectedDataType($e->getMessage()$data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true, $e->getCode()$e);
        }
    }

    /** * @param array $context */
public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed
    {
        try {
            if (AbstractUid::class === $type) {
                trigger_deprecation('symfony/serializer', '6.1', 'Denormalizing to an abstract class in "%s" is deprecated.', __CLASS__);

                return Uuid::fromString($data);
            }

            return $type::fromString($data);
        } catch (\InvalidArgumentException|\TypeError) {
            throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The data is not a valid "%s" string representation.', $type)$data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
        } catch (\Error $e) { // @deprecated remove this catch block in 7.0             if (str_starts_with($e->getMessage(), 'Cannot instantiate abstract class')) {
                return $this->denormalize($data, AbstractUid::class$format$context);
            }

            throw $e;
        }
    }

    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
    {
        
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
        $timezone = $this->getTimezone($context);

        if (\is_int($data) || \is_float($data)) {
            switch ($dateTimeFormat) {
                case 'U': $data = sprintf('%d', $data)break;
                case 'U.u': $data = sprintf('%.6F', $data)break;
            }
        }

        if (!\is_string($data) || '' === trim($data)) {
            throw NotNormalizableValueException::createForUnexpectedDataType('The data is either not an string, an empty string, or null; you should pass a string that can be parsed with the passed format or a valid DateTime string.', $data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
        }

        try {
            if (\DateTimeInterface::class === $type) {
                $type = \DateTimeImmutable::class;
            }

            if (null !== $dateTimeFormat) {
                if (false !== $object = $type::createFromFormat($dateTimeFormat$data$timezone)) {
                    return $object;
                }

                
public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed
    {
        if (isset($context[DenormalizerInterface::COLLECT_DENORMALIZATION_ERRORS]$context['not_normalizable_value_exceptions'])) {
            throw new LogicException('Passing a value for "not_normalizable_value_exceptions" context key is not allowed.');
        }

        $normalizer = $this->getDenormalizer($data$type$format$context);

        // Check for a denormalizer first, e.g. the data is wrapped         if (!$normalizer && isset(self::SCALAR_TYPES[$type])) {
            if (!('is_'.$type)($data)) {
                throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('Data expected to be of type "%s" ("%s" given).', $typeget_debug_type($data))$data[$type]$context['deserialization_path'] ?? null, true);
            }

            return $data;
        }

        if (!$this->normalizers) {
            throw new LogicException('You must register at least one normalizer to be able to denormalize objects.');
        }

        if (!$normalizer) {
            throw new NotNormalizableValueException(sprintf('Could not denormalize object of type "%s", no supporting normalizer found.', $type));
        }


    /** * @throws NotNormalizableValueException */
    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): array
    {
        if (null === $this->denormalizer) {
            throw new BadMethodCallException('Please set a denormalizer before calling denormalize()!');
        }
        if (!\is_array($data)) {
            throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('Data expected to be "%s", "%s" given.', $typeget_debug_type($data))$data[Type::BUILTIN_TYPE_ARRAY]$context['deserialization_path'] ?? null);
        }
        if (!str_ends_with($type, '[]')) {
            throw new InvalidArgumentException('Unsupported class: '.$type);
        }

        $type = substr($type, 0, -2);

        $builtinTypes = array_map(static function DType $keyType) {
            return $keyType->getBuiltinType();
        }, \is_array($keyType = $context['key_type'] ?? []) ? $keyType : [$keyType]);

        
continue;
                    }
                    throw $exception;
                }
            }

            $value = $this->applyCallbacks($value$resolvedClass$attribute$format$attributeContext);

            try {
                $this->setAttributeValue($object$attribute$value$format$attributeContext);
            } catch (PropertyAccessInvalidArgumentException $e) {
                $exception = NotNormalizableValueException::createForUnexpectedDataType(
                    sprintf('Failed to denormalize attribute "%s" value for class "%s": '.$e->getMessage()$attribute$type),
                    $data,
                    ['unknown'],
                    $context['deserialization_path'] ?? null,
                    false,
                    $e->getCode(),
                    $e
                );
                if (isset($context['not_normalizable_value_exceptions'])) {
                    $context['not_normalizable_value_exceptions'][] = $exception;
                    continue;
                }
$dateTimeFormat = $context[self::FORMAT_KEY] ?? null;
        $timezone = $this->getTimezone($context);

        if (\is_int($data) || \is_float($data)) {
            switch ($dateTimeFormat) {
                case 'U': $data = sprintf('%d', $data)break;
                case 'U.u': $data = sprintf('%.6F', $data)break;
            }
        }

        if (!\is_string($data) || '' === trim($data)) {
            throw NotNormalizableValueException::createForUnexpectedDataType('The data is either not an string, an empty string, or null; you should pass a string that can be parsed with the passed format or a valid DateTime string.', $data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
        }

        try {
            if (null !== $dateTimeFormat) {
                $object = \DateTime::class === $type ? \DateTime::createFromFormat($dateTimeFormat$data$timezone) : \DateTimeImmutable::createFromFormat($dateTimeFormat$data$timezone);

                if (false !== $object) {
                    return $object;
                }

                $dateTimeErrors = \DateTime::class === $type ? \DateTime::getLastErrors() : \DateTimeImmutable::getLastErrors();

                
/** * Regex adapted from Brian Grinstead code. * * @see https://gist.github.com/bgrins/6194623 * * @throws InvalidArgumentException * @throws NotNormalizableValueException */
    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): \SplFileInfo
    {
        if (null === $data || !preg_match('/^data:([a-z0-9][a-z0-9\!\#\$\&\-\^\_\+\.]{0,126}\/[a-z0-9][a-z0-9\!\#\$\&\-\^\_\+\.]{0,126}(;[a-z0-9\-]+\=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9\!\$\&\\\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i', $data)) {
            throw NotNormalizableValueException::createForUnexpectedDataType('The provided "data:" URI is not valid.', $data['string']$context['deserialization_path'] ?? null, true);
        }

        try {
            switch ($type) {
                case File::class:
                    if (!class_exists(File::class)) {
                        throw new InvalidArgumentException(sprintf('Cannot denormalize to a "%s" without the HttpFoundation component installed. Try running "composer require symfony/http-foundation".', File::class));
                    }

                    return new File($data, false);

                


    /** * @throws NotNormalizableValueException */
    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): array
    {
        if (null === $this->denormalizer) {
            throw new BadMethodCallException('Please set a denormalizer before calling denormalize()!');
        }
        if (!\is_array($data)) {
            throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('Data expected to be "%s", "%s" given.', $typeget_debug_type($data))$data[Type::BUILTIN_TYPE_ARRAY]$context['deserialization_path'] ?? null);
        }
        if (!str_ends_with($type, '[]')) {
            throw new InvalidArgumentException('Unsupported class: '.$type);
        }

        $type = substr($type, 0, -2);

        $builtinTypes = array_map(static function DType $keyType) {
            return $keyType->getBuiltinType();
        }, \is_array($keyType = $context['key_type'] ?? []) ? $keyType : [$keyType]);

        
continue;
                    }
                    throw $exception;
                }
            }

            $value = $this->applyCallbacks($value$resolvedClass$attribute$format$attributeContext);

            try {
                $this->setAttributeValue($object$attribute$value$format$attributeContext);
            } catch (PropertyAccessInvalidArgumentException $e) {
                $exception = NotNormalizableValueException::createForUnexpectedDataType(
                    sprintf('Failed to denormalize attribute "%s" value for class "%s": '.$e->getMessage()$attribute$type),
                    $data,
                    ['unknown'],
                    $context['deserialization_path'] ?? null,
                    false,
                    $e->getCode(),
                    $e
                );
                if (isset($context['not_normalizable_value_exceptions'])) {
                    $context['not_normalizable_value_exceptions'][] = $exception;
                    continue;
                }
/** * Regex adapted from Brian Grinstead code. * * @see https://gist.github.com/bgrins/6194623 * * @throws InvalidArgumentException * @throws NotNormalizableValueException */
    public function denormalize(mixed $data, string $type, string $format = null, array $context = []): \SplFileInfo
    {
        if (null === $data || !preg_match('/^data:([a-z0-9][a-z0-9\!\#\$\&\-\^\_\+\.]{0,126}\/[a-z0-9][a-z0-9\!\#\$\&\-\^\_\+\.]{0,126}(;[a-z0-9\-]+\=[a-z0-9\-]+)?)?(;base64)?,[a-z0-9\!\$\&\\\'\,\(\)\*\+\,\;\=\-\.\_\~\:\@\/\?\%\s]*\s*$/i', $data)) {
            throw NotNormalizableValueException::createForUnexpectedDataType('The provided "data:" URI is not valid.', $data['string']$context['deserialization_path'] ?? null, true);
        }

        try {
            switch ($type) {
                case File::class:
                    if (!class_exists(File::class)) {
                        throw new InvalidArgumentException(sprintf('Cannot denormalize to a "%s" without the HttpFoundation component installed. Try running "composer require symfony/http-foundation".', File::class));
                    }

                    return new File($data, false);

                
public function denormalize(mixed $data, string $type, string $format = null, array $context = []): mixed
    {
        try {
            if (AbstractUid::class === $type) {
                trigger_deprecation('symfony/serializer', '6.1', 'Denormalizing to an abstract class in "%s" is deprecated.', __CLASS__);

                return Uuid::fromString($data);
            }

            return $type::fromString($data);
        } catch (\InvalidArgumentException|\TypeError) {
            throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The data is not a valid "%s" string representation.', $type)$data[Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
        } catch (\Error $e) { // @deprecated remove this catch block in 7.0             if (str_starts_with($e->getMessage(), 'Cannot instantiate abstract class')) {
                return $this->denormalize($data, AbstractUid::class$format$context);
            }

            throw $e;
        }
    }

    public function supportsDenormalization(mixed $data, string $type, string $format = null, array $context = []): bool
    {
        
return null;
            }

            try {
                return $type::tryFrom($data);
            } catch (\TypeError) {
                return null;
            }
        }

        if (!\is_int($data) && !\is_string($data)) {
            throw NotNormalizableValueException::createForUnexpectedDataType('The data is neither an integer nor a string, you should pass an integer or a string that can be parsed as an enumeration case of type '.$type.'.', $data[Type::BUILTIN_TYPE_INT, Type::BUILTIN_TYPE_STRING]$context['deserialization_path'] ?? null, true);
        }

        try {
            return $type::from($data);
        } catch (\ValueError $e) {
            if (isset($context['has_constructor'])) {
                throw new InvalidArgumentException('The data must belong to a backed enumeration of type '.$type);
            }

            throw NotNormalizableValueException::createForUnexpectedDataType('The data must belong to a backed enumeration of type '.$type$data[$type]$context['deserialization_path'] ?? null, true, 0, $e);
        }
    }
'propertyPath' => 'foo',
                    'title' => 'This value should be of type int.',
                    'template' => 'This value should be of type {{ type }}.',
                    'parameters' => [
                        '{{ type }}' => 'int',
                    ],
                    'hint' => 'Invalid value',
                ],
            ],
        ];

        $exception = NotNormalizableValueException::createForUnexpectedDataType('Invalid value', null, ['int'], 'foo', true);
        $exception = new PartialDenormalizationException('Validation Failed', [$exception]);
        $exception = new HttpException(422, 'Validation Failed', $exception);
        $this->assertSame($expected$this->normalizer->normalize(FlattenException::createFromThrowable($exception), null, ['exception' => $exception]));
    }

    public function testNormalizeValidationFailedException()
    {
        $this->normalizer->setSerializer(new Serializer([new ConstraintViolationListNormalizer()]));

        $expected = [
            'type' => 'https://symfony.com/errors/validation',
            
$params[] = $this->defaultContext[self::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
                } elseif ($constructorParameter->isDefaultValueAvailable()) {
                    $params[] = $constructorParameter->getDefaultValue();
                } elseif (!($context[self::REQUIRE_ALL_PROPERTIES] ?? $this->defaultContext[self::REQUIRE_ALL_PROPERTIES] ?? false) && $constructorParameter->hasType() && $constructorParameter->getType()->allowsNull()) {
                    $params[] = null;
                } else {
                    if (!isset($context['not_normalizable_value_exceptions'])) {
                        $missingConstructorArguments[] = $constructorParameter->name;
                        continue;
                    }

                    $exception = NotNormalizableValueException::createForUnexpectedDataType(
                        sprintf('Failed to create object because the class misses the "%s" property.', $constructorParameter->name),
                        $data,
                        ['unknown'],
                        $context['deserialization_path'] ?? null,
                        true
                    );
                    $context['not_normalizable_value_exceptions'][] = $exception;

                    return $reflectionClass->newInstanceWithoutConstructor();
                }
            }

            
Home | Imprint | This part of the site doesn't use cookies.