BaseSerializationTest.php 28 KB

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