BaseSerializationTest.php 25 KB

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