BaseSerializationTest.php 20 KB

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