Skip to content
This repository was archived by the owner on Jan 29, 2020. It is now read-only.

Commit 5ec9f3c

Browse files
committed
Render DateTime values using ISO 8601 format via XmlRenderer
As reported in #3, the `JsonRenderer` benefits from the fact that PHP will serialize `DateTime` instances to a JSON object. For the `XmlRenderer`, we instead detect if the value is a `DateTimeInterface`, and, if so, call its `format()` method using the "c" format (ISO 8601).
1 parent 41a15e8 commit 5ec9f3c

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/Renderer/XmlRenderer.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
namespace Zend\Expressive\Hal\Renderer;
99

10+
use DateTimeInterface;
1011
use DOMDocument;
1112
use DOMNode;
1213
use Zend\Expressive\Hal\HalResource;
@@ -152,17 +153,20 @@ private function createNodeTree(DOMDocument $doc, DOMNode $node, array $data) :
152153
* @todo Detect JsonSerializable, and pass to
153154
* json_decode(json_encode($object), true), passing the final value
154155
* back to createResourceElement()?
155-
* @todo How should we handle DateTimeInterface implementations?
156-
* $date->format('c')?
157156
* @param object $object
158157
* @throws Exception\InvalidResourceValueException if unable to serialize
159158
* the data to a string.
160159
*/
161160
private function createDataFromObject($object) : string
162161
{
162+
if ($object instanceof DateTimeInterface) {
163+
return $object->format('c');
164+
}
165+
163166
if (! method_exists($object, '__toString')) {
164167
throw Exception\InvalidResourceValueException::fromObject($object);
165168
}
169+
166170
return (string) $object;
167171
}
168172
}

test/Renderer/XmlRendererTest.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ public function testRendersExpectedXmlPayload()
6565
$this->assertSame($expected, $renderer->render($resource));
6666
}
6767

68+
/**
69+
* @see https://github.com/zendframework/zend-expressive-hal/issues/3
70+
*/
6871
public function testCanRenderPhpDateTimeInstances()
6972
{
7073
$dateTime = new DateTime('now');
@@ -75,6 +78,6 @@ public function testCanRenderPhpDateTimeInstances()
7578

7679
$renderer = new XmlRenderer();
7780
$xml = $renderer->render($resource);
78-
$this->assertContains((string) $dateTime, $xml);
81+
$this->assertContains($dateTime->format('c'), $xml);
7982
}
8083
}

0 commit comments

Comments
 (0)