symfony / symfony

The Symfony PHP framework
https://symfony.com
MIT License
29.47k stars 9.41k forks source link

Support Carbon(Immutable) in DateTimeNormalizer #57482

Open amcsi opened 1 week ago

amcsi commented 1 week ago

Description

Currently the DateTimeNormalizer supports denormalizing DateTime, DateTimeImmutable, and DateTimeInterface, but not extensions of DateTime and DateTimeImmutable e.g. Carbon and CarbonImmutable.

Now the denormalizer is currently perfectly capable of denormalizing Carbon and CarbonImmutable. The issue is that the normalizer reports it as not supported in the supportsDenormalization() method, because rather than checking if the type class is or extends one of the supporting classes, it just checks against the DateTime/Immutable/Interface class strings directly.

The problem with this is that when using DateTimeNormalizer as part of a compound configuration of a Serializer with - say - a ReflectionExtractor set up for reading class property type-hints, then denormalization to class properties with CarbonImmutable as the type-hint won't work, because DateTimeNormalizer reports them as not supported.

Example

        $denormalizer = new DateTimeNormalizer();
        $dateString = '2012-01-01T00:00:00Z';
        // Converts to a DateTimeImmutable
        $result = $denormalizer->denormalize($dateString, \DateTimeImmutable::class);
        // $supportsDenormalization = true
        $supportsDenormalization = $denormalizer->supportsDenormalization($dateString, \DateTimeImmutable::class);

        $denormalizer = new DateTimeNormalizer();
        // Converts to a CarbonImmutable just fine
        $result = $denormalizer->denormalize($dateString, CarbonImmutable::class);
        // $supportsDenormalization = false :(
        $supportsDenormalization = $denormalizer->supportsDenormalization($dateString, CarbonImmutable::class);
derrabus commented 1 week ago

We could think about making the supported types array configurable.