BaseSerializationTest.php 24 KB

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