Skip to content
Merged
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
88 changes: 88 additions & 0 deletions doc/reference/annotations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,94 @@ will need to wrap your custom strategy with the ``SerializedNameattributeStrateg
)
->build();

XML Specific Usage
------------------

When serializing to or deserializing from XML, ``#[SerializedName]`` supports special
syntax to map PHP properties to XML attributes. This can be useful for more complex
XML structures where ``#[XmlAttribute]`` might not suffice. These syntaxes work for
both serialization and deserialization.

1. **Attribute on the current element:**
To map a property as an attribute of the XML element that represents the current
class instance, prefix the attribute name with ``@``.

.. code-block:: php

<?php
use JMS\Serializer\Annotation as Serializer;

#[Serializer\XmlRoot("user")]
class User
{
#[Serializer\SerializedName("@id")]
#[Serializer\Type("integer")]
private $id; // Becomes an attribute "id" on the <user> element

#[Serializer\SerializedName("name")]
#[Serializer\Type("string")]
private $name; // Becomes a child element <name>

public function __construct(int $id, string $name)
{
$this->id = $id;
$this->name = $name;
}
}

// Example: $user = new User(1, 'John Doe');
// Serializes to: <user id="1"><name>John Doe</name></user>

2. **Attribute on a sibling element:**
To map a property as an attribute on a *sibling* XML element, use the
syntax ``"ElementName/@AttributeName"``. The property's value will
become an attribute named ``AttributeName`` on a sibling XML element named
``ElementName``. Your PHP class should typically have one property that defines
the sibling element's value (e.g., ``ElementName``) and another property that
defines its attribute (e.g., ``ElementName/@AttributeName``).

.. code-block:: php

<?php
use JMS\Serializer\Annotation as Serializer;

#[Serializer\XmlRoot("item")]
class Item
{
/**
* This property defines the <identifier> XML element.
*/
#[Serializer\SerializedName("identifier")]
#[Serializer\Type("string")]
#[Serializer\XmlElement(cdata: false)]
private $identifierValue;

/**
* This property becomes the "scheme" attribute on the <identifier> element.
*/
#[Serializer\SerializedName("identifier/@scheme")]
#[Serializer\Type("string")]
#[Serializer\XmlElement(cdata: false)] // Namespace can be specified here if needed via namespace: "http://..."
private $identifierScheme;

public function __construct(string $identifierValue, string $identifierScheme)
{
$this->identifierValue = $identifierValue;
$this->identifierScheme = $identifierScheme;
}
}

// Example: $item = new Item('ABC', 'product_sku');
// Serializes to: <item><identifier scheme="product_sku">ABC</identifier></item>

During serialization, if a property mapped to an attribute has a ``null`` value,
the attribute will not be rendered on the XML element.
The ``#[XmlElement]`` annotation can be used on properties mapped with these
syntaxes, for instance, to control the XML namespace of the attribute if it
differs from the element's namespace (though typically attributes inherit the
namespace of their element or have no namespace).


#[Since]
~~~~~~~~
This attribute can be defined on a property to specify starting from which
Expand Down
64 changes: 64 additions & 0 deletions src/XmlDeserializationVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,70 @@ public function visitProperty(PropertyMetadata $metadata, $data)
throw new NotAcceptableException();
}

if (0 === strpos($name, '@')) {
$attributeName = substr($name, 1);
$attributes = $data->attributes($metadata->xmlNamespace);

if (isset($attributes[$attributeName])) {
if (!$metadata->type) {
throw RuntimeException::noMetadataForProperty($metadata->class, $metadata->name);
}

return $this->navigator->accept($attributes[$attributeName], $metadata->type);
}

throw new NotAcceptableException(sprintf('Attribute "%s" (derived from serializedName "%s") in namespace "%s" not found for property %s::$%s. XML: %s', $attributeName, $name, $metadata->xmlNamespace ?? '[none]', $metadata->class, $metadata->name, $data->asXML()));
}

