BaseSerializationTest.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. <?php
  2. /*
  3. * Copyright 2011 Johannes M. Schmitt <schmittjoh@gmail.com>
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. namespace JMS\SerializerBundle\Tests\Serializer;
  18. use JMS\SerializerBundle\Tests\Fixtures\AccessorOrderParent;
  19. use JMS\SerializerBundle\Tests\Fixtures\AccessorOrderChild;
  20. use JMS\SerializerBundle\Tests\Fixtures\GetSetObject;
  21. use JMS\SerializerBundle\Tests\Fixtures\IndexedCommentsBlogPost;
  22. use JMS\SerializerBundle\Tests\Fixtures\CurrencyAwareOrder;
  23. use JMS\SerializerBundle\Tests\Fixtures\CurrencyAwarePrice;
  24. use JMS\SerializerBundle\Tests\Fixtures\Order;
  25. use Symfony\Component\Yaml\Inline;
  26. use JMS\SerializerBundle\Serializer\YamlSerializationVisitor;
  27. use Doctrine\Common\Collections\ArrayCollection;
  28. use Symfony\Component\Form\Form;
  29. use Symfony\Component\Form\FormError;
  30. use Symfony\Component\Validator\ConstraintViolation;
  31. use Symfony\Component\Validator\ConstraintViolationList;
  32. use JMS\SerializerBundle\Serializer\Handler\DeserializationHandlerInterface;
  33. use JMS\SerializerBundle\Serializer\Handler\SerializationHandlerInterface;
  34. use JMS\SerializerBundle\Tests\Fixtures\AuthorList;
  35. use JMS\SerializerBundle\Serializer\VisitorInterface;
  36. use JMS\SerializerBundle\Serializer\XmlDeserializationVisitor;
  37. use JMS\SerializerBundle\Serializer\Construction\UnserializeObjectConstructor;
  38. use JMS\SerializerBundle\Serializer\JsonDeserializationVisitor;
  39. use JMS\SerializerBundle\Tests\Fixtures\Log;
  40. use JMS\SerializerBundle\Serializer\Handler\ArrayCollectionHandler;
  41. use JMS\SerializerBundle\Serializer\Handler\ObjectBasedCustomHandler;
  42. use JMS\SerializerBundle\Serializer\Handler\DateTimeHandler;
  43. use JMS\SerializerBundle\Serializer\Handler\FormErrorHandler;
  44. use JMS\SerializerBundle\Serializer\Handler\ConstraintViolationHandler;
  45. use JMS\SerializerBundle\Serializer\Handler\DoctrineProxyHandler;
  46. use JMS\SerializerBundle\Tests\Fixtures\Comment;
  47. use JMS\SerializerBundle\Tests\Fixtures\Author;
  48. use JMS\SerializerBundle\Tests\Fixtures\AuthorReadOnly;
  49. use JMS\SerializerBundle\Tests\Fixtures\BlogPost;
  50. use JMS\SerializerBundle\Tests\Fixtures\ObjectWithLifecycleCallbacks;
  51. use JMS\SerializerBundle\Tests\Fixtures\CircularReferenceParent;
  52. use JMS\SerializerBundle\Tests\Fixtures\InlineParent;
  53. use JMS\SerializerBundle\Tests\Fixtures\GroupsObject;
  54. use JMS\SerializerBundle\Tests\Fixtures\ObjectWithVirtualProperties;
  55. use JMS\SerializerBundle\Serializer\XmlSerializationVisitor;
  56. use Doctrine\Common\Annotations\AnnotationReader;
  57. use JMS\SerializerBundle\Metadata\Driver\AnnotationDriver;
  58. use Metadata\MetadataFactory;
  59. use JMS\SerializerBundle\Tests\Fixtures\SimpleObject;
  60. use JMS\SerializerBundle\Tests\Fixtures\SimpleObjectProxy;
  61. use JMS\SerializerBundle\Tests\Fixtures\Price;
  62. use JMS\SerializerBundle\Serializer\Naming\CamelCaseNamingStrategy;
  63. use JMS\SerializerBundle\Serializer\Naming\SerializedNameAnnotationStrategy;
  64. use JMS\SerializerBundle\Serializer\JsonSerializationVisitor;
  65. use JMS\SerializerBundle\Serializer\Serializer;
  66. use JMS\SerializerBundle\Tests\Fixtures\ObjectWithVersionedVirtualProperties;
  67. abstract class BaseSerializationTest extends \PHPUnit_Framework_TestCase
  68. {
  69. public function testString()
  70. {
  71. $this->assertEquals($this->getContent('string'), $this->serialize('foo'));
  72. if ($this->hasDeserializer()) {
  73. $this->assertEquals('foo', $this->deserialize($this->getContent('string'), 'string'));
  74. }
  75. }
  76. /**
  77. * @dataProvider getBooleans
  78. */
  79. public function testBooleans($strBoolean, $boolean)
  80. {
  81. $this->assertEquals($this->getContent('boolean_'.$strBoolean), $this->serialize($boolean));
  82. if ($this->hasDeserializer()) {
  83. $this->assertSame($boolean, $this->deserialize($this->getContent('boolean_'.$strBoolean), 'boolean'));
  84. }
  85. }
  86. public function getBooleans()
  87. {
  88. return array(array('true', true), array('false', false));
  89. }
  90. /**
  91. * @dataProvider getNumerics
  92. */
  93. public function testNumerics($key, $value)
  94. {
  95. $this->assertEquals($this->getContent($key), $this->serialize($value));
  96. if ($this->hasDeserializer()) {
  97. $this->assertEquals($value, $this->deserialize($this->getContent($key), is_double($value) ? 'double' : 'integer'));
  98. }
  99. }
  100. public function getNumerics()
  101. {
  102. return array(
  103. array('integer', 1),
  104. array('float', 4.533),
  105. array('float_trailing_zero', 1.0),
  106. );
  107. }
  108. public function testSimpleObject()
  109. {
  110. $this->assertEquals($this->getContent('simple_object'), $this->serialize($obj = new SimpleObject('foo', 'bar')));
  111. if ($this->hasDeserializer()) {
  112. $this->assertEquals($obj, $this->deserialize($this->getContent('simple_object'), get_class($obj)));
  113. }
  114. }
  115. public function testArrayStrings()
  116. {
  117. $data = array('foo', 'bar');
  118. $this->assertEquals($this->getContent('array_strings'), $this->serialize($data));
  119. if ($this->hasDeserializer()) {
  120. $this->assertEquals($data, $this->deserialize($this->getContent('array_strings'), 'array<string>'));
  121. }
  122. }
  123. public function testArrayBooleans()
  124. {
  125. $data = array(true, false);
  126. $this->assertEquals($this->getContent('array_booleans'), $this->serialize($data));
  127. if ($this->hasDeserializer()) {
  128. $this->assertEquals($data, $this->deserialize($this->getContent('array_booleans'), 'array<boolean>'));
  129. }
  130. }
  131. public function testArrayIntegers()
  132. {
  133. $data = array(1, 3, 4);
  134. $this->assertEquals($this->getContent('array_integers'), $this->serialize($data));
  135. if ($this->hasDeserializer()) {
  136. $this->assertEquals($data, $this->deserialize($this->getContent('array_integers'), 'array<integer>'));
  137. }
  138. }
  139. public function testArrayFloats()
  140. {
  141. $data = array(1.34, 3.0, 6.42);
  142. $this->assertEquals($this->getContent('array_floats'), $this->serialize($data));
  143. if ($this->hasDeserializer()) {
  144. $this->assertEquals($data, $this->deserialize($this->getContent('array_floats'), 'array<double>'));
  145. }
  146. }
  147. public function testArrayObjects()
  148. {
  149. $data = array(new SimpleObject('foo', 'bar'), new SimpleObject('baz', 'boo'));
  150. $this->assertEquals($this->getContent('array_objects'), $this->serialize($data));
  151. if ($this->hasDeserializer()) {
  152. $this->assertEquals($data, $this->deserialize($this->getContent('array_objects'), 'array<JMS\SerializerBundle\Tests\Fixtures\SimpleObject>'));
  153. }
  154. }
  155. public function testArrayMixed()
  156. {
  157. $this->assertEquals($this->getContent('array_mixed'), $this->serialize(array('foo', 1, true, new SimpleObject('foo', 'bar'), array(1, 3, true))));
  158. }
  159. public function testBlogPost()
  160. {
  161. $post = new BlogPost('This is a nice title.', $author = new Author('Foo Bar'), new \DateTime('2011-07-30 00:00', new \DateTimeZone('UTC')));
  162. $post->addComment($comment = new Comment($author, 'foo'));
  163. $this->assertEquals($this->getContent('blog_post'), $this->serialize($post));
  164. if ($this->hasDeserializer()) {
  165. $deserialized = $this->deserialize($this->getContent('blog_post'), get_class($post));
  166. $this->assertEquals('2011-07-30T00:00:00+0000', $this->getField($deserialized, 'createdAt')->format(\DateTime::ISO8601));
  167. $this->assertAttributeEquals('This is a nice title.', 'title', $deserialized);
  168. $this->assertAttributeSame(false, 'published', $deserialized);
  169. $this->assertAttributeEquals(new ArrayCollection(array($comment)), 'comments', $deserialized);
  170. $this->assertAttributeEquals($author, 'author', $deserialized);
  171. }
  172. }
  173. public function testReadOnly()
  174. {
  175. $author = new AuthorReadOnly(123, 'Ruud Kamphuis');
  176. $this->assertEquals($this->getContent('readonly'), $this->serialize($author));
  177. if ($this->hasDeserializer()) {
  178. $deserialized = $this->deserialize($this->getContent('readonly'), get_class($author));
  179. $this->assertNull($this->getField($deserialized, 'id'));
  180. $this->assertEquals('Ruud Kamphuis', $this->getField($deserialized, 'name'));
  181. }
  182. }
  183. public function testPrice()
  184. {
  185. $price = new Price(3);
  186. $this->assertEquals($this->getContent('price'), $this->serialize($price));
  187. if ($this->hasDeserializer()) {
  188. $deserialized = $this->deserialize($this->getContent('price'), get_class($price));
  189. $this->assertEquals(3, $this->getField($deserialized, 'price'));
  190. }
  191. }
  192. public function testOrder()
  193. {
  194. $order = new Order(new Price(12.34));
  195. $this->assertEquals($this->getContent('order'), $this->serialize($order));
  196. if ($this->hasDeserializer()) {
  197. $this->assertEquals($order, $this->deserialize($this->getContent('order'), get_class($order)));
  198. }
  199. }
  200. public function testCurrencyAwarePrice()
  201. {
  202. $price = new CurrencyAwarePrice(2.34);
  203. $this->assertEquals($this->getContent('currency_aware_price'), $this->serialize($price));
  204. if ($this->hasDeserializer()) {
  205. $this->assertEquals($price, $this->deserialize($this->getContent('currency_aware_price'), get_class($price)));
  206. }
  207. }
  208. public function testOrderWithCurrencyAwarePrice()
  209. {
  210. $order = new CurrencyAwareOrder(new CurrencyAwarePrice(1.23));
  211. $this->assertEquals($this->getContent('order_with_currency_aware_price'), $this->serialize($order));
  212. if ($this->hasDeserializer()) {
  213. $this->assertEquals($order, $this->deserialize($this->getContent('order_with_currency_aware_price'), get_class($order)));
  214. }
  215. }
  216. public function testArticle()
  217. {
  218. $article = new Article();
  219. $article->element = 'custom';
  220. $article->value = 'serialized';
  221. $result = $this->serialize($article);
  222. $this->assertEquals($this->getContent('article'), $result);
  223. if ($this->hasDeserializer()) {
  224. $this->assertEquals($article, $this->deserialize($result, 'JMS\SerializerBundle\Tests\Serializer\Article'));
  225. }
  226. }
  227. public function testInline()
  228. {
  229. $inline = new InlineParent();
  230. $result = $this->serialize($inline);
  231. $this->assertEquals($this->getContent('inline'), $result);
  232. //no deserialization support
  233. /*if ($this->hasDeserializer()) {
  234. $this->assertEquals($inline, $this->deserialize($result, 'JMS\SerializerBundle\Tests\Serializer\InlineParent'));
  235. }*/
  236. }
  237. /**
  238. * @group test
  239. */
  240. public function testLog()
  241. {
  242. $this->assertEquals($this->getContent('log'), $this->serialize($log = new Log()));
  243. if ($this->hasDeserializer()) {
  244. $deserialized = $this->deserialize($this->getContent('log'), get_class($log));
  245. $this->assertEquals($log, $deserialized);
  246. }
  247. }
  248. public function testCircularReference()
  249. {
  250. $object = new CircularReferenceParent();
  251. $this->assertEquals($this->getContent('circular_reference'), $this->serialize($object));
  252. if ($this->hasDeserializer()) {
  253. $deserialized = $this->deserialize($this->getContent('circular_reference'), get_class($object));
  254. $col = $this->getField($deserialized, 'collection');
  255. $this->assertEquals(2, count($col));
  256. $this->assertEquals('child1', $col[0]->getName());
  257. $this->assertEquals('child2', $col[1]->getName());
  258. $this->assertSame($deserialized, $col[0]->getParent());
  259. $this->assertSame($deserialized, $col[1]->getParent());
  260. $col = $this->getField($deserialized, 'anotherCollection');
  261. $this->assertEquals(2, count($col));
  262. $this->assertEquals('child1', $col[0]->getName());
  263. $this->assertEquals('child2', $col[1]->getName());
  264. $this->assertSame($deserialized, $col[0]->getParent());
  265. $this->assertSame($deserialized, $col[1]->getParent());
  266. }
  267. }
  268. public function testLifecycleCallbacks()
  269. {
  270. $object = new ObjectWithLifecycleCallbacks();
  271. $this->assertEquals($this->getContent('lifecycle_callbacks'), $this->serialize($object));
  272. $this->assertAttributeSame(null, 'name', $object);
  273. if ($this->hasDeserializer()) {
  274. $deserialized = $this->deserialize($this->getContent('lifecycle_callbacks'), get_class($object));
  275. $this->assertEquals($object, $deserialized);
  276. }
  277. }
  278. public function testFormErrors()
  279. {
  280. $errors = array(
  281. new FormError('This is the form error'),
  282. new FormError('Another error')
  283. );
  284. $this->assertEquals($this->getContent('form_errors'), $this->serialize($errors));
  285. }
  286. public function testNestedFormErrors()
  287. {
  288. $dispatcher = $this->getMock('Symfony\Component\EventDispatcher\EventDispatcherInterface');
  289. $formConfig = $this->getMock('Symfony\Component\Form\FormConfigInterface');
  290. $formConfig->expects($this->any())
  291. ->method('getEventDispatcher')
  292. ->will($this->returnValue($dispatcher));
  293. $formConfig->expects($this->any())
  294. ->method('getModelTransformers')
  295. ->will($this->returnValue(array()));
  296. $fooConfig = clone $formConfig;
  297. $fooConfig->expects($this->any())
  298. ->method('getName')
  299. ->will($this->returnValue('foo'));
  300. $form = new Form($fooConfig);
  301. $form->addError(new FormError('This is the form error'));
  302. $barConfig = clone $formConfig;
  303. $barConfig->expects($this->any())
  304. ->method('getName')
  305. ->will($this->returnValue('bar'));
  306. $child = new Form($barConfig);
  307. $child->addError(new FormError('Error of the child form'));
  308. $form->add($child);
  309. $this->assertEquals($this->getContent('nested_form_errors'), $this->serialize($form));
  310. }
  311. public function testConstraintViolation()
  312. {
  313. $violation = new ConstraintViolation('Message of violation', array(), null, 'foo', null);
  314. $this->assertEquals($this->getContent('constraint_violation'), $this->serialize($violation));
  315. }
  316. public function testConstraintViolationList()
  317. {
  318. $violations = new ConstraintViolationList();
  319. $violations->add(new ConstraintViolation('Message of violation', array(), null, 'foo', null));
  320. $violations->add(new ConstraintViolation('Message of another violation', array(), null, 'bar', null));
  321. $this->assertEquals($this->getContent('constraint_violation_list'), $this->serialize($violations));
  322. }
  323. public function testDoctrineProxy()
  324. {
  325. if (!class_exists('Doctrine\ORM\Version')) {
  326. $this->markTestSkipped('Doctrine is not available.');
  327. }
  328. $object = new SimpleObjectProxy('foo', 'bar');
  329. $this->assertEquals($this->getContent('orm_proxy'), $this->serialize($object));
  330. }
  331. public function testInitializedDoctrineProxy()
  332. {
  333. if (!class_exists('Doctrine\ORM\Version')) {
  334. $this->markTestSkipped('Doctrine is not available.');
  335. }
  336. $object = new SimpleObjectProxy('foo', 'bar');
  337. $object->__load();
  338. $this->assertEquals($this->getContent('orm_proxy'), $this->serialize($object));
  339. }
  340. public function testCustomAccessor()
  341. {
  342. $post = new IndexedCommentsBlogPost();
  343. $this->assertEquals($this->getContent('custom_accessor'), $this->serialize($post));
  344. }
  345. public function testMixedAccessTypes()
  346. {
  347. $object = new GetSetObject();
  348. $this->assertEquals($this->getContent('mixed_access_types'), $this->serialize($object));
  349. if ($this->hasDeserializer()) {
  350. $object = $this->deserialize($this->getContent('mixed_access_types'), 'JMS\SerializerBundle\Tests\Fixtures\GetSetObject');
  351. $this->assertAttributeEquals(1, 'id', $object);
  352. $this->assertAttributeEquals('Johannes', 'name', $object);
  353. $this->assertAttributeEquals(42, 'readOnlyProperty', $object);
  354. }
  355. }
  356. public function testAccessorOrder()
  357. {
  358. $this->assertEquals($this->getContent('accessor_order_child'), $this->serialize(new AccessorOrderChild()));
  359. $this->assertEquals($this->getContent('accessor_order_parent'), $this->serialize(new AccessorOrderParent()));
  360. }
  361. public function testGroups()
  362. {
  363. $serializer = $this->getSerializer();
  364. $groupsObject = new GroupsObject();
  365. $this->assertEquals($this->getContent('groups_all'), $serializer->serialize($groupsObject, $this->getFormat()));
  366. $serializer->setGroups(array("foo"));
  367. $this->assertEquals($this->getContent('groups_foo'), $serializer->serialize($groupsObject, $this->getFormat()));
  368. $serializer->setGroups(array("foo", "bar"));
  369. $this->assertEquals($this->getContent('groups_foobar'), $serializer->serialize($groupsObject, $this->getFormat()));
  370. $serializer->setGroups(null);
  371. $this->assertEquals($this->getContent('groups_all'), $serializer->serialize($groupsObject, $this->getFormat()));
  372. $serializer->setGroups(array());
  373. $this->assertEquals($this->getContent('groups_all'), $serializer->serialize($groupsObject, $this->getFormat()));
  374. }
  375. public function testVirtualProperty()
  376. {
  377. $this->assertEquals($this->getContent('virtual_properties'), $this->serialize(new ObjectWithVirtualProperties()));
  378. }
  379. public function testVirtualVersions()
  380. {
  381. $serializer = $this->getSerializer();
  382. $serializer->setVersion(2);
  383. $this->assertEquals($this->getContent('virtual_properties_low'), $serializer->serialize(new ObjectWithVersionedVirtualProperties(), $this->getFormat()));
  384. $serializer->setVersion(7);
  385. $this->assertEquals($this->getContent('virtual_properties_all'), $serializer->serialize(new ObjectWithVersionedVirtualProperties(), $this->getFormat()));
  386. $serializer->setVersion(9);
  387. $this->assertEquals($this->getContent('virtual_properties_high'), $serializer->serialize(new ObjectWithVersionedVirtualProperties(), $this->getFormat()));
  388. }
  389. abstract protected function getContent($key);
  390. abstract protected function getFormat();
  391. protected function hasDeserializer()
  392. {
  393. return true;
  394. }
  395. protected function serialize($data)
  396. {
  397. return $this->getSerializer()->serialize($data, $this->getFormat());
  398. }
  399. protected function deserialize($content, $type)
  400. {
  401. return $this->getSerializer()->deserialize($content, $type, $this->getFormat());
  402. }
  403. protected function getSerializer()
  404. {
  405. $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
  406. $namingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy());
  407. $objectConstructor = new UnserializeObjectConstructor();
  408. $customSerializationHandlers = $this->getSerializationHandlers();
  409. $customDeserializationHandlers = $this->getDeserializationHandlers();
  410. $serializationVisitors = array(
  411. 'json' => new JsonSerializationVisitor($namingStrategy, $customSerializationHandlers),
  412. 'xml' => new XmlSerializationVisitor($namingStrategy, $customSerializationHandlers),
  413. 'yml' => new YamlSerializationVisitor($namingStrategy, $customSerializationHandlers),
  414. );
  415. $deserializationVisitors = array(
  416. 'json' => new JsonDeserializationVisitor($namingStrategy, $customDeserializationHandlers, $objectConstructor),
  417. 'xml' => new XmlDeserializationVisitor($namingStrategy, $customDeserializationHandlers, $objectConstructor),
  418. );
  419. return new Serializer($factory, $serializationVisitors, $deserializationVisitors);
  420. }
  421. protected function getSerializationHandlers()
  422. {
  423. $translatorMock = $this->getMock('Symfony\\Component\\Translation\\TranslatorInterface');
  424. $translatorMock
  425. ->expects($this->any())
  426. ->method('trans')
  427. ->will($this->returnArgument(0));
  428. $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
  429. $objectConstructor = new UnserializeObjectConstructor();
  430. $handlers = array(
  431. new ObjectBasedCustomHandler($objectConstructor, $factory),
  432. new DateTimeHandler(),
  433. new FormErrorHandler($translatorMock),
  434. new ConstraintViolationHandler(),
  435. new DoctrineProxyHandler(),
  436. );
  437. return $handlers;
  438. }
  439. protected function getDeserializationHandlers()
  440. {
  441. $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
  442. $objectConstructor = new UnserializeObjectConstructor();
  443. $handlers = array(
  444. new ObjectBasedCustomHandler($objectConstructor, $factory),
  445. new DateTimeHandler(),
  446. new ArrayCollectionHandler(),
  447. new AuthorListDeserializationHandler(),
  448. );
  449. return $handlers;
  450. }
  451. private function getField($obj, $name)
  452. {
  453. $ref = new \ReflectionProperty($obj, $name);
  454. $ref->setAccessible(true);
  455. return $ref->getValue($obj);
  456. }
  457. private function setField($obj, $name, $value)
  458. {
  459. $ref = new \ReflectionProperty($obj, $name);
  460. $ref->setAccessible(true);
  461. $ref->setValue($obj, $value);
  462. }
  463. }
  464. class AuthorListDeserializationHandler implements DeserializationHandlerInterface
  465. {
  466. public function deserialize(VisitorInterface $visitor, $data, $type, &$visited)
  467. {
  468. if ('AuthorList' !== $type) {
  469. return;
  470. }
  471. $visited = true;
  472. $elements = $visitor->getNavigator()->accept($data, 'array<integer, JMS\SerializerBundle\Tests\Fixtures\Author>', $visitor);
  473. $list = new AuthorList();
  474. foreach ($elements as $author) {
  475. $list->add($author);
  476. }
  477. return $list;
  478. }
  479. }
  480. class Article implements SerializationHandlerInterface, DeserializationHandlerInterface
  481. {
  482. public $element;
  483. public $value;
  484. public function serialize(VisitorInterface $visitor, $data, $type, &$visited)
  485. {
  486. if (!$data instanceof Article) {
  487. return;
  488. }
  489. if ($visitor instanceof XmlSerializationVisitor) {
  490. $visited = true;
  491. if (null === $visitor->document) {
  492. $visitor->document = $visitor->createDocument(null, null, false);
  493. }
  494. $visitor->document->appendChild($visitor->document->createElement($this->element, $this->value));
  495. } elseif ($visitor instanceof JsonSerializationVisitor) {
  496. $visited = true;
  497. $visitor->setRoot(array($this->element => $this->value));
  498. } elseif ($visitor instanceof YamlSerializationVisitor) {
  499. $visited = true;
  500. $visitor->writer->writeln(Inline::dump($this->element).': '.Inline::dump($this->value));
  501. }
  502. }
  503. public function deserialize(VisitorInterface $visitor, $data, $type, &$visited)
  504. {
  505. if ('JMS\SerializerBundle\Tests\Serializer\Article' !== $type) {
  506. return;
  507. }
  508. if ($visitor instanceof XmlDeserializationVisitor) {
  509. $visited = true;
  510. $this->element = $data->getName();
  511. $this->value = (string)$data;
  512. } elseif ($visitor instanceof JsonDeserializationVisitor) {
  513. $visited = true;
  514. $this->element = key($data);
  515. $this->value = reset($data);
  516. }
  517. return $this;
  518. }
  519. }