BaseSerializationTest.php 11 KB

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