DEV Community

Richard McHale
Richard McHale

Posted on

1

PHP - Creating a pretty printing JMS Serializer at runtime

I needed to create a pretty printing JMS Serializer for a unit test, and couldn't find a good example. So here's one for the next person.

Note: If doing this application wide I'd recommend using the config instead, as specified here http://jmsyst.com/bundles/JMSSerializerBundle/master/configuration#extension-reference

    private function createPrettyPrintingJsonSerializer(): Serializer
    {
        $builder = SerializerBuilder::create();
        $builder->setSerializationVisitor(
            'json',
            (new JsonSerializationVisitorFactory())->setOptions(JSON_PRETTY_PRINT)
        );
        return $builder->build();
    }
Enter fullscreen mode Exit fullscreen mode
    public function testUsingTheSerializer(): void
    {
        $serializer = $this->createPrettyPrintingJsonSerializer();

        $data = [
            'a' => 't1',
            'b' => 't2',
        ];

        print($serializer->serialize($data, 'json'));
    }
Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay