BaseSerializationTest.php 24 KB

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