Description
Symfony version(s) affected
6.1.2 - 6.13
Description
The Q&A sums it up perfectly: #46117
I noticed it as I was trying to set the below, but noticed it wasn't being honored by the serializer or it's friends:
framework:
serializer:
default_context:
skip_null_values: true
Problem:
I have been learning Symfony 6 and I got stuck on a weird behaviour of the Serializer component.
Default instance of Serializer service seems to be ignoring default context set in config file. I am not sure if this is a bug in the framework or rather my misunderstanding how the component and the framework work, but the situation can be easily reproduced in a fresh project.
How to reproduce
Steps to reproduce:
Environment: PHP 8.1.4, Symfony CLI 5.4.7, Symfony 6.0.7.
- Create a fresh project by executing
symfony local:new --webapp demo
.- Generate a skeleton console command by executing
bin/console make:command app:demo
.- Open the generated
config/packages/framework.yaml
and configure Serializer to pretty-print JSON:framework: # ... serializer: default_context: json_encode_options: 128 # value of JSON_PRETTY_PRINT
- Open the generated
App\Command\DemoCommand
class and request dependency on Serializer in constructor:public function __construct( private \Symfony\Component\Serializer\SerializerInterface $serializer, ) { parent::__construct(); }
- Modify command's
execute
method to demonstrate the bug:protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $data = [ 'foo' => 'bar', 'baz' => ['a' => 'b'], ]; $context = [ // exactly what was configured in default context 'json_encode_options' => JSON_PRETTY_PRINT, ]; $io->info($this->serializer->serialize($data, 'json')); // this should use default context $io->info($this->serializer->serialize($data, 'json', $context)); // this uses manually configured context return Command::SUCCESS; }
- Execute the command to see the bug:
$ bin/console -vvv app:wat [INFO] {"foo":"bar","baz":{"a":"b"}} [INFO] { "foo": "bar", "baz": { "a": "b" } }If my understanding of Symfony's documentation is correct, both calls to
serialize
should return the same output. Is this really a bug or did I misunderstood something?
Possible Solution
No response
Additional Context
No response