Skip to content

Allow to not skip empty not inline array root node #611

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jul 26, 2016
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/JMS/Serializer/Annotation/XmlCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,9 @@ abstract class XmlCollection
* @var string
*/
public $namespace;

/**
* @var boolean
*/
public $skip_when_empty = true;
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we use this casing for other annotations? I think we already use camelCasing, no?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

true, will fix it

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

}
1 change: 1 addition & 0 deletions src/JMS/Serializer/Metadata/Driver/AnnotationDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ public function loadMetadataForClass(\ReflectionClass $class)
$propertyMetadata->xmlCollectionInline = $annot->inline;
$propertyMetadata->xmlEntryName = $annot->entry;
$propertyMetadata->xmlEntryNamespace = $annot->namespace;
$propertyMetadata->xmlCollectionSkipWhenEmpty = $annot->skip_when_empty;
} elseif ($annot instanceof XmlMap) {
$propertyMetadata->xmlCollection = true;
$propertyMetadata->xmlCollectionInline = $annot->inline;
Expand Down
7 changes: 7 additions & 0 deletions src/JMS/Serializer/Metadata/Driver/XmlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ protected function loadMetadataFromFile(\ReflectionClass $class, $path)
}

if (isset($pElem->{'xml-list'})) {

$pMetadata->xmlCollection = true;

$colConfig = $pElem->{'xml-list'};
Expand All @@ -172,6 +173,12 @@ protected function loadMetadataFromFile(\ReflectionClass $class, $path)
if (isset($colConfig->attributes()->{'entry-name'})) {
$pMetadata->xmlEntryName = (string) $colConfig->attributes()->{'entry-name'};
}

if (isset($colConfig->attributes()->{'skip-when-empty'})) {
$pMetadata->xmlCollectionSkipWhenEmpty = 'true' === (string) $colConfig->attributes()->{'skip-when-empty'};
} else {
$pMetadata->xmlCollectionSkipWhenEmpty = true;
}

if (isset($colConfig->attributes()->namespace)) {
$pMetadata->xmlEntryNamespace = (string) $colConfig->attributes()->namespace;
Expand Down
10 changes: 8 additions & 2 deletions src/JMS/Serializer/Metadata/Driver/YamlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,17 @@ protected function loadMetadataFromFile(\ReflectionClass $class, $file)

$colConfig = $pConfig['xml_list'];
if (isset($colConfig['inline'])) {
$pMetadata->xmlCollectionInline = (Boolean) $colConfig['inline'];
$pMetadata->xmlCollectionInline = (Boolean)$colConfig['inline'];
}

if (isset($colConfig['entry_name'])) {
$pMetadata->xmlEntryName = (string) $colConfig['entry_name'];
$pMetadata->xmlEntryName = (string)$colConfig['entry_name'];
}

if (isset($colConfig['skip_when_empty'])) {
$pMetadata->xmlCollectionSkipWhenEmpty = (Boolean)$colConfig['skip_when_empty'];
} else {
$pMetadata->xmlCollectionSkipWhenEmpty = true;
}

if (isset($colConfig['namespace'])) {
Expand Down
6 changes: 6 additions & 0 deletions src/JMS/Serializer/Metadata/PropertyMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class PropertyMetadata extends BasePropertyMetadata
public $type;
public $xmlCollection = false;
public $xmlCollectionInline = false;
public $xmlCollectionSkipWhenEmpty = true;
public $xmlEntryName;
public $xmlEntryNamespace;
public $xmlKeyAttribute;
Expand Down Expand Up @@ -134,6 +135,7 @@ public function serialize()
$this->maxDepth,
parent::serialize(),
'xmlEntryNamespace' => $this->xmlEntryNamespace,
'xmlCollectionSkipWhenEmpty' => $this->xmlCollectionSkipWhenEmpty,
));
}

Expand Down Expand Up @@ -167,6 +169,10 @@ public function unserialize($str)
if (isset($unserialized['xmlEntryNamespace'])){
$this->xmlEntryNamespace = $unserialized['xmlEntryNamespace'];
}
if (isset($unserialized['xmlCollectionSkipWhenEmpty'])){
$this->xmlCollectionSkipWhenEmpty = $unserialized['xmlCollectionSkipWhenEmpty'];
}


parent::unserialize($parentStr);
}
Expand Down
13 changes: 5 additions & 8 deletions src/JMS/Serializer/XmlDeserializationVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,16 +267,13 @@ public function visitProperty(PropertyMetadata $metadata, $data, Context $contex
$prefix = uniqid('ns-');
$data->registerXPathNamespace($prefix, $namespaces['']);
$nodes = $data->xpath('./'.$prefix. ':'.$name );
if (empty($nodes)) {
return;
}
$node = reset($nodes);
} else {
if (!isset($data->$name)) {
return;
}
$node = $data->$name;
$nodes = $data->xpath('./'. $name );
}
if (empty($nodes)) {
return;
}
$node = reset($nodes);
}

