Serializer example

$stampSenders = $stamp->getTransportNames();
        $this->assertEquals(\count($configuredSenders), \count($stampSenders));

        foreach ($configuredSenders as $key => $sender) {
            $this->assertSame($sender$stampSenders[$key]);
        }
    }

    public function testDeserialization()
    {
        $stamp = new TransportNamesStamp(['foo']);
        $serializer = new Serializer(
            new SymfonySerializer([
                new ArrayDenormalizer(),
                new ObjectNormalizer(),
            ][new JsonEncoder()])
        );

        $deserializedEnvelope = $serializer->decode($serializer->encode(new Envelope(new \stdClass()[$stamp])));

        $deserializedStamp = $deserializedEnvelope->last(TransportNamesStamp::class);
        $this->assertInstanceOf(TransportNamesStamp::class$deserializedStamp);
        $this->assertEquals($stamp$deserializedStamp);
    }
EOF;

        $extractor = new PhpDocExtractor();
        $propertyNormalizer = new PropertyNormalizer(null, null, $extractor);
        $serializer = new Serializer([
            new ArrayDenormalizer(),
            new MimeMessageNormalizer($propertyNormalizer),
            new ObjectNormalizer(null, null, null, $extractor),
            $propertyNormalizer,
        ][new JsonEncoder()]);

        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n = $serializer->deserialize($serialized, TemplatedEmail::class, 'json');
        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        
