BaseSerializationTest.php 18 KB

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