JsonSerializationTest.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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\Serializer\Tests\Serializer;
  18. use JMS\Serializer\Exception\RuntimeException;
  19. use JMS\Serializer\EventDispatcher\Event;
  20. use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
  21. use JMS\Serializer\GraphNavigator;
  22. use JMS\Serializer\VisitorInterface;
  23. use JMS\Serializer\Tests\Fixtures\Author;
  24. use JMS\Serializer\Tests\Fixtures\AuthorList;
  25. class JsonSerializationTest extends BaseSerializationTest
  26. {
  27. protected function getContent($key)
  28. {
  29. static $outputs = array();
  30. if (!$outputs) {
  31. $outputs['readonly'] = '{"id":123,"full_name":"Ruud Kamphuis"}';
  32. $outputs['string'] = '"foo"';
  33. $outputs['boolean_true'] = 'true';
  34. $outputs['boolean_false'] = 'false';
  35. $outputs['integer'] = '1';
  36. $outputs['float'] = '4.533';
  37. $outputs['float_trailing_zero'] = '1';
  38. $outputs['simple_object'] = '{"foo":"foo","moo":"bar","camel_case":"boo"}';
  39. $outputs['circular_reference'] = '{"collection":[{"name":"child1"},{"name":"child2"}],"another_collection":[{"name":"child1"},{"name":"child2"}]}';
  40. $outputs['array_strings'] = '["foo","bar"]';
  41. $outputs['array_booleans'] = '[true,false]';
  42. $outputs['array_integers'] = '[1,3,4]';
  43. $outputs['array_floats'] = '[1.34,3,6.42]';
  44. $outputs['array_objects'] = '[{"foo":"foo","moo":"bar","camel_case":"boo"},{"foo":"baz","moo":"boo","camel_case":"boo"}]';
  45. $outputs['array_mixed'] = '["foo",1,true,{"foo":"foo","moo":"bar","camel_case":"boo"},[1,3,true]]';
  46. $outputs['blog_post'] = '{"title":"This is a nice title.","created_at":"2011-07-30T00:00:00+0000","is_published":false,"comments":[{"author":{"full_name":"Foo Bar"},"text":"foo"}],"author":{"full_name":"Foo Bar"}}';
  47. $outputs['blog_post_unauthored'] = '{"title":"This is a nice title.","created_at":"2011-07-30T00:00:00+0000","is_published":false,"comments":[],"author":null}';
  48. $outputs['price'] = '{"price":3}';
  49. $outputs['currency_aware_price'] = '{"currency":"EUR","amount":2.34}';
  50. $outputs['order'] = '{"cost":{"price":12.34}}';
  51. $outputs['order_with_currency_aware_price'] = '{"cost":{"currency":"EUR","amount":1.23}}';
  52. $outputs['log'] = '{"author_list":[{"full_name":"Johannes Schmitt"},{"full_name":"John Doe"}],"comments":[{"author":{"full_name":"Foo Bar"},"text":"foo"},{"author":{"full_name":"Foo Bar"},"text":"bar"},{"author":{"full_name":"Foo Bar"},"text":"baz"}]}';
  53. $outputs['lifecycle_callbacks'] = '{"name":"Foo Bar"}';
  54. $outputs['form_errors'] = '["This is the form error","Another error"]';
  55. $outputs['nested_form_errors'] = '{"errors":["This is the form error"],"children":{"bar":{"errors":["Error of the child form"]}}}';
  56. $outputs['constraint_violation'] = '{"property_path":"foo","message":"Message of violation"}';
  57. $outputs['constraint_violation_list'] = '[{"property_path":"foo","message":"Message of violation"},{"property_path":"bar","message":"Message of another violation"}]';
  58. $outputs['article'] = '{"custom":"serialized"}';
  59. $outputs['orm_proxy'] = '{"foo":"foo","moo":"bar","camel_case":"proxy-boo"}';
  60. $outputs['custom_accessor'] = '{"comments":{"Foo":{"comments":[{"author":{"full_name":"Foo"},"text":"foo"},{"author":{"full_name":"Foo"},"text":"bar"}],"count":2}}}';
  61. $outputs['mixed_access_types'] = '{"id":1,"name":"Johannes","read_only_property":42}';
  62. $outputs['accessor_order_child'] = '{"c":"c","d":"d","a":"a","b":"b"}';
  63. $outputs['accessor_order_parent'] = '{"a":"a","b":"b"}';
  64. $outputs['inline'] = '{"c":"c","a":"a","b":"b","d":"d"}';
  65. $outputs['groups_all'] = '{"foo":"foo","foobar":"foobar","bar":"bar","none":"none"}';
  66. $outputs['groups_foo'] = '{"foo":"foo","foobar":"foobar"}';
  67. $outputs['groups_foobar'] = '{"foo":"foo","foobar":"foobar","bar":"bar"}';
  68. $outputs['groups_default'] = '{"bar":"bar","none":"none"}';
  69. $outputs['virtual_properties'] = '{"exist_field":"value","virtual_value":"value","test":"other-name"}';
  70. $outputs['virtual_properties_low'] = '{"low":1}';
  71. $outputs['virtual_properties_high'] = '{"high":8}';
  72. $outputs['virtual_properties_all'] = '{"low":1,"high":8}';
  73. $outputs['nullable'] = '{"foo":"bar","baz":null}';
  74. $outputs['null'] = 'null';
  75. $outputs['simple_object_nullable'] = '{"foo":"foo","moo":"bar","camel_case":"boo","null_property":null}';
  76. $outputs['input'] = '{"attributes":{"type":"text","name":"firstname","value":"Adrien"}}';
  77. $outputs['hash_empty'] = '{"hash":{}}';
  78. $outputs['object_when_null'] = '{"text":"foo"}';
  79. $outputs['object_when_null_and_serialized'] = '{"author":null,"text":"foo"}';
  80. $outputs['date_time'] = '"2011-08-30T00:00:00+0000"';
  81. $outputs['date_interval'] = '"PT45M"';
  82. }
  83. if (!isset($outputs[$key])) {
  84. throw new RuntimeException(sprintf('The key "%s" is not supported.', $key));
  85. }
  86. return $outputs[$key];
  87. }
  88. public function testAddLinksToOutput()
  89. {
  90. $this->dispatcher->addSubscriber(new LinkAddingSubscriber());
  91. $this->handlerRegistry->registerHandler(GraphNavigator::DIRECTION_SERIALIZATION, 'JMS\Serializer\Tests\Fixtures\AuthorList', 'json',
  92. function(VisitorInterface $visitor, AuthorList $data, array $type) {
  93. return $visitor->visitArray(iterator_to_array($data), $type);
  94. }
  95. );
  96. $list = new AuthorList();
  97. $list->add(new Author('foo'));
  98. $list->add(new Author('bar'));
  99. $this->assertEquals('[{"full_name":"foo","_links":{"details":"http:\/\/foo.bar\/details\/foo","comments":"http:\/\/foo.bar\/details\/foo\/comments"}},{"full_name":"bar","_links":{"details":"http:\/\/foo.bar\/details\/bar","comments":"http:\/\/foo.bar\/details\/bar\/comments"}}]', $this->serialize($list));
  100. }
  101. public function getPrimitiveTypes()
  102. {
  103. return array(
  104. array(
  105. 'type' => 'boolean',
  106. 'data' => true,
  107. ),
  108. array(
  109. 'type' => 'boolean',
  110. 'data' => 1,
  111. ),
  112. array(
  113. 'type' => 'integer',
  114. 'data' => 123,
  115. ),
  116. array(
  117. 'type' => 'integer',
  118. 'data' => "123",
  119. ),
  120. array(
  121. 'type' => 'string',
  122. 'data' => "hello",
  123. ),
  124. array(
  125. 'type' => 'string',
  126. 'data' => 123,
  127. ),
  128. array(
  129. 'type' => 'double',
  130. 'data' => 0.1234,
  131. ),
  132. array(
  133. 'type' => 'double',
  134. 'data' => "0.1234",
  135. ),
  136. );
  137. }
  138. /**
  139. * @dataProvider getPrimitiveTypes
  140. */
  141. public function testPrimitiveTypes($primitiveType, $data)
  142. {
  143. $visitor = $this->serializationVisitors->get('json')->get();
  144. $functionToCall = 'visit' . ucfirst($primitiveType);
  145. $result = $visitor->$functionToCall($data, array());
  146. if ($primitiveType == 'double') {
  147. $primitiveType = 'float';
  148. }
  149. $this->assertInternalType($primitiveType, $result);
  150. }
  151. protected function getFormat()
  152. {
  153. return 'json';
  154. }
  155. }
  156. class LinkAddingSubscriber implements EventSubscriberInterface
  157. {
  158. public function onPostSerialize(Event $event)
  159. {
  160. $author = $event->getObject();
  161. $event->getVisitor()->addData('_links', array(
  162. 'details' => 'http://foo.bar/details/'.$author->getName(),
  163. 'comments' => 'http://foo.bar/details/'.$author->getName().'/comments',
  164. ));
  165. }
  166. public static function getSubscribedEvents()
  167. {
  168. return array(
  169. array('event' => 'serializer.post_serialize', 'method' => 'onPostSerialize', 'format' => 'json', 'class' => 'JMS\Serializer\Tests\Fixtures\Author'),
  170. );
  171. }
  172. }