BaseSerializationTest.php 12 KB

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