BaseSerializationTest.php 17 KB

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