Skip to content
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

Feature/different tagnames in xmllist #955

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
104 changes: 104 additions & 0 deletions doc/reference/annotations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,110 @@ Resulting XML:
</post>

You can also specify the entry tag namespace using the ``namespace`` attribute (``@XmlList(inline = true, entry = "comment", namespace="http://www.example.com/ns")``).
If the tag name is determined by the type of the object, use the ``allowTypes`` attribute (see @XmlElementRef).

@XmlElementRef
~~~~~~~~~~~~~~
It is used in the ``allowTypes`` attribute of the ``@XmlList`` annotation to describe the types used.

.. code-block :: php

<?php

namespace JMS\Serializer\Tests\Fixtures;

use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\XmlRoot;
use JMS\Serializer\Annotation\XmlList;
use JMS\Serializer\Annotation\XmlElementRef;

interface ObjectWithXmlListWithObjectTypesInterface
{
}

class ObjectWithXmlListWithObjectTypeA implements ObjectWithXmlListWithObjectTypesInterface
{
/**
* @var string
* @Type(name="string")
*/
private $foo;

/**
* @param string $foo
*/
public function __construct($foo = null)
{
$this->foo = $foo;
}
}

class ObjectWithXmlListWithObjectTypeB implements ObjectWithXmlListWithObjectTypesInterface
{
/**
* @var string
* @Type(name="string")
*/
private $bar;

/**
* @param string $bar
*/
public function __construct($bar = null)
{
$this->bar = $bar;
}
}

/**
* @XmlRoot(name="object")
*/
class ObjectWithXmlListWithObjectType
{
/**
* @var ObjectWithXmlListWithObjectTypesInterface[]
* @Type(name="array<JMS\Serializer\Tests\Fixtures\ObjectWithXmlListWithObjectTypesInterface>")
* @XmlList(inline=true, allowTypes={
* @XmlElementRef(name="TypeA", type="JMS\Serializer\Tests\Fixtures\ObjectWithXmlListWithObjectTypeA"),
* @XmlElementRef(name="TypeB", type="JMS\Serializer\Tests\Fixtures\ObjectWithXmlListWithObjectTypeB")
* })
*/
private $list;

public function __construct()
{
$this->list = self::create();
}

public static function create()
{
return
[
new ObjectWithXmlListWithObjectTypeA('testA'),
new ObjectWithXmlListWithObjectTypeB(),
new ObjectWithXmlListWithObjectTypeA(),
new ObjectWithXmlListWithObjectTypeB('testB'),
]
;
}
}

Resulting XML:

.. code-block :: xml

<?xml version="1.0" encoding="UTF-8"?>
<object>
<TypeA>
<foo><![CDATA[testA]]></foo>
</TypeA>
<TypeB/>
<TypeA/>
<TypeB>
<bar><![CDATA[testB]]></bar>
</TypeB>
</object>


@XmlMap
~~~~~~~
Expand Down
5 changes: 5 additions & 0 deletions src/JMS/Serializer/Annotation/XmlCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,9 @@ abstract class XmlCollection
* @var boolean
*/
public $skipWhenEmpty = true;

/**
* @var array<JMS\Serializer\Annotation\XmlElementRef>
*/
public $allowTypes = [];
}
25 changes: 25 additions & 0 deletions src/JMS/Serializer/Annotation/XmlElementRef.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace JMS\Serializer\Annotation;

