BaseSerializationTest.php 15 KB

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