Browse Source

Handle entities and value objects that implement toArray() correctly.

Entities will be values in the collection, and eventually end up in
`_createChild` where they need to be array cast before they can be
serialized into xml.
mark_story 12 years ago
parent
commit
64f654e667
2 changed files with 22 additions and 0 deletions
  1. 3 0
      src/Utility/Xml.php
  2. 19 0
      tests/TestCase/Utility/XmlTest.php

+ 3 - 0
src/Utility/Xml.php

@@ -302,6 +302,9 @@ class Xml {
 	protected static function _createChild($data) {
 		extract($data);
 		$childNS = $childValue = null;
+		if (method_exists($value, 'toArray')) {
+			$value = $value->toArray();
+		}
 		if (is_array($value)) {
 			if (isset($value['@'])) {
 				$childValue = (string)$value['@'];

+ 19 - 0
tests/TestCase/Utility/XmlTest.php

@@ -16,6 +16,7 @@ namespace Cake\Test\TestCase\Utility;
 
 use Cake\Collection\Collection;
 use Cake\Core\Configure;
+use Cake\ORM\Entity;
 use Cake\TestSuite\TestCase;
 use Cake\Utility\Error\XmlException;
 use Cake\Utility\Xml;
@@ -132,6 +133,24 @@ class XmlTest extends TestCase {
 	}
 
 /**
+ * Test build() with ORM\Entity instances wrapped in a Collection.
+ *
+ * @return void
+ */
+	public function testBuildOrmEntity() {
+		$user = new Entity(['username' => 'mark', 'email' => 'mark@example.com']);
+		$xml = new Collection([
+			'response' => [
+				'users' => new Collection([$user])
+			]
+		]);
+		$obj = Xml::build($xml);
+		$output = $obj->saveXML();
+		$this->assertContains('<username>mark</username>', $output);
+		$this->assertContains('<email>mark@example.com</email>', $output);
+	}
+
+/**
  * data provider function for testBuildInvalidData
  *
  * @return array