BaseSerializationTest.php 20 KB

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