if (false !== strpos($name, '/@')) {
[$elementName, $attributeName] = explode('/@', $name, 2);

$childDataNode = null;
if ('' === $metadata->xmlNamespace) {
// Element explicitly in NO namespace
$xpathQuery = "./*[local-name()='" . $elementName . "' and (namespace-uri()='' or not(namespace-uri()))]";
$matchingNodes = $data->xpath($xpathQuery);
if (!empty($matchingNodes)) {
$childDataNode = $matchingNodes[0];
}
} elseif ($metadata->xmlNamespace) {
// Element in a specific namespace URI
$childrenInNs = $data->children($metadata->xmlNamespace);
if (isset($childrenInNs->$elementName)) {
$childDataNode = $childrenInNs->$elementName;
}
} else {
// xmlNamespace is null: element in default namespace (or no namespace if no default is active)
$childrenInDefaultOrNoNs = $data->children(null);
if (isset($childrenInDefaultOrNoNs->$elementName)) {
$childDataNode = $childrenInDefaultOrNoNs->$elementName;
}
}

if (!$childDataNode || !$childDataNode->getName()) {
if (null === $metadata->xmlNamespace) {
$ns = '[default/none]';
} else {
$ns = '' === $metadata->xmlNamespace ? '[none]' : $metadata->xmlNamespace;
}

throw new NotAcceptableException(sprintf('Child element "%s" for attribute access not found (element namespace: %s). Property %s::$%s. XML: %s', $elementName, $ns, $metadata->class, $metadata->name, $data->asXML()));
}

$attributeTargetNs = $metadata->xmlNamespace && '' !== $metadata->xmlNamespace ? $metadata->xmlNamespace : null;
$attributes = $childDataNode->attributes($attributeTargetNs);

if (isset($attributes[$attributeName])) {
if (!$metadata->type) {
throw RuntimeException::noMetadataForProperty($metadata->class, $metadata->name);
}

return $this->navigator->accept($attributes[$attributeName], $metadata->type);
}

throw new NotAcceptableException(sprintf('Attribute "%s" on element "%s" not found (attribute namespace: %s). Property %s::$%s. XML: %s', $attributeName, $elementName, $attributeTargetNs ?? '[none]', $metadata->class, $metadata->name, $data->asXML()));
}

