BaseSerializationTest.php 13 KB

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