DateTimeNormalizer example

use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;

/** * @author Kévin Dunglas <dunglas@gmail.com> */
class DateTimeNormalizerTest extends TestCase
{
    private DateTimeNormalizer $normalizer;

    protected function setUp(): void
    {
        $this->normalizer = new DateTimeNormalizer();
    }

    public function testSupportsNormalization()
    {
        $this->assertTrue($this->normalizer->supportsNormalization(new \DateTime()));
        $this->assertTrue($this->normalizer->supportsNormalization(new \DateTimeImmutable()));
        $this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
    }

    public function testNormalize()
    {
        
$obj = $serializer->denormalize(['inner' => 'foo'], ObjectOuter::class);

        $this->assertInstanceOf(ObjectInner::class$obj->getInner());
    }

    public function testDenormalizeUsesContextAttributeForPropertiesInConstructorWithSeralizedName()
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());

        $extractor = new PropertyInfoExtractor([][new PhpDocExtractor()new ReflectionExtractor()]);
        $normalizer = new ObjectNormalizer($classMetadataFactorynew MetadataAwareNameConverter($classMetadataFactory), null, $extractor);
        $serializer = new Serializer([new DateTimeNormalizer([DateTimeNormalizer::FORMAT_KEY => 'd-m-Y'])$normalizer]);

        /** @var ObjectDummyWithContextAttribute $obj */
        $obj = $serializer->denormalize(['property_with_serialized_name' => '01-02-2022', 'propertyWithoutSerializedName' => '01-02-2022'], ObjectDummyWithContextAttribute::class);

        $this->assertSame($obj->propertyWithSerializedName->format('Y-m-d')$obj->propertyWithoutSerializedName->format('Y-m-d'));
    }

    public function testNormalizeUsesContextAttributeForPropertiesInConstructorWithSerializedPath()
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());

        
$this->format = $format;
        $this->context = $context + [self::MESSENGER_SERIALIZATION_CONTEXT => true];
    }

    public static function create(): self
    {
        if (!class_exists(SymfonySerializer::class)) {
            throw new LogicException(sprintf('The "%s" class requires Symfony\'s Serializer component. Try running "composer require symfony/serializer" or use "%s" instead.', __CLASS__, PhpSerializer::class));
        }

        $encoders = [new XmlEncoder()new JsonEncoder()];
        $normalizers = [new DateTimeNormalizer()new ArrayDenormalizer()new ObjectNormalizer()];
        $serializer = new SymfonySerializer($normalizers$encoders);

        return new self($serializer);
    }

    public function decode(array $encodedEnvelope): Envelope
    {
        if (empty($encodedEnvelope['body']) || empty($encodedEnvelope['headers'])) {
            throw new MessageDecodingFailedException('Encoded envelope should have at least a "body" and some "headers", or maybe you should implement your own serializer.');
        }

        

  protected function setUp(): void {
    parent::setUp();

    $system_date_config = $this->prophesize(ImmutableConfig::class);
    $system_date_config->get('timezone.default')
      ->willReturn('Australia/Sydney');
    $config_factory = $this->prophesize(ConfigFactoryInterface::class);
    $config_factory->get('system.date')
      ->willReturn($system_date_config->reveal());

    $this->normalizer = new DateTimeNormalizer($config_factory->reveal());
    $this->data = $this->prophesize(DateTimeInterface::class);
  }

  /** * @covers ::supportsNormalization */
  public function testSupportsNormalization() {
    $this->assertTrue($this->normalizer->supportsNormalization($this->data->reveal()));

    $datetimeiso8601 = $this->prophesize(DateTimeIso8601::class);
    $this->assertTrue($this->normalizer->supportsNormalization($datetimeiso8601->reveal()));

    
public function testThrowUnexpectedValueException()
    {
        $this->expectException(UnexpectedValueException::class);
        $this->normalizer->denormalize(['foo' => 'bar'], ObjectTypeHinted::class);
    }

    public function testDenomalizeRecursive()
    {
        $extractor = new PropertyInfoExtractor([][new PhpDocExtractor()new ReflectionExtractor()]);
        $normalizer = new ObjectNormalizer(null, null, null, $extractor);
        $serializer = new Serializer([new ArrayDenormalizer()new DateTimeNormalizer()$normalizer]);

        $obj = $serializer->denormalize([
            'inner' => ['foo' => 'foo', 'bar' => 'bar'],
            'date' => '1988/01/21',
            'inners' => [['foo' => 1]['foo' => 2]],
        ], ObjectOuter::class);

        $this->assertSame('foo', $obj->getInner()->foo);
        $this->assertSame('bar', $obj->getInner()->bar);
        $this->assertSame('1988-01-21', $obj->getDate()->format('Y-m-d'));
        $this->assertSame(1, $obj->getInners()[0]->foo);
        

trait ContextMetadataTestTrait
{
    /** * @dataProvider contextMetadataDummyProvider */
    public function testContextMetadataNormalize(string $contextMetadataDummyClass)
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());
        $normalizer = new ObjectNormalizer($classMetadataFactory, null, null, new PhpDocExtractor());
        new Serializer([new DateTimeNormalizer()$normalizer]);

        $dummy = new $contextMetadataDummyClass();
        $dummy->date = new \DateTimeImmutable('2011-07-28T08:44:00.123+00:00');

        self::assertEquals(['date' => '2011-07-28T08:44:00+00:00']$normalizer->normalize($dummy));

        self::assertEquals(['date' => '2011-07-28T08:44:00.123+00:00']$normalizer->normalize($dummy, null, [
            ObjectNormalizer::GROUPS => 'extended',
        ]), 'a specific normalization context is used for this group');

        self::assertEquals(['date' => '2011-07-28T08:44:00+00:00']$normalizer->normalize($dummy, null, [
            
$serializer = new Serializer([new UnwrappingDenormalizer()]['json' => new JsonEncoder()]);

        $this->assertSame(42, $serializer->deserialize('{"wrapper": 42}', 'int', 'json', [UnwrappingDenormalizer::UNWRAP_PATH => '[wrapper]']));
    }

    public function testUnionTypeDeserializable()
    {
        $classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader());
        $extractor = new PropertyInfoExtractor([][new PhpDocExtractor()new ReflectionExtractor()]);
        $serializer = new Serializer(
            [
                new DateTimeNormalizer(),
                new ObjectNormalizer($classMetadataFactory, null, null, $extractornew ClassDiscriminatorFromClassMetadata($classMetadataFactory)),
            ],
            ['json' => new JsonEncoder()]
        );

        $actual = $serializer->deserialize('{ "changed": null }', DummyUnionType::class, 'json', [
            DateTimeNormalizer::FORMAT_KEY => \DateTimeinterface::ATOM,
        ]);

        $this->assertEquals((new DummyUnionType())->setChanged(null)$actual, 'Union type denormalization first case failed.');

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