if ($metadata->xmlValue) {
if (!$metadata->type) {
throw RuntimeException::noMetadataForProperty($metadata->class, $metadata->name);
Expand Down
91 changes: 91 additions & 0 deletions src/XmlSerializationVisitor.php
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,28 @@ public function visitProperty(PropertyMetadata $metadata, $v): void
return;
}

if (false !== strpos($metadata->serializedName, '/@') && $this->trySerializePropertyAsAttributeOnSiblingElement($metadata, $v)) {
return;
}

if (0 === strpos($metadata->serializedName, '@')) {
[$attributeValue, $processedNode] = $this->processValueForXmlAttribute($v, $metadata->type, $metadata);

if (null === $v && null === $processedNode) {
return;
}

$attributeName = substr($metadata->serializedName, 1);

if ($this->currentNode instanceof \DOMElement) {
$this->setAttributeOnNode($this->currentNode, $attributeName, $attributeValue, $metadata->xmlNamespace);
} else {
throw new RuntimeException('Cannot set attribute on a non-element node.');
}

return;
}

if ($addEnclosingElement = !$this->isInLineCollection($metadata) && !$metadata->inline) {
$namespace = $metadata->xmlNamespace ?? $this->getClassDefaultNamespace($this->objectMetadataStack->top());

Expand Down Expand Up @@ -354,6 +376,75 @@ public function visitProperty(PropertyMetadata $metadata, $v): void
$this->hasValue = false;
}

private function trySerializePropertyAsAttributeOnSiblingElement(PropertyMetadata $metadata, $v): bool
{
[$elementName, $attributeName] = explode('/@', $metadata->serializedName, 2);
$namespace = $metadata->xmlNamespace ?? $this->getClassDefaultNamespace($this->objectMetadataStack->top());
$targetElement = null;

if ($this->currentNode instanceof \DOMElement) {
foreach ($this->currentNode->childNodes as $childNode) {
if ($childNode instanceof \DOMElement && $childNode->localName === $elementName) {
$isNamespaceMatch = false;
// Case 1: Expected a specific namespace, and child node has it.
// Case 2 (else): Expected no namespace
if (null !== $namespace && $childNode->namespaceURI === $namespace) {
$isNamespaceMatch = true;
} elseif ((null === $namespace || '' === $namespace) && (null === $childNode->namespaceURI || '' === $childNode->namespaceURI)) {
$isNamespaceMatch = true;
}

if ($isNamespaceMatch) {
$targetElement = $childNode;
break;
}
}
}
}

if (!$targetElement) {
return false;
}

if (null === $v) {
return true;
}

[$attributeStringValue, $attributeValueNode] = $this->processValueForXmlAttribute($v, $metadata->type, $metadata);

if (null !== $attributeValueNode || is_scalar($v)) {
$this->setAttributeOnNode($targetElement, $attributeName, $attributeStringValue, $metadata->xmlNamespace);
}

return true;
}

/**
* @return array{0:string, 1:\DOMNode|null} string value for attribute, and the processed DOMNode/null.
*
* @throws RuntimeException If the value is unsuitable for an XML attribute.
*/
private function processValueForXmlAttribute($inputValue, ?array $valueType, PropertyMetadata $metadataForNavigatorContext): array
{
$this->setCurrentMetadata($metadataForNavigatorContext);
$processedNode = $this->navigator->accept($inputValue, $valueType);
$this->revertCurrentMetadata();

if ($processedNode instanceof \DOMCharacterData) {
$stringValue = $processedNode->nodeValue;
} elseif (null === $processedNode) {
$stringValue = is_scalar($inputValue) ? (string) $inputValue : '';
} else {
throw new RuntimeException(sprintf(
'Unsupported value for XML attribute for property "%s". Expected character data or scalar, but got %s.',
$metadataForNavigatorContext->name,
\is_object($processedNode) ? \get_class($processedNode) : \gettype($processedNode),
));
}

return [$stringValue, $processedNode];
}

private function isInLineCollection(PropertyMetadata $metadata): bool
{
return $metadata->xmlCollection && $metadata->xmlCollectionInline;
Expand Down
60 changes: 60 additions & 0 deletions tests/Fixtures/ObjectWithAttributeSyntax.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests\Fixtures;

use JMS\Serializer\Annotation as Serializer;

/**
* @Serializer\XmlRoot("test-object")
* @Serializer\XmlNamespace(uri="http://example.com/default", prefix="")
* @Serializer\XmlNamespace(uri="http://example.com/ns1", prefix="ns1")
*/
class ObjectWithAttributeSyntax
{
/**
* @Serializer\SerializedName("Value")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false)
*/
public $value;

/**
* @Serializer\SerializedName("@Identifier")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false)
*/
public $testIdentifier;

/**
* @Serializer\SerializedName("@NamespacedIdentifier")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false, namespace="http://example.com/ns1")
*/
public $testIdentifierNs;

/**
* @Serializer\SerializedName("@NullableIdentifier")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false)
*/
public $nullableIdentifierValue = null;

/**
* @Serializer\SerializedName("@NamespacedNullableIdentifier")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false, namespace="http://example.com/ns1")
*/
public $nullableIdentifierScheme = null;

public function __construct(
string $value,
string $testIdentifier,
string $testIdentifierNs
) {
$this->value = $value;
$this->testIdentifier = $testIdentifier;
$this->testIdentifierNs = $testIdentifierNs;
}
}
49 changes: 49 additions & 0 deletions tests/Fixtures/ObjectWithAttributeSyntaxWithoutNs.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace JMS\Serializer\Tests\Fixtures;

use JMS\Serializer\Annotation as Serializer;

/**
* @Serializer\XmlRoot("test-object")
*/
class ObjectWithAttributeSyntaxWithoutNs
{
/**
* @Serializer\SerializedName("Value")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false)
*/
public $value;

/**
* @Serializer\SerializedName("@Identifier")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false)
*/
public $testIdentifier;

/**
* @Serializer\SerializedName("@NullableIdentifier")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false)
*/
public $nullableIdentifierValue = null;

/**
* @Serializer\SerializedName("@NullableIdentifierScheme")
* @Serializer\Type("string")
* @Serializer\XmlElement(cdata=false)
*/
public $nullableIdentifierScheme = null;

public function __construct(
string $value,
string $testIdentifier
) {
$this->value = $value;
$this->testIdentifier = $testIdentifier;
}
}
Loading
Loading