BaseSerializationTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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\DoctrineProxyHandler;
  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 testDoctrineProxy()
  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. public function testInitializedDoctrineProxy()
  288. {
  289. if (!class_exists('Doctrine\ORM\Version')) {
  290. $this->markTestSkipped('Doctrine is not available.');
  291. }
  292. $object = new SimpleObjectProxy('foo', 'bar');
  293. $object->__load();
  294. $this->assertEquals($this->getContent('orm_proxy'), $this->serialize($object));
  295. }
  296. abstract protected function getContent($key);
  297. abstract protected function getFormat();
  298. protected function hasDeserializer()
  299. {
  300. return true;
  301. }
  302. protected function serialize($data)
  303. {
  304. return $this->getSerializer()->serialize($data, $this->getFormat());
  305. }
  306. protected function deserialize($content, $type)
  307. {
  308. return $this->getSerializer()->deserialize($content, $type, $this->getFormat());
  309. }
  310. protected function getSerializer()
  311. {
  312. $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
  313. $namingStrategy = new SerializedNameAnnotationStrategy(new CamelCaseNamingStrategy());
  314. $objectConstructor = new UnserializeObjectConstructor();
  315. $customSerializationHandlers = $this->getSerializationHandlers();
  316. $customDeserializationHandlers = $this->getDeserializationHandlers();
  317. $serializationVisitors = array(
  318. 'json' => new JsonSerializationVisitor($namingStrategy, $customSerializationHandlers),
  319. 'xml' => new XmlSerializationVisitor($namingStrategy, $customSerializationHandlers),
  320. 'yml' => new YamlSerializationVisitor($namingStrategy, $customSerializationHandlers),
  321. );
  322. $deserializationVisitors = array(
  323. 'json' => new JsonDeserializationVisitor($namingStrategy, $customDeserializationHandlers, $objectConstructor),
  324. 'xml' => new XmlDeserializationVisitor($namingStrategy, $customDeserializationHandlers, $objectConstructor),
  325. );
  326. return new Serializer($factory, $serializationVisitors, $deserializationVisitors);
  327. }
  328. protected function getSerializationHandlers()
  329. {
  330. $translatorMock = $this->getMock('Symfony\\Component\\Translation\\TranslatorInterface');
  331. $translatorMock
  332. ->expects($this->any())
  333. ->method('trans')
  334. ->will($this->returnArgument(0));
  335. $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
  336. $objectConstructor = new UnserializeObjectConstructor();
  337. $handlers = array(
  338. new ObjectBasedCustomHandler($objectConstructor, $factory),
  339. new DateTimeHandler(),
  340. new FormErrorHandler($translatorMock),
  341. new ConstraintViolationHandler(),
  342. new DoctrineProxyHandler(),
  343. );
  344. return $handlers;
  345. }
  346. protected function getDeserializationHandlers()
  347. {
  348. $factory = new MetadataFactory(new AnnotationDriver(new AnnotationReader()));
  349. $objectConstructor = new UnserializeObjectConstructor();
  350. $handlers = array(
  351. new ObjectBasedCustomHandler($objectConstructor, $factory),
  352. new DateTimeHandler(),
  353. new ArrayCollectionHandler(),
  354. new AuthorListDeserializationHandler(),
  355. );
  356. return $handlers;
  357. }
  358. private function getField($obj, $name)
  359. {
  360. $ref = new \ReflectionProperty($obj, $name);
  361. $ref->setAccessible(true);
  362. return $ref->getValue($obj);
  363. }
  364. private function setField($obj, $name, $value)
  365. {
  366. $ref = new \ReflectionProperty($obj, $name);
  367. $ref->setAccessible(true);
  368. $ref->setValue($obj, $value);
  369. }
  370. }
  371. class AuthorListDeserializationHandler implements DeserializationHandlerInterface
  372. {
  373. public function deserialize(VisitorInterface $visitor, $data, $type, &$visited)
  374. {
  375. if ('AuthorList' !== $type) {
  376. return;
  377. }
  378. $visited = true;
  379. $elements = $visitor->getNavigator()->accept($data, 'array<integer, JMS\SerializerBundle\Tests\Fixtures\Author>', $visitor);
  380. $list = new AuthorList();
  381. foreach ($elements as $author) {
  382. $list->add($author);
  383. }
  384. return $list;
  385. }
  386. }
  387. class Article implements SerializationHandlerInterface, DeserializationHandlerInterface
  388. {
  389. public $element;
  390. public $value;
  391. public function serialize(VisitorInterface $visitor, $data, $type, &$visited)
  392. {
  393. if (!$data instanceof Article) {
  394. return;
  395. }
  396. if ($visitor instanceof XmlSerializationVisitor) {
  397. $visited = true;
  398. if (null === $visitor->document) {
  399. $visitor->document = $visitor->createDocument(null, null, false);
  400. }
  401. $visitor->document->appendChild($visitor->document->createElement($this->element, $this->value));
  402. } elseif ($visitor instanceof JsonSerializationVisitor) {
  403. $visited = true;
  404. $visitor->setRoot(array($this->element => $this->value));
  405. } elseif ($visitor instanceof YamlSerializationVisitor) {
  406. $visited = true;
  407. $visitor->writer->writeln(Inline::dump($this->element).': '.Inline::dump($this->value));
  408. }
  409. }
  410. public function deserialize(VisitorInterface $visitor, $data, $type, &$visited)
  411. {
  412. if ('JMS\SerializerBundle\Tests\Serializer\Article' !== $type) {
  413. return;
  414. }
  415. if ($visitor instanceof XmlDeserializationVisitor) {
  416. $visited = true;
  417. $this->element = $data->getName();
  418. $this->value = (string)$data;
  419. } elseif ($visitor instanceof JsonDeserializationVisitor) {
  420. $visited = true;
  421. $this->element = key($data);
  422. $this->value = reset($data);
  423. }
  424. return $this;
  425. }
  426. }