So I have many classes I want to serialize with Symfony serializer. For instance
class Foo
{
public $apple = 1;
public $pear = null;
public function serialize() {
Utils::serialize($this);
}
}
which I serialize with the following serialize() call :
class Utils {
public static function serialize($object) {
$encoder = new XmlEncoder();
$normalizer = new ObjectNormalizer();
$serializer = new Serializer(array($normalizer), array($encoder));
$str = $serializer->serialize($object, 'xml')
}
}
The output produced gives me:
<apple>1</apple><pear/>
The output expected should be:
<apple>1</apple>
I took a look at the Symfony 2.8 doc and managed to find a quick solution by using $normalizer->setIgnoredAttributes("pear").
So the improved serialize static function looks like this
class Utils {
public static function ignoreNullAttributes($object) {
$ignored_attributes = array();
foreach($object as $member => $value) {
if (is_null($object->$member)) {
array_push($ignored_attributes, $member);
}
}
return $ignored_attributes;
}
public static function serialize($object) {
$encoder = new XmlEncoder();
$normalizer = new ObjectNormalizer();
$normalizer->setIgnoredAttributes(Utils::ignoreNullAttributes($object));
$serializer = new Serializer(array($normalizer), array($encoder));
$str = $serializer->serialize($object, 'xml')
}
}
However, this solution does not satisfy me since I have more complicated cases where different Foo can be owned by a same class. e.g.
class Bar
{
public $foo1; // (apple=null; pear=2)
public $foo2; // (apple=2; pear=null)
public function serialize() {
Utils::serialize($this);
}
}
Here I cannot use the setIgnoredAttributes method since $foo1 and $foo2 do not have the same null elements. Furthermore, I do not call the serialize method from the child class (i.e. Foo) here so the setIgnoredAttributes is empty.
Without having to write complex introspection code, how can I hide by default null element with Symfony 2.8 serializer ? I have seen for instance that it is enabled by default with JMSSerializer.
elseif (null === $val) { return false; }here github.com/symfony/symfony/blob/2.8/src/Symfony/Component/… resolves your problem, but to do that you need rewrite a lot of code because almost all methods are private intoXmlEncoder:(