/**
* @Annotation
* @Target({"PROPERTY","METHOD","ANNOTATION"})
*/
class XmlElementRef
{
/**
* @var string
*/
public $name;

/**
* @var string
*/
public $namespace;

/**
* @var string
*/
public $type;
}
11 changes: 11 additions & 0 deletions src/JMS/Serializer/Metadata/Driver/AnnotationDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
use JMS\Serializer\Annotation\XmlAttributeMap;
use JMS\Serializer\Annotation\XmlDiscriminator;
use JMS\Serializer\Annotation\XmlElement;
use JMS\Serializer\Annotation\XmlElementRef;
use JMS\Serializer\Annotation\XmlKeyValuePairs;
use JMS\Serializer\Annotation\XmlList;
use JMS\Serializer\Annotation\XmlMap;
Expand Down Expand Up @@ -191,6 +192,16 @@ public function loadMetadataForClass(\ReflectionClass $class)
} elseif ($annot instanceof XmlList) {
$propertyMetadata->xmlCollection = true;
$propertyMetadata->xmlCollectionInline = $annot->inline;
if (!empty($annot->allowTypes)) {
/** @var XmlElementRef $allowType */
foreach ($annot->allowTypes as $allowType) {
$propertyMetadata->xmlAllowTypes[] = [
'type' => $allowType->type,
'name' => $allowType->name,
'namespace' => $allowType->namespace
];
}
}
$propertyMetadata->xmlEntryName = $annot->entry;
$propertyMetadata->xmlEntryNamespace = $annot->namespace;
$propertyMetadata->xmlCollectionSkipWhenEmpty = $annot->skipWhenEmpty;
Expand Down
10 changes: 10 additions & 0 deletions src/JMS/Serializer/Metadata/Driver/XmlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,16 @@ protected function loadMetadataFromFile(\ReflectionClass $class, $path)
if (isset($colConfig->attributes()->namespace)) {
$pMetadata->xmlEntryNamespace = (string)$colConfig->attributes()->namespace;
}

if (isset($colConfig->{'allow-types'}->type) /*&& is_array(($colConfig->{'allow-types'}->type))*/) {
foreach ($colConfig->{'allow-types'}->type as $allowType) {
$pMetadata->xmlAllowTypes[] = [
'type' => $allowType->attributes()->type,
'name' => $allowType->attributes()->name,
'namespace' => $allowType->attributes()->namespace ?: null
];
}
}
}

if (isset($pElem->{'xml-map'})) {
Expand Down
10 changes: 10 additions & 0 deletions src/JMS/Serializer/Metadata/Driver/YamlDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,16 @@ protected function loadMetadataFromFile(\ReflectionClass $class, $file)
if (isset($colConfig['namespace'])) {
$pMetadata->xmlEntryNamespace = (string)$colConfig['namespace'];
}

if (isset($colConfig['allow_types']) && is_array($colConfig['allow_types'])) {
foreach ($colConfig['allow_types'] as $allowType) {
$pMetadata->xmlAllowTypes[] = [
'type' => $allowType['type'],
'name' => $allowType['name'],
'namespace' => array_key_exists('namespace', $allowType) ? $allowType['namespace'] : null
];
}
}
}

if (isset($pConfig['xml_map'])) {
Expand Down
1 change: 1 addition & 0 deletions src/JMS/Serializer/Metadata/PropertyMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class PropertyMetadata extends BasePropertyMetadata
public $xmlNamespace;
public $xmlKeyValuePairs = false;
public $xmlElementCData = true;
public $xmlAllowTypes = null;
public $getter;
public $setter;
public $inline = false;
Expand Down
82 changes: 65 additions & 17 deletions src/JMS/Serializer/XmlDeserializationVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,12 @@ class XmlDeserializationVisitor extends AbstractVisitor implements NullAwareVisi
private $metadataStack;
private $objectMetadataStack;
private $currentObject;

/** @var PropertyMetadata */
private $currentMetadata;
private $result;

/** @var GraphNavigator */
private $navigator;
private $disableExternalEntities = true;
private $doctypeWhitelist = array();
Expand Down Expand Up @@ -150,6 +154,22 @@ public function visitDouble($data, array $type, Context $context)
return $data;
}

private function getTypeForArrayElement($name, $namespace)
{
foreach ($this->currentMetadata->xmlAllowTypes as $xmlAllowType) {
if ($xmlAllowType['name'] == $name && $xmlAllowType['namespace'] == $namespace) {
return ['name' => $xmlAllowType['type'], 'params' => []];
}
}
return null;
}

/**
* @param \SimpleXMLElement $data
* @param array $type
* @param Context $context
* @return array|mixed
*/
public function visitArray($data, array $type, Context $context)
{
// handle key-value-pairs
Expand All @@ -170,27 +190,46 @@ public function visitArray($data, array $type, Context $context)
return $result;
}

$entryName = null !== $this->currentMetadata && $this->currentMetadata->xmlEntryName ? $this->currentMetadata->xmlEntryName : 'entry';
$namespace = null !== $this->currentMetadata && $this->currentMetadata->xmlEntryNamespace ? $this->currentMetadata->xmlEntryNamespace : null;
if (!empty($this->currentMetadata) && !empty($this->currentMetadata->xmlAllowTypes)) {
$allowTypes = $this->currentMetadata->xmlAllowTypes;
}
else {
$entryName = null !== $this->currentMetadata && $this->currentMetadata->xmlEntryName ? $this->currentMetadata->xmlEntryName : 'entry';
$namespace = null !== $this->currentMetadata && $this->currentMetadata->xmlEntryNamespace ? $this->currentMetadata->xmlEntryNamespace : null;
$allowTypes = array(
array(
'name' => $entryName,
'namespace' => $namespace
)
);
}