$v = $this->navigator->accept($node, $metadata->type, $context);
Expand Down
30 changes: 15 additions & 15 deletions src/JMS/Serializer/XmlSerializationVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -303,15 +303,19 @@ public function visitProperty(PropertyMetadata $metadata, $object, Context $cont
if ($addEnclosingElement) {
$this->revertCurrentNode();

if ($element->hasChildNodes() || $element->hasAttributes()
|| (isset($metadata->type['name']) && $metadata->type['name'] === 'array' && isset($metadata->type['params'][1]))) {
if ($this->nodeNotEmpty($element) || ((!$metadata->xmlCollection || !$metadata->xmlCollectionSkipWhenEmpty) && $node === null && $v !== null && !$context->isVisiting($v))) {
$this->currentNode->appendChild($element);
}
}

$this->hasValue = false;
}

private function nodeNotEmpty(\DOMElement $element)
{
return $element->hasChildNodes() || $element->hasAttributes();
}

public function endVisitingObject(ClassMetadata $metadata, $data, array $type, Context $context)
{
$this->objectMetadataStack->pop();
Expand Down Expand Up @@ -439,21 +443,17 @@ private function addNamespaceAttributes(ClassMetadata $metadata, \DOMElement $el

private function createElement($tagName, $namespace = null)
{
if (null !== $namespace) {

if ($this->currentNode->isDefaultNamespace($namespace)) {
return $this->document->createElementNS($namespace, $tagName);
} else {
if (!$prefix = $this->currentNode->lookupPrefix($namespace)) {
$prefix = 'ns-'. substr(sha1($namespace), 0, 8);
}
return $this->document->createElementNS($namespace, $prefix . ':' . $tagName);
}


} else {
if (null === $namespace) {
return $this->document->createElement($tagName);
}
if ($this->currentNode->isDefaultNamespace($namespace)) {
return $this->document->createElementNS($namespace, $tagName);
}
if (!($prefix = $this->currentNode->lookupPrefix($namespace)) && !($prefix = $this->document->lookupPrefix($namespace))) {
$prefix = 'ns-'. substr(sha1($namespace), 0, 8);
return $this->document->createElementNS($namespace, $prefix . ':' . $tagName);
}
return $this->document->createElement($prefix . ':' . $tagName);
}

private function setAttributeOnNode(\DOMElement $node, $name, $value, $namespace = null)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* Copyright 2013 Johannes M. Schmitt <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace JMS\Serializer\Tests\Fixtures;

use JMS\Serializer\Annotation as Serializer;

class ObjectWithAbsentXmlListNode
{
/**
* @Serializer\XmlList(inline=false, entry="comment", skip_when_empty=true)
* @Serializer\Type("array<string>")
*/
public $absent;
/**
* @Serializer\XmlList(inline=false, entry="comment", skip_when_empty=false)
* @Serializer\Type("array<string>")
*/
public $present;

/**
* @Serializer\XmlList(inline=false, entry="comment")
* @Serializer\Type("array<string>")
*/
public $skipDefault;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php

/*
* Copyright 2013 Johannes M. Schmitt <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace JMS\Serializer\Tests\Fixtures;

use JMS\Serializer\Annotation as Serializer;

class ObjectWithEmptyNullableAndEmptyArrays
{
/**
* @Serializer\XmlList(inline = true, entry = "comment")
* @Serializer\Type("array")
*/
public $null_inline = null;

/**
* @Serializer\XmlList(inline = true, entry = "comment")
* @Serializer\Type("array")
*/
public $empty_inline = [];


/**
* @Serializer\XmlList(inline = true, entry = "comment")
* @Serializer\Type("array")
*/
public $not_empty_inline = ['not_empty_inline'];

/**
* @Serializer\XmlList(inline = false, entry = "comment")
* @Serializer\Type("array")
*/
public $null_not_inline = null;

/**
* @Serializer\XmlList(inline = false, entry = "comment")
* @Serializer\Type("array")
*/
public $empty_not_inline = [];

/**
* @Serializer\XmlList(inline = false, entry = "comment", skip_when_empty=false)
* @Serializer\Type("array")
*/
public $not_empty_not_inline = ['not_empty_not_inline'];

/**
* @Serializer\XmlList(inline = false, entry = "comment", skip_when_empty=false)
* @Serializer\Type("array")
*/
public $null_not_inline_skip = null;

/**
* @Serializer\XmlList(inline = false, entry = "comment", skip_when_empty=false)
* @Serializer\Type("array")
*/
public $empty_not_inline_skip = [];


/**
* @Serializer\XmlList(inline = false, entry = "comment", skip_when_empty=false)
* @Serializer\Type("array")
*/
public $not_empty_not_inline_skip = ['not_empty_not_inline_skip'];
}
13 changes: 13 additions & 0 deletions tests/JMS/Serializer/Tests/Metadata/Driver/BaseDriverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ public function testLoadBlogPostMetadata()
$this->assertEquals($p, $m->propertyMetadata['price']);
}

public function testXMLListAbsentNode()
{
$m = $this->getDriver()->loadMetadataForClass(new \ReflectionClass('JMS\Serializer\Tests\Fixtures\ObjectWithAbsentXmlListNode'));

$this->assertArrayHasKey('absent', $m->propertyMetadata);
$this->assertArrayHasKey('present', $m->propertyMetadata);
$this->assertArrayHasKey('skipDefault', $m->propertyMetadata);

$this->assertTrue($m->propertyMetadata['absent']->xmlCollectionSkipWhenEmpty);
$this->assertTrue($m->propertyMetadata['skipDefault']->xmlCollectionSkipWhenEmpty);
$this->assertFalse($m->propertyMetadata['present']->xmlCollectionSkipWhenEmpty);
}

public function testVirtualProperty()
{
$m = $this->getDriver()->loadMetadataForClass(new \ReflectionClass('JMS\Serializer\Tests\Fixtures\ObjectWithVirtualProperties'));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Metadata\VirtualPropertyMetadata;

$className = 'JMS\Serializer\Tests\Fixtures\ObjectWithAbsentXmlListNode';

$metadata = new ClassMetadata( $className );

$pMetadata = new PropertyMetadata($className, 'absent');
$pMetadata->xmlCollectionSkipWhenEmpty = true;
$metadata->addPropertyMetadata($pMetadata);

$pMetadata = new PropertyMetadata($className, 'present');
$pMetadata->xmlCollectionSkipWhenEmpty = false;
$metadata->addPropertyMetadata($pMetadata);

$pMetadata = new PropertyMetadata($className, 'skipDefault');
$metadata->addPropertyMetadata($pMetadata);


return $metadata;
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<serializer>
<class name="JMS\Serializer\Tests\Fixtures\ObjectWithAbsentXmlListNode">
<property name="absent">
<type>array</type>
<xml-list skip-when-empty="true"/>
</property>
<property name="present">
<type>array</type>
<xml-list skip-when-empty="false"/>
</property>
<property name="skipDefault">
<type>array</type>
</property>
</class>
</serializer>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
JMS\Serializer\Tests\Fixtures\ObjectWithAbsentXmlListNode:
properties:
absent:
type: array
xml_list:
skip_when_empty: true
present:
type: array
xml_list:
skip_when_empty: false
skipDefault:
type: array
xml_list:
inline: false
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use JMS\Serializer\Tests\Fixtures\Garage;
use JMS\Serializer\Tests\Fixtures\InlineChildEmpty;
use JMS\Serializer\Tests\Fixtures\NamedDateTimeArraysObject;
use JMS\Serializer\Tests\Fixtures\ObjectWithEmptyNullableAndEmptyArrays;
use JMS\Serializer\Tests\Fixtures\ObjectWithIntListAndIntMap;
use JMS\Serializer\Tests\Fixtures\Tag;
use JMS\Serializer\Tests\Fixtures\Timestamp;
Expand Down Expand Up @@ -977,6 +978,12 @@ public function testDeserializingIntoExistingObject()
$this->assertAttributeInstanceOf('JMS\Serializer\Tests\Fixtures\Price', 'cost', $deseralizedOrder);
}

public function testObjectWithNullableArrays()
{
$object = new ObjectWithEmptyNullableAndEmptyArrays();
$this->assertEquals($this->getContent('nullable_arrays'), $this->serializer->serialize($object, $this->getFormat()));
}

abstract protected function getContent($key);
abstract protected function getFormat();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ protected function getContent($key)
$outputs['car_without_type'] = '{"km":5}';
$outputs['garage'] = '{"vehicles":[{"km":3,"type":"car"},{"km":1,"type":"moped"}]}';
$outputs['tree'] = '{"tree":{"children":[{"children":[{"children":[],"foo":"bar"}],"foo":"bar"}],"foo":"bar"}}';
$outputs['nullable_arrays'] = '{"empty_inline":[],"not_empty_inline":["not_empty_inline"],"empty_not_inline":[],"not_empty_not_inline":["not_empty_not_inline"],"empty_not_inline_skip":[],"not_empty_not_inline_skip":["not_empty_not_inline_skip"]}';
}

if (!isset($outputs[$key])) {
Expand Down
Loading