XmlSerializationTest.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. <?php
  2. namespace JMS\Serializer\Tests\Serializer;
  3. use JMS\Serializer\Construction\UnserializeObjectConstructor;
  4. use JMS\Serializer\Context;
  5. use JMS\Serializer\Exception\InvalidArgumentException;
  6. use JMS\Serializer\GraphNavigator;
  7. use JMS\Serializer\Handler\DateHandler;
  8. use JMS\Serializer\Handler\HandlerRegistry;
  9. use JMS\Serializer\Metadata\StaticPropertyMetadata;
  10. use JMS\Serializer\Naming\CamelCaseNamingStrategy;
  11. use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
  12. use JMS\Serializer\Naming\SerializedNameAnnotationStrategy;
  13. use JMS\Serializer\SerializationContext;
  14. use JMS\Serializer\Serializer;
  15. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlAttributeDiscriminatorChild;
  16. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlAttributeDiscriminatorParent;
  17. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlNamespaceAttributeDiscriminatorChild;
  18. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlNamespaceAttributeDiscriminatorParent;
  19. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlNamespaceDiscriminatorChild;
  20. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlNamespaceDiscriminatorParent;
  21. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlNotCDataDiscriminatorChild;
  22. use JMS\Serializer\Tests\Fixtures\Discriminator\ObjectWithXmlNotCDataDiscriminatorParent;
  23. use JMS\Serializer\Tests\Fixtures\Input;
  24. use JMS\Serializer\Tests\Fixtures\InvalidUsageOfXmlValue;
  25. use JMS\Serializer\Tests\Fixtures\ObjectWithNamespacesAndList;
  26. use JMS\Serializer\Tests\Fixtures\ObjectWithNamespacesAndNestedList;
  27. use JMS\Serializer\Tests\Fixtures\ObjectWithToString;
  28. use JMS\Serializer\Tests\Fixtures\ObjectWithVirtualXmlProperties;
  29. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlKeyValuePairs;
  30. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlKeyValuePairsWithObjectType;
  31. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlKeyValuePairsWithType;
  32. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlNamespaces;
  33. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlNamespacesAndObjectProperty;
  34. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlNamespacesAndObjectPropertyAuthor;
  35. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlNamespacesAndObjectPropertyVirtual;
  36. use JMS\Serializer\Tests\Fixtures\ObjectWithXmlRootNamespace;
  37. use JMS\Serializer\Tests\Fixtures\Person;
  38. use JMS\Serializer\Tests\Fixtures\PersonCollection;
  39. use JMS\Serializer\Tests\Fixtures\PersonLocation;
  40. use JMS\Serializer\Tests\Fixtures\SimpleClassObject;
  41. use JMS\Serializer\Tests\Fixtures\SimpleObject;
  42. use JMS\Serializer\Tests\Fixtures\SimpleSubClassObject;
  43. use JMS\Serializer\XmlDeserializationVisitor;
  44. use JMS\Serializer\XmlSerializationVisitor;
  45. use PhpCollection\Map;
  46. class XmlSerializationTest extends BaseSerializationTest
  47. {
  48. /**
  49. * @expectedException JMS\Serializer\Exception\RuntimeException
  50. */
  51. public function testInvalidUsageOfXmlValue()
  52. {
  53. $obj = new InvalidUsageOfXmlValue();
  54. $this->serialize($obj);
  55. }
  56. /**
  57. * @dataProvider getXMLBooleans
  58. */
  59. public function testXMLBooleans($xmlBoolean, $boolean)
  60. {
  61. if ($this->hasDeserializer()) {
  62. $this->assertSame($boolean, $this->deserialize('<result>' . $xmlBoolean . '</result>', 'boolean'));
  63. }
  64. }
  65. public function getXMLBooleans()
  66. {
  67. return array(array('true', true), array('false', false), array('1', true), array('0', false));
  68. }
  69. public function testAccessorSetterDeserialization()
  70. {
  71. /** @var \JMS\Serializer\Tests\Fixtures\AccessorSetter $object */
  72. $object = $this->deserialize('<?xml version="1.0"?>
  73. <AccessorSetter>
  74. <element attribute="attribute">element</element>
  75. <collection>
  76. <entry>collectionEntry</entry>
  77. </collection>
  78. </AccessorSetter>',
  79. 'JMS\Serializer\Tests\Fixtures\AccessorSetter'
  80. );
  81. $this->assertInstanceOf('stdClass', $object->getElement());
  82. $this->assertInstanceOf('JMS\Serializer\Tests\Fixtures\AccessorSetterElement', $object->getElement()->element);
  83. $this->assertEquals('attribute-different', $object->getElement()->element->getAttribute());
  84. $this->assertEquals('element-different', $object->getElement()->element->getElement());
  85. $this->assertEquals(['collectionEntry' => 'collectionEntry'], $object->getCollection());
  86. }
  87. public function testPropertyIsObjectWithAttributeAndValue()
  88. {
  89. $personCollection = new PersonLocation;
  90. $person = new Person;
  91. $person->name = 'Matthias Noback';
  92. $person->age = 28;
  93. $personCollection->person = $person;
  94. $personCollection->location = 'The Netherlands';
  95. $this->assertEquals($this->getContent('person_location'), $this->serialize($personCollection));
  96. }
  97. public function testPropertyIsCollectionOfObjectsWithAttributeAndValue()
  98. {
  99. $personCollection = new PersonCollection;
  100. $person = new Person;
  101. $person->name = 'Matthias Noback';
  102. $person->age = 28;
  103. $personCollection->persons->add($person);
  104. $personCollection->location = 'The Netherlands';
  105. $this->assertEquals($this->getContent('person_collection'), $this->serialize($personCollection));
  106. }
  107. /**
  108. * @expectedException JMS\Serializer\Exception\InvalidArgumentException
  109. * @expectedExceptionMessage The document type "<!DOCTYPE author [<!ENTITY foo SYSTEM "php://filter/read=convert.base64-encode/resource=XmlSerializationTest.php">]>" is not allowed. If it is safe, you may add it to the whitelist configuration.
  110. */
  111. public function testExternalEntitiesAreDisabledByDefault()
  112. {
  113. $this->deserialize('<?xml version="1.0"?>
  114. <!DOCTYPE author [
  115. <!ENTITY foo SYSTEM "php://filter/read=convert.base64-encode/resource=' . basename(__FILE__) . '">
  116. ]>
  117. <result>
  118. &foo;
  119. </result>', 'stdClass');
  120. }
  121. /**
  122. * @expectedException JMS\Serializer\Exception\InvalidArgumentException
  123. * @expectedExceptionMessage The document type "<!DOCTYPE foo>" is not allowed. If it is safe, you may add it to the whitelist configuration.
  124. */
  125. public function testDocumentTypesAreNotAllowed()
  126. {
  127. $this->deserialize('<?xml version="1.0"?><!DOCTYPE foo><foo></foo>', 'stdClass');
  128. }
  129. public function testWhitelistedDocumentTypesAreAllowed()
  130. {
  131. $this->deserializationVisitors->get('xml')->get()->setDoctypeWhitelist(array(
  132. '<!DOCTYPE authorized SYSTEM "http://authorized_url.dtd">',
  133. '<!DOCTYPE author [<!ENTITY foo SYSTEM "php://filter/read=convert.base64-encode/resource=' . basename(__FILE__) . '">]>'));
  134. $this->serializer->deserialize('<?xml version="1.0"?>
  135. <!DOCTYPE authorized SYSTEM "http://authorized_url.dtd">
  136. <foo></foo>', 'stdClass', 'xml');
  137. $this->serializer->deserialize('<?xml version="1.0"?>
  138. <!DOCTYPE author [
  139. <!ENTITY foo SYSTEM "php://filter/read=convert.base64-encode/resource=' . basename(__FILE__) . '">
  140. ]>
  141. <foo></foo>', 'stdClass', 'xml');
  142. }
  143. public function testVirtualAttributes()
  144. {
  145. $this->assertEquals(
  146. $this->getContent('virtual_attributes'),
  147. $this->serialize(new ObjectWithVirtualXmlProperties(), SerializationContext::create()->setGroups(array('attributes')))
  148. );
  149. }
  150. public function testVirtualValues()
  151. {
  152. $this->assertEquals(
  153. $this->getContent('virtual_values'),
  154. $this->serialize(new ObjectWithVirtualXmlProperties(), SerializationContext::create()->setGroups(array('values')))
  155. );
  156. }
  157. public function testVirtualXmlList()
  158. {
  159. $this->assertEquals(
  160. $this->getContent('virtual_properties_list'),
  161. $this->serialize(new ObjectWithVirtualXmlProperties(), SerializationContext::create()->setGroups(array('list')))
  162. );
  163. }
  164. public function testVirtualXmlMap()
  165. {
  166. $this->assertEquals(
  167. $this->getContent('virtual_properties_map'),
  168. $this->serialize(new ObjectWithVirtualXmlProperties(), SerializationContext::create()->setGroups(array('map')))
  169. );
  170. }
  171. public function testUnserializeMissingArray()
  172. {
  173. $xml = '<result></result>';
  174. $object = $this->serializer->deserialize($xml, 'JMS\Serializer\Tests\Fixtures\ObjectWithAbsentXmlListNode', 'xml');
  175. $this->assertEquals($object->absentAndNs, array());
  176. $xml = '<result xmlns:x="http://www.example.com">
  177. <absent_and_ns>
  178. <x:entry>foo</x:entry>
  179. </absent_and_ns>
  180. </result>';
  181. $object = $this->serializer->deserialize($xml, 'JMS\Serializer\Tests\Fixtures\ObjectWithAbsentXmlListNode', 'xml');
  182. $this->assertEquals($object->absentAndNs, array("foo"));
  183. }
  184. public function testObjectWithNamespacesAndList()
  185. {
  186. $object = new ObjectWithNamespacesAndList();
  187. $object->name = 'name';
  188. $object->nameAlternativeB = 'nameB';
  189. $object->phones = array('111', '222');
  190. $object->addresses = array('A' => 'Street 1', 'B' => 'Street 2');
  191. $object->phonesAlternativeB = array('555', '666');
  192. $object->addressesAlternativeB = array('A' => 'Street 5', 'B' => 'Street 6');
  193. $object->phonesAlternativeC = array('777', '888');
  194. $object->addressesAlternativeC = array('A' => 'Street 7', 'B' => 'Street 8');
  195. $object->phonesAlternativeD = array('999', 'AAA');
  196. $object->addressesAlternativeD = array('A' => 'Street 9', 'B' => 'Street A');
  197. $this->assertEquals(
  198. $this->getContent('object_with_namespaces_and_list'),
  199. $this->serialize($object, SerializationContext::create())
  200. );
  201. $this->assertEquals(
  202. $object,
  203. $this->deserialize($this->getContent('object_with_namespaces_and_list'), get_class($object))
  204. );
  205. }
  206. public function testObjectWithNamespaceAndNestedList()
  207. {
  208. $object = new ObjectWithNamespacesAndNestedList();
  209. $personCollection = new PersonCollection();
  210. $personA = new Person();
  211. $personA->age = 11;
  212. $personA->name = 'AAA';
  213. $personB = new Person();
  214. $personB->age = 22;
  215. $personB->name = 'BBB';
  216. $personCollection->persons->add($personA);
  217. $personCollection->persons->add($personB);
  218. $object->personCollection = $personCollection;
  219. $this->assertEquals(
  220. $this->getContent('object_with_namespaces_and_nested_list'),
  221. $this->serialize($object, SerializationContext::create())
  222. );
  223. $this->assertEquals(
  224. $object,
  225. $this->deserialize($this->getContent('object_with_namespaces_and_nested_list'), get_class($object))
  226. );
  227. }
  228. public function testArrayKeyValues()
  229. {
  230. $this->assertEquals($this->getContent('array_key_values'), $this->serializer->serialize(new ObjectWithXmlKeyValuePairs(), 'xml'));
  231. }
  232. public function testDeserializeArrayKeyValues()
  233. {
  234. $xml = $this->getContent('array_key_values_with_type_1');
  235. $result = $this->serializer->deserialize($xml, ObjectWithXmlKeyValuePairsWithType::class, 'xml');
  236. $this->assertInstanceOf(ObjectWithXmlKeyValuePairsWithType::class, $result);
  237. $this->assertEquals(ObjectWithXmlKeyValuePairsWithType::create1(), $result);
  238. $xml2 = $this->getContent('array_key_values_with_type_2');
  239. $result2 = $this->serializer->deserialize($xml2, ObjectWithXmlKeyValuePairsWithType::class, 'xml');
  240. $this->assertInstanceOf(ObjectWithXmlKeyValuePairsWithType::class, $result2);
  241. $this->assertEquals(ObjectWithXmlKeyValuePairsWithType::create2(), $result2);
  242. }
  243. public function testDeserializeTypedAndNestedArrayKeyValues()
  244. {
  245. $xml = $this->getContent('array_key_values_with_nested_type');
  246. $result = $this->serializer->deserialize($xml, ObjectWithXmlKeyValuePairsWithObjectType::class, 'xml');
  247. $this->assertInstanceOf(ObjectWithXmlKeyValuePairsWithObjectType::class, $result);
  248. $this->assertEquals(ObjectWithXmlKeyValuePairsWithObjectType::create1(), $result);
  249. }
  250. /**
  251. * @dataProvider getDateTime
  252. * @group datetime
  253. */
  254. public function testDateTimeNoCData($key, $value, $type)
  255. {
  256. $handlerRegistry = new HandlerRegistry();
  257. $handlerRegistry->registerSubscribingHandler(new DateHandler(\DateTime::ISO8601, 'UTC', false));
  258. $objectConstructor = new UnserializeObjectConstructor();
  259. $serializer = new Serializer($this->factory, $handlerRegistry, $objectConstructor, $this->serializationVisitors, $this->deserializationVisitors);
  260. $this->assertEquals($this->getContent($key . '_no_cdata'), $serializer->serialize($value, $this->getFormat()));
  261. }
  262. /**
  263. * @dataProvider getDateTimeImmutable
  264. * @group datetime
  265. */
  266. public function testDateTimeImmutableNoCData($key, $value, $type)
  267. {
  268. $handlerRegistry = new HandlerRegistry();
  269. $handlerRegistry->registerSubscribingHandler(new DateHandler(\DateTime::ISO8601, 'UTC', false));
  270. $objectConstructor = new UnserializeObjectConstructor();
  271. $serializer = new Serializer($this->factory, $handlerRegistry, $objectConstructor, $this->serializationVisitors, $this->deserializationVisitors);
  272. $this->assertEquals($this->getContent($key . '_no_cdata'), $serializer->serialize($value, $this->getFormat()));
  273. }
  274. /**
  275. * @expectedException JMS\Serializer\Exception\RuntimeException
  276. * @expectedExceptionMessage Unsupported value type for XML attribute map. Expected array but got object
  277. */
  278. public function testXmlAttributeMapWithoutArray()
  279. {
  280. $attributes = new \ArrayObject(array(
  281. 'type' => 'text',
  282. ));
  283. $this->serializer->serialize(new Input($attributes), $this->getFormat());
  284. }
  285. public function testObjectWithOnlyNamespacesAndList()
  286. {
  287. $object = new ObjectWithNamespacesAndList();
  288. $object->phones = array();
  289. $object->addresses = array();
  290. $object->phonesAlternativeB = array();
  291. $object->addressesAlternativeB = array();
  292. $object->phonesAlternativeC = array('777', '888');
  293. $object->addressesAlternativeC = array('A' => 'Street 7', 'B' => 'Street 8');
  294. $object->phonesAlternativeD = array();
  295. $object->addressesAlternativeD = array();
  296. $this->assertEquals(
  297. $this->getContent('object_with_only_namespaces_and_list'),
  298. $this->serialize($object, SerializationContext::create())
  299. );
  300. $deserialized = $this->deserialize($this->getContent('object_with_only_namespaces_and_list'), get_class($object));
  301. $this->assertEquals($object, $deserialized);
  302. }
  303. public function testDeserializingNull()
  304. {
  305. $this->markTestSkipped('Not supported in XML.');
  306. }
  307. public function testDeserializeWithObjectWithToStringMethod()
  308. {
  309. $input = new ObjectWithToString($this->getContent('simple_object'));
  310. $object = $this->deserialize($input, SimpleObject::class);
  311. $this->assertInstanceOf(SimpleObject::class, $object);
  312. }
  313. public function testObjectWithXmlNamespaces()
  314. {
  315. $object = new ObjectWithXmlNamespaces('This is a nice title.', 'Foo Bar', new \DateTime('2011-07-30 00:00', new \DateTimeZone('UTC')), 'en');
  316. $serialized = $this->serialize($object);
  317. $this->assertEquals($this->getContent('object_with_xml_namespaces'), $this->serialize($object));
  318. $xml = simplexml_load_string($this->serialize($object));
  319. $xml->registerXPathNamespace('ns1', "http://purl.org/dc/elements/1.1/");
  320. $xml->registerXPathNamespace('ns2', "http://schemas.google.com/g/2005");
  321. $xml->registerXPathNamespace('ns3', "http://www.w3.org/2005/Atom");
  322. $this->assertEquals('2011-07-30T00:00:00+0000', $this->xpathFirstToString($xml, './@created_at'));
  323. $this->assertEquals('1edf9bf60a32d89afbb85b2be849e3ceed5f5b10', $this->xpathFirstToString($xml, './@ns2:etag'));
  324. $this->assertEquals('en', $this->xpathFirstToString($xml, './@ns1:language'));
  325. $this->assertEquals('This is a nice title.', $this->xpathFirstToString($xml, './ns1:title'));
  326. $this->assertEquals('Foo Bar', $this->xpathFirstToString($xml, './ns3:author'));
  327. $deserialized = $this->deserialize($this->getContent('object_with_xml_namespacesalias'), get_class($object));
  328. $this->assertEquals('2011-07-30T00:00:00+0000', $this->getField($deserialized, 'createdAt')->format(\DateTime::ISO8601));
  329. $this->assertAttributeEquals('This is a nice title.', 'title', $deserialized);
  330. $this->assertAttributeSame('1edf9bf60a32d89afbb85b2be849e3ceed5f5b10', 'etag', $deserialized);
  331. $this->assertAttributeSame('en', 'language', $deserialized);
  332. $this->assertAttributeEquals('Foo Bar', 'author', $deserialized);
  333. }
  334. public function testObjectWithXmlNamespacesAndBackReferencedNamespaces()
  335. {
  336. $author = new ObjectWithXmlNamespacesAndObjectPropertyAuthor('mr', 'smith');
  337. $object = new ObjectWithXmlNamespacesAndObjectProperty('This is a nice title.', $author);
  338. $serialized = $this->serialize($object);
  339. $this->assertEquals($this->getContent('object_with_xml_namespaces_and_object_property'), $serialized);
  340. }
  341. public function testObjectWithXmlNamespacesAndBackReferencedNamespacesWithListeners()
  342. {
  343. $author = new ObjectWithXmlNamespacesAndObjectPropertyAuthor('mr', 'smith');
  344. $object = new ObjectWithXmlNamespacesAndObjectPropertyVirtual('This is a nice title.', new \stdClass());
  345. $this->handlerRegistry->registerHandler(GraphNavigator::DIRECTION_SERIALIZATION, 'ObjectWithXmlNamespacesAndObjectPropertyAuthorVirtual', $this->getFormat(),
  346. function (XmlSerializationVisitor $visitor, $data, $type, Context $context) use ($author) {
  347. $factory = $context->getMetadataFactory(get_class($author));
  348. $classMetadata = $factory->getMetadataForClass(get_class($author));
  349. $metadata = new StaticPropertyMetadata(get_class($author), 'foo', $author);
  350. $metadata->xmlNamespace = $classMetadata->xmlRootNamespace;
  351. $metadata->xmlNamespace = $classMetadata->xmlRootNamespace;
  352. $visitor->visitProperty($metadata, $author, $context);
  353. }
  354. );
  355. $serialized = $this->serialize($object);
  356. $this->assertEquals($this->getContent('object_with_xml_namespaces_and_object_property_virtual'), $serialized);
  357. }
  358. public function testObjectWithXmlRootNamespace()
  359. {
  360. $object = new ObjectWithXmlRootNamespace('This is a nice title.', 'Foo Bar', new \DateTime('2011-07-30 00:00', new \DateTimeZone('UTC')), 'en');
  361. $this->assertEquals($this->getContent('object_with_xml_root_namespace'), $this->serialize($object));
  362. }
  363. public function testXmlNamespacesInheritance()
  364. {
  365. $object = new SimpleClassObject();
  366. $object->foo = 'foo';
  367. $object->bar = 'bar';
  368. $object->moo = 'moo';
  369. $this->assertEquals($this->getContent('simple_class_object'), $this->serialize($object));
  370. $childObject = new SimpleSubClassObject();
  371. $childObject->foo = 'foo';
  372. $childObject->bar = 'bar';
  373. $childObject->moo = 'moo';
  374. $childObject->baz = 'baz';
  375. $childObject->qux = 'qux';
  376. $this->assertEquals($this->getContent('simple_subclass_object'), $this->serialize($childObject));
  377. }
  378. public function testWithoutFormatedOutputByXmlSerializationVisitor()
  379. {
  380. $namingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy());
  381. $xmlVisitor = new XmlSerializationVisitor($namingStrategy);
  382. $xmlVisitor->setFormatOutput(false);
  383. $visitors = new Map(array(
  384. 'xml' => new XmlSerializationVisitor($namingStrategy),
  385. ));
  386. $serializer = new Serializer(
  387. $this->factory,
  388. $this->handlerRegistry,
  389. new UnserializeObjectConstructor(),
  390. $visitors,
  391. $this->deserializationVisitors,
  392. $this->dispatcher
  393. );
  394. $object = new SimpleClassObject;
  395. $object->foo = 'foo';
  396. $object->bar = 'bar';
  397. $object->moo = 'moo';
  398. $stringXml = $serializer->serialize($object, $this->getFormat());
  399. $this->assertXmlStringEqualsXmlString($this->getContent('simple_class_object_minified'), $stringXml);
  400. }
  401. public function testDiscriminatorAsXmlAttribute()
  402. {
  403. $xml = $this->serialize(new ObjectWithXmlAttributeDiscriminatorChild());
  404. $this->assertEquals($this->getContent('xml_discriminator_attribute'), $xml);
  405. $this->assertInstanceOf(
  406. ObjectWithXmlAttributeDiscriminatorChild::class,
  407. $this->deserialize(
  408. $xml,
  409. ObjectWithXmlAttributeDiscriminatorParent::class
  410. )
  411. );
  412. }
  413. public function testDiscriminatorAsNotCData()
  414. {
  415. $xml = $this->serialize(new ObjectWithXmlNotCDataDiscriminatorChild());
  416. $this->assertEquals($this->getContent('xml_discriminator_not_cdata'), $xml);
  417. $this->assertInstanceOf(
  418. ObjectWithXmlNotCDataDiscriminatorChild::class,
  419. $this->deserialize(
  420. $xml,
  421. ObjectWithXmlNotCDataDiscriminatorParent::class
  422. )
  423. );
  424. }
  425. public function testDiscriminatorWithNamespace()
  426. {
  427. $xml = $this->serialize(new ObjectWithXmlNamespaceDiscriminatorChild());
  428. $this->assertEquals($this->getContent('xml_discriminator_namespace'), $xml);
  429. $this->assertInstanceOf(
  430. ObjectWithXmlNamespaceDiscriminatorChild::class,
  431. $this->deserialize(
  432. $xml,
  433. ObjectWithXmlNamespaceDiscriminatorParent::class
  434. )
  435. );
  436. }
  437. public function testDiscriminatorAsXmlAttributeWithNamespace()
  438. {
  439. $xml = $this->serialize(new ObjectWithXmlNamespaceAttributeDiscriminatorChild());
  440. $this->assertEquals($this->getContent('xml_discriminator_namespace_attribute'), $xml);
  441. $this->assertInstanceOf(
  442. ObjectWithXmlNamespaceAttributeDiscriminatorChild::class,
  443. $this->deserialize(
  444. $xml,
  445. ObjectWithXmlNamespaceAttributeDiscriminatorParent::class
  446. )
  447. );
  448. }
  449. /**
  450. * @expectedException \JMS\Serializer\Exception\XmlErrorException
  451. */
  452. public function testDeserializeEmptyString()
  453. {
  454. $this->deserialize('', 'stdClass');
  455. }
  456. public function testEvaluatesToNull()
  457. {
  458. $namingStrategy = $this->getMockBuilder(PropertyNamingStrategyInterface::class)->getMock();
  459. $visitor = new XmlDeserializationVisitor($namingStrategy);
  460. $xsdNilAsTrueElement = simplexml_load_string('<empty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>');
  461. $xsdNilAsOneElement = simplexml_load_string('<empty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="1"/>');
  462. $this->assertTrue($visitor->isNull($xsdNilAsTrueElement));
  463. $this->assertTrue($visitor->isNull($xsdNilAsOneElement));
  464. $this->assertTrue($visitor->isNull(null));
  465. }
  466. private function xpathFirstToString(\SimpleXMLElement $xml, $xpath)
  467. {
  468. $nodes = $xml->xpath($xpath);
  469. return (string)reset($nodes);
  470. }
  471. /**
  472. * @param string $key
  473. */
  474. protected function getContent($key)
  475. {
  476. if (!file_exists($file = __DIR__ . '/xml/' . $key . '.xml')) {
  477. throw new InvalidArgumentException(sprintf('The key "%s" is not supported.', $key));
  478. }
  479. return file_get_contents($file);
  480. }
  481. protected function getFormat()
  482. {
  483. return 'xml';
  484. }
  485. }