return;
            }

            usleep(100 * 1000); // 100ms         }

        throw new \RuntimeException('Expected output never arrived. Got "'.$process->getOutput().'" instead.');
    }

    private function createSerializer(): SerializerInterface
    {
        return new Serializer(
            new SerializerComponent\Serializer([new ObjectNormalizer()new ArrayDenormalizer()]['json' => new JsonEncoder()])
        );
    }

    private function assertApproximateDuration($startTime, int $expectedDuration)
    {
        $actualDuration = microtime(true) - $startTime;

        if (method_exists($this, 'assertEqualsWithDelta')) {
            $this->assertEqualsWithDelta($expectedDuration$actualDuration, .5, 'Duration was not within expected range');
        } else {
            
public function testConstructorWithObjectTypeHintDenormalize()
    {
        $data = [
            'id' => 10,
            'inner' => [
                'foo' => 'oof',
                'bar' => 'rab',
            ],
        ];

        $normalizer = new ObjectNormalizer();
        $serializer = new Serializer([$normalizer]);
        $normalizer->setSerializer($serializer);

        $obj = $normalizer->denormalize($data, DummyWithConstructorObject::class);
        $this->assertInstanceOf(DummyWithConstructorObject::class$obj);
        $this->assertEquals(10, $obj->getId());
        $this->assertInstanceOf(ObjectInner::class$obj->getInner());
        $this->assertEquals('oof', $obj->getInner()->foo);
        $this->assertEquals('rab', $obj->getInner()->bar);
    }

    public function testConstructorWithUnconstructableNullableObjectTypeHintDenormalize()
    {
->method('collectDenormalize')
            ->with($this->isType('string'), 'data', 'type', 'format', $this->isType('array')$this->isType('float'));
        $dataCollector
            ->expects($this->once())
            ->method('collectEncode')
            ->with($this->isType('string'), 'data', 'format', $this->isType('array')$this->isType('float'));
        $dataCollector
            ->expects($this->once())
            ->method('collectDecode')
            ->with($this->isType('string'), 'data', 'format', $this->isType('array')$this->isType('float'));

        $traceableSerializer = new TraceableSerializer(new Serializer()$dataCollector);

        $traceableSerializer->serialize('data', 'format');
        $traceableSerializer->deserialize('data', 'type', 'format');
        $traceableSerializer->normalize('data', 'format');
        $traceableSerializer->denormalize('data', 'type', 'format');
        $traceableSerializer->encode('data', 'format');
        $traceableSerializer->decode('data', 'format');
    }

    public function testAddDebugTraceIdInContext()
    {
        
EOF;

        $extractor = new PhpDocExtractor();
        $propertyNormalizer = new PropertyNormalizer(null, null, $extractor);
        $serializer = new Serializer([
            new ArrayDenormalizer(),
            new MimeMessageNormalizer($propertyNormalizer),
            new ObjectNormalizer(null, null, null, $extractor),
            $propertyNormalizer,
        ][new JsonEncoder()]);

        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        $this->assertSame($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n = $serializer->deserialize($serialized, Email::class, 'json');
        $serialized = $serializer->serialize($e, 'json', [ObjectNormalizer::IGNORED_ATTRIBUTES => ['cachedBody']]);
        
EOF;

        $extractor = new PhpDocExtractor();
        $propertyNormalizer = new PropertyNormalizer(null, null, $extractor);
        $serializer = new Serializer([
            new ArrayDenormalizer(),
            new MimeMessageNormalizer($propertyNormalizer),
            new ObjectNormalizer(null, null, null, $extractor),
            $propertyNormalizer,
        ][new JsonEncoder()]);

        $serialized = $serializer->serialize($e, 'json');
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n = $serializer->deserialize($serialized, Message::class, 'json');
        $this->assertEquals($expected$n);

        
public static function serializerDataProvider(): \Generator
    {
        yield ['{{ object|serialize }}', '{"name":"howdy","title":"fixture"}'];
        yield ['{{ object|serialize(\'yaml\') }}', '{ name: howdy, title: fixture }'];
        yield ['{{ object|serialize(\'yaml\', {groups: \'read\'}) }}', '{ name: howdy }'];
    }

    private function getTwig(string $template): Environment
    {
        $meta = new ClassMetadataFactory(new AnnotationLoader());
        $runtime = new SerializerRuntime(new Serializer([new ObjectNormalizer($meta)][new JsonEncoder()new YamlEncoder()]));

        $mockRuntimeLoader = $this->createMock(RuntimeLoaderInterface::class);
        $mockRuntimeLoader
            ->method('load')
            ->willReturnMap([
                ['Symfony\Bridge\Twig\Extension\SerializerRuntime', $runtime],
            ])
        ;

        $twig = new Environment(new ArrayLoader(['template' => $template]));
        $twig->addExtension(new SerializerExtension());
        
/** * @covers ::on4xx */
  public function testOn4xx() {
    $kernel = $this->prophesize(HttpKernelInterface::class);
    $request = Request::create('/test');
    $request->setRequestFormat('json');

    $e = new MethodNotAllowedHttpException(['POST', 'PUT'], 'test message');
    $event = new ExceptionEvent($kernel->reveal()$request, HttpKernelInterface::MAIN_REQUEST, $e);
    $subscriber = new DefaultExceptionSubscriber(new Serializer([][new JsonEncoder()])[]);
    $subscriber->on4xx($event);
    $response = $event->getResponse();

    $this->assertInstanceOf(Response::class$response);
    $this->assertEquals('{"message":"test message"}', $response->getContent());
    $this->assertEquals(405, $response->getStatusCode());
    $this->assertEquals('POST, PUT', $response->headers->get('Allow'));
    $this->assertEquals('application/json', $response->headers->get('Content-Type'));
  }

}
return new PropertyNormalizer();
    }

    protected function getNormalizerForCallbacksWithPropertyTypeExtractor(): PropertyNormalizer
    {
        return new PropertyNormalizer(null, null, $this->getCallbackPropertyTypeExtractor());
    }

    protected function getNormalizerForCircularReference(array $defaultContext): PropertyNormalizer
    {
        $normalizer = new PropertyNormalizer(null, null, null, null, null, $defaultContext);
        new Serializer([$normalizer]);

        return $normalizer;
    }

    protected function getSelfReferencingModel()
    {
        return new PropertyCircularReferenceDummy();
    }

    public function testSiblingReference()
    {
        
throw new InvalidArgumentException();
            }

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

        $discriminatorResolver = new ClassDiscriminatorFromClassMetadata($loaderMock);
        $normalizer = new AbstractObjectNormalizerDummy($factory, null, new PhpDocExtractor()$discriminatorResolver);
        $serializer = new Serializer([$normalizer]);
        $normalizer->setSerializer($serializer);
        $normalizedData = $normalizer->denormalize(['foo' => 'foo', 'baz' => 'baz', 'quux' => ['value' => 'quux'], 'type' => 'second'], AbstractDummy::class);

        $this->assertInstanceOf(DummySecondChildQuux::class$normalizedData->quux);
    }

    public function testDenormalizeWithDiscriminatorMapAndObjectToPopulateUsesCorrectClassname()
    {
        $factory = new ClassMetadataFactory(new AnnotationLoader());

        $loaderMock = new class() implements ClassMetadataFactoryInterface {
            
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()
    {
        
return [
            'id' => 1,
            'body' => '{"message": "Hi"}',
            'headers' => [
                'type' => DummyMessage::class,
            ],
        ];
    }

    private function createSerializer(): Serializer
    {
        $serializer = new Serializer(
            new SerializerComponent\Serializer([new ObjectNormalizer()]['json' => new JsonEncoder()])
        );

        return $serializer;
    }
}
$this->assertEquals($this->testArray, $this->encoder->decode('test', 'test'));
  }

  /** * @covers ::getBaseEncoder */
  public function testDefaultEncoderHasSerializer() {
    // The serializer should be set on the Drupal encoder, which should then     // set it on our default encoder.     $encoder = new XmlEncoder();
    $serializer = new Serializer([new GetSetMethodNormalizer()]);
    $encoder->setSerializer($serializer);
    $base_encoder = $encoder->getBaseEncoder();
    $this->assertInstanceOf(BaseXmlEncoder::class$base_encoder);
    // Test the encoder.     $base_encoder->encode(['a' => new TestObject()], 'xml');
  }

}

class TestObject {

  
use PHPUnit\Framework\TestCase;
use Symfony\Component\ErrorHandler\ErrorRenderer\SerializerErrorRenderer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ProblemNormalizer;
use Symfony\Component\Serializer\Serializer;

class SerializerErrorRendererTest extends TestCase
{
    public function testDefaultContent()
    {
        $errorRenderer = new SerializerErrorRenderer(new Serializer(), 'html');

        self::assertStringContainsString('<h2>The server returned a "500 Internal Server Error".</h2>', $errorRenderer->render(new \RuntimeException())->getAsString());
    }

    public function testSerializerContent()
    {
        $exception = new \RuntimeException('Foo');
        $errorRenderer = new SerializerErrorRenderer(
            new Serializer([new ProblemNormalizer()][new JsonEncoder()]),
            fn () => 'json'
        );

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