setSerializer example

/** * @param array<NormalizerInterface|DenormalizerInterface> $normalizers * @param array<EncoderInterface|DecoderInterface> $encoders */
    public function __construct(
        private array $normalizers = [],
        array $encoders = [],
    ) {
        foreach ($normalizers as $normalizer) {
            if ($normalizer instanceof SerializerAwareInterface) {
                $normalizer->setSerializer($this);
            }

            if ($normalizer instanceof DenormalizerAwareInterface) {
                $normalizer->setDenormalizer($this);
            }

            if ($normalizer instanceof NormalizerAwareInterface) {
                $normalizer->setNormalizer($this);
            }

            if (!($normalizer instanceof NormalizerInterface || $normalizer instanceof DenormalizerInterface)) {
                
protected static function getTsantosSerializerService($container)
    {
        $a = new \TSantos\Serializer\NormalizerRegistry();

        $b = new \TSantos\Serializer\Normalizer\CollectionNormalizer();

        $c = new \TSantos\Serializer\EventDispatcher\EventDispatcher();
        $c->addSubscriber(new \TSantos\SerializerBundle\EventListener\StopwatchListener(new \Symfony\Component\Stopwatch\Stopwatch(true)));

        $container->services['tsantos_serializer'] = $instance = new \TSantos\Serializer\EventEmitterSerializer(new \TSantos\Serializer\Encoder\JsonEncoder()$a$c);

        $b->setSerializer($instance);
        $d = new \TSantos\Serializer\Normalizer\JsonNormalizer();
        $d->setSerializer($instance);

        $a->add(new \TSantos\Serializer\Normalizer\ObjectNormalizer(new \TSantos\SerializerBundle\Serializer\CircularReferenceHandler()));
        $a->add($b);
        $a->add($d);

        return $instance;
    }
}

  public function testNormalizeComplexData() {
    $serializer_prophecy = $this->prophesize(Serializer::class);

    $non_internal_property = $this->getTypedDataProperty(FALSE);

    $serializer_prophecy->normalize($non_internal_propertystatic::TEST_FORMAT, [])
      ->willReturn('A-normalized')
      ->shouldBeCalled();

    $this->normalizer->setSerializer($serializer_prophecy->reveal());

    $complex_data = $this->prophesize(ComplexDataInterface::class);
    $complex_data->getProperties(TRUE)
      ->willReturn([
        'prop:a' => $non_internal_property,
        'prop:internal' => $this->getTypedDataProperty(TRUE),
      ])
      ->shouldBeCalled();

    $normalized = $this->normalizer->normalize($complex_data->reveal()static::TEST_FORMAT);
    $this->assertEquals(['prop:a' => 'A-normalized']$normalized);
  }


        return $this->normalizer->supportsDenormalization($data$type$format$context);
    }

    public function setSerializer(SerializerInterface $serializer): void
    {
        if (!$this->normalizer instanceof SerializerAwareInterface) {
            return;
        }

        $this->normalizer->setSerializer($serializer);
    }

    public function setNormalizer(NormalizerInterface $normalizer): void
    {
        if (!$this->normalizer instanceof NormalizerAwareInterface) {
            return;
        }

        $this->normalizer->setNormalizer($normalizer);
    }

    


            public function hasMetadataFor($value): bool
            {
                return AbstractDummyValue::class === $value;
            }
        };

        $factory = new ClassMetadataFactory(new AnnotationLoader());
        $normalizer = new ObjectNormalizer($factory, null, null, new PhpDocExtractor()new ClassDiscriminatorFromClassMetadata($loaderMock));
        $serializer = new Serializer([$normalizernew ArrayDenormalizer()]);
        $normalizer->setSerializer($serializer);

        return $serializer;
    }
}

abstract class AbstractDummyValue
{
    public $value;
}

class DummyValue extends AbstractDummyValue
{
use Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy;

class XmlEncoderTest extends TestCase
{
    private XmlEncoder $encoder;
    private string $exampleDateTimeString = '2017-02-19T15:16:08+0300';

