BaseSerializationTest.php 18 KB

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