BaseSerializationTest.php 14 KB

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