    protected function setUp(): void
    {
        $this->encoder = new XmlEncoder();
        $serializer = new Serializer([new CustomNormalizer()]['xml' => new XmlEncoder()]);
        $this->encoder->setSerializer($serializer);
    }

    public function testEncodeScalar()
    {
        $obj = new ScalarDummy();
        $obj->xmlFoo = 'foo';

        $expected = '<?xml version="1.0"?>'."\n".
            '<response>foo</response>'."\n";

        $this->assertEquals($expected$this->encoder->encode($obj, 'xml'));
    }
private SerializerInterface&NormalizerInterface&MockObject $serializer;

    protected function setUp(): void
    {
        $this->createNormalizer();
    }

    private function createNormalizer(array $defaultContext = []): void
    {
        $this->serializer = $this->createMock(SerializerNormalizer::class);
        $this->normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
        $this->normalizer->setSerializer($this->serializer);
    }

    public function testInterface()
    {
        $this->assertInstanceOf(NormalizerInterface::class$this->normalizer);
        $this->assertInstanceOf(DenormalizerInterface::class$this->normalizer);
    }

    public function testNormalize()
    {
        $obj = new GetSetDummy();
        
protected function setUp(): void {
    parent::setUp();

    $this->entityRepository = $this->prophesize(EntityRepositoryInterface::class);
    $this->normalizer = new EntityReferenceFieldItemNormalizer($this->entityRepository->reveal());

    $this->serializer = $this->prophesize(Serializer::class);
    // Set up the serializer to return an entity property.     $this->serializer->normalize(Argument::cetera())
      ->willReturn('test');

    $this->normalizer->setSerializer($this->serializer->reveal());

    $this->fieldItem = $this->prophesize(EntityReferenceItem::class);
    $this->fieldItem->getIterator()
      ->willReturn(new \ArrayIterator(['target_id' => []]));

    $this->fieldDefinition = $this->prophesize(FieldDefinitionInterface::class);
    $this->fieldDefinition->getItemDefinition()
      ->willReturn($this->prophesize(FieldItemDataDefinition::class)->reveal());

  }

  


    $serializer = $this->prophesize(DenormalizerInterface::class);
    $serializer->willImplement(SerializerInterface::class);
    $serializer->denormalize(
      Argument::type('array'),
      Argument::type('string'),
      Argument::type('string'),
      Argument::type('array')
    )->willReturnArgument(0);

    $this->normalizer->setSerializer($serializer->reveal());
  }

