BaseSerializationTest.php 24 KB

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