BaseSerializationTest.php 23 KB

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