  /** * @covers ::denormalize * @dataProvider denormalizeProvider */
  public function testDenormalize($input$expected) {
    $resource_type = new ResourceType('node', 'article', FieldableEntityInterface::class);
    $resource_type->setRelatableResourceTypes([]);
    $context = ['resource_type' => $resource_type];
    $denormalized = $this->normalizer->denormalize($input, NULL, 'api_json', $context);
    

class UnwrappinDenormalizerTest extends TestCase
{
    private UnwrappingDenormalizer $denormalizer;
    private MockObject&Serializer $serializer;

    protected function setUp(): void
    {
        $this->serializer = $this->createMock(Serializer::class);
        $this->denormalizer = new UnwrappingDenormalizer();
        $this->denormalizer->setSerializer($this->serializer);
    }

    public function testSupportsNormalization()
    {
        $this->assertTrue($this->denormalizer->supportsDenormalization([], 'stdClass', 'any', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]']));
        $this->assertFalse($this->denormalizer->supportsDenormalization([], 'stdClass', 'any', [UnwrappingDenormalizer::UNWRAP_PATH => '[baz][inner]', 'unwrapped' => true]));
        $this->assertFalse($this->denormalizer->supportsDenormalization([], 'stdClass', 'any', []));
    }

    public function testDenormalize()
    {
        
$serializer = $this->getMockBuilder('Symfony\Component\Serializer\Serializer')
      ->disableOriginalConstructor()
      ->onlyMethods(['normalize'])
      ->getMock();
    $serializer->expects($this->exactly(2))
      ->method('normalize')
      ->withConsecutive(
        [$list_item_1, 'test_format'],
        [$list_item_2, 'test_format'],
      );

    $this->entityNormalizer->setSerializer($serializer);

    $this->entityNormalizer->normalize($content_entity, 'test_format');
  }

  /** * Tests the denormalize() method with no entity type provided in context. * * @covers ::denormalize */
  public function testDenormalizeWithNoEntityType() {
    $this->expectException(UnexpectedValueException::class);
    
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\SerializerAwareInterface;
use Symfony\Component\Serializer\Tests\Fixtures\ScalarDummy;

class CustomNormalizerTest extends TestCase
{
    private CustomNormalizer $normalizer;

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

    public function testInterface()
    {
        $this->assertInstanceOf(NormalizerInterface::class$this->normalizer);
        $this->assertInstanceOf(DenormalizerInterface::class$this->normalizer);
        $this->assertInstanceOf(SerializerAwareInterface::class$this->normalizer);
    }

    public function testSerialize()
    {
        
$d1->bar = 'Bar';
        $d1->baz = 'Baz';
        $d1->qux = 'Quz';
        $d2 = new Dummy();
        $d2->foo = 'FOO';
        $d2->bar = 'BAR';
        $d2->baz = 'BAZ';
        $d2->qux = 'QUZ';
        $obj = new VariadicConstructorTypedArgsDummy($d1$d2);

        $serializer = new Serializer([$normalizer][new JsonEncoder()]);
        $normalizer->setSerializer($serializer);
        $data = $serializer->serialize($obj, 'json');
        $dummy = $normalizer->denormalize(json_decode($data, true), VariadicConstructorTypedArgsDummy::class);
        $this->assertInstanceOf(VariadicConstructorTypedArgsDummy::class$dummy);
        $this->assertCount(2, $dummy->getFoo());
        foreach ($dummy->getFoo() as $foo) {
            $this->assertInstanceOf(Dummy::class$foo);
        }

        $dummy = $serializer->deserialize($data, VariadicConstructorTypedArgsDummy::class, 'json');
        $this->assertInstanceOf(VariadicConstructorTypedArgsDummy::class$dummy);
        $this->assertCount(2, $dummy->getFoo());
        

        $extractor = $this->createMock(PhpDocExtractor::class);
        $extractor->method('getTypes')
            ->will($this->onConsecutiveCalls(
                [new Type('array', false, null, true, new Type('int')new Type('object', false, DummyChild::class))],
                null
            ));

        $denormalizer = new AbstractObjectNormalizerCollectionDummy(null, null, $extractor);
        $arrayDenormalizer = new ArrayDenormalizerDummy();
        $serializer = new SerializerCollectionDummy([$arrayDenormalizer$denormalizer]);
        $arrayDenormalizer->setSerializer($serializer);
        $denormalizer->setSerializer($serializer);

        return $denormalizer;
    }

    public function testDenormalizeStringCollectionDecodedFromXmlWithOneChild()
    {
        $denormalizer = $this->getDenormalizerForStringCollection();

        // if an xml-node can have children which should be deserialized as string[]         // and only one child exists
Address::class => $isCacheable,
            AbstractPart::class => $isCacheable,
        ];
    }

    public function setSerializer(SerializerInterface $serializer): void
    {
        if (!$serializer instanceof NormalizerInterface || !$serializer instanceof DenormalizerInterface) {
            throw new LogicException(sprintf('The passed serializer should implement both NormalizerInterface and DenormalizerInterface, "%s" given.', get_debug_type($serializer)));
        }
        $this->serializer = $serializer;
        $this->normalizer->setSerializer($serializer);
    }

    public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
    {
        if ($object instanceof Headers) {
            $ret = [];
            foreach ($this->headersProperty->getValue($object) as $name => $header) {
                $ret[$name] = $this->serializer->normalize($header$format$context);
            }

            return $ret;
        }
Home | Imprint | This part of the site doesn't use cookies.