if ($namespace === null && $this->objectMetadataStack->count()) {
$classMetadata = $this->objectMetadataStack->top();
$namespace = isset($classMetadata->xmlNamespaces['']) ? $classMetadata->xmlNamespaces[''] : $namespace;
if ($namespace === null) {
$namespaces = $data->getDocNamespaces();
if (isset($namespaces[''])) {
$namespace = $namespaces[''];
$queryArray = array();
foreach ($allowTypes as $allowType) {
$entryName = $allowType['name'];
$namespace = $allowType['namespace'] ?: null;

if ($namespace === null && $this->objectMetadataStack->count()) {
$classMetadata = $this->objectMetadataStack->top();
$namespace = isset($classMetadata->xmlNamespaces['']) ? $classMetadata->xmlNamespaces[''] : $namespace;
if ($namespace === null) {
$namespaces = $data->getDocNamespaces();
if (isset($namespaces[''])) {
$namespace = $namespaces[''];
}
}
}
}

if (null !== $namespace) {
$prefix = uniqid('ns-');
$data->registerXPathNamespace($prefix, $namespace);
$nodes = $data->xpath("$prefix:$entryName");
} else {
$nodes = $data->xpath($entryName);
if (null !== $namespace) {
$prefix = uniqid('ns-');
$data->registerXPathNamespace($prefix, $namespace);
$queryArray[] = $prefix . ':' . $entryName;
} else {
$queryArray[] = $entryName;
}
}
$q = implode('|', $queryArray);
$nodes = $data->xpath($q);

if (!count($nodes)) {
if (null === $this->result) {
Expand All @@ -212,7 +251,16 @@ public function visitArray($data, array $type, Context $context)
}

foreach ($nodes as $v) {
$result[] = $this->navigator->accept($v, $type['params'][0], $context);
if (!empty($this->currentMetadata) && !empty($this->currentMetadata->xmlAllowTypes)) {
$t = $this->getTypeForArrayElement($v->getName(), dom_import_simplexml($v)->namespaceURI);
if (!$t) {
continue;
}
}
else {
$t = $type['params'][0];
}
$result[] = $this->navigator->accept($v, $t, $context);
}

return $result;
Expand Down
23 changes: 23 additions & 0 deletions src/JMS/Serializer/XmlSerializationVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,10 @@
*/
class XmlSerializationVisitor extends AbstractVisitor
{
/** @var \DOMDocument */
public $document;

/** @var GraphNavigator */
private $navigator;
private $defaultRootName = 'result';
private $defaultRootNamespace;
Expand All @@ -42,6 +44,8 @@ class XmlSerializationVisitor extends AbstractVisitor
private $stack;
private $metadataStack;
private $currentNode;

/** @var PropertyMetadata */
private $currentMetadata;
private $hasValue;
private $nullWasVisited;
Expand Down Expand Up @@ -167,6 +171,16 @@ public function visitDouble($data, array $type, Context $context)
return $this->visitNumeric($data, $type);
}

private function getTypeForArrayElement($className)
{
foreach ($this->currentMetadata->xmlAllowTypes as $allowType) {
if ($allowType['type'] == $className) {
return $allowType;
}
}
return null;
}

public function visitArray($data, array $type, Context $context)
{
if (null === $this->document) {
Expand All @@ -185,6 +199,15 @@ public function visitArray($data, array $type, Context $context)

$tagName = (null !== $this->currentMetadata && $this->currentMetadata->xmlKeyValuePairs && $this->isElementNameValid($k)) ? $k : $entryName;

if (null !== $this->currentMetadata && !empty($this->currentMetadata->xmlAllowTypes)) {
$type = $this->getTypeForArrayElement(get_class($v));
if ($type) {
$tagName = $type['name'];
$namespace = $type['namespace'];
} else
continue;//or Exception?
}

$entryNode = $this->createElement($tagName, $namespace);
$this->currentNode->appendChild($entryNode);
$this->setCurrentNode($entryNode);
Expand Down
Loading