JsonSerializationTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. <?php
  2. /*
  3. * Copyright 2013 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\Context;
  19. use JMS\Serializer\Exception\RuntimeException;
  20. use JMS\Serializer\EventDispatcher\Event;
  21. use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
  22. use JMS\Serializer\GraphNavigator;
  23. use JMS\Serializer\VisitorInterface;
  24. use JMS\Serializer\Tests\Fixtures\Author;
  25. use JMS\Serializer\Tests\Fixtures\AuthorList;
  26. class JsonSerializationTest extends BaseSerializationTest
  27. {
  28. protected function getContent($key)
  29. {
  30. static $outputs = array();
  31. if (!$outputs) {
  32. $outputs['readonly'] = '{"id":123,"full_name":"Ruud Kamphuis"}';
  33. $outputs['string'] = '"foo"';
  34. $outputs['boolean_true'] = 'true';
  35. $outputs['boolean_false'] = 'false';
  36. $outputs['integer'] = '1';
  37. $outputs['float'] = '4.533';
  38. $outputs['float_trailing_zero'] = '1';
  39. $outputs['simple_object'] = '{"foo":"foo","moo":"bar","camel_case":"boo"}';
  40. $outputs['circular_reference'] = '{"collection":[{"name":"child1"},{"name":"child2"}],"another_collection":[{"name":"child1"},{"name":"child2"}]}';
  41. $outputs['array_strings'] = '["foo","bar"]';
  42. $outputs['array_booleans'] = '[true,false]';
  43. $outputs['array_integers'] = '[1,3,4]';
  44. $outputs['array_floats'] = '[1.34,3,6.42]';
  45. $outputs['array_objects'] = '[{"foo":"foo","moo":"bar","camel_case":"boo"},{"foo":"baz","moo":"boo","camel_case":"boo"}]';
  46. $outputs['array_mixed'] = '["foo",1,true,{"foo":"foo","moo":"bar","camel_case":"boo"},[1,3,true]]';
  47. $outputs['array_datetimes_object'] = '{"array_with_default_date_time":["2047-01-01T12:47:47+0000","2013-12-05T00:00:00+0000"],"array_with_formatted_date_time":["01.01.2047 12:47:47","05.12.2013 00:00:00"]}';
  48. $outputs['array_named_datetimes_object'] = '{"named_array_with_formatted_date":{"testdate1":"01.01.2047 12:47:47","testdate2":"05.12.2013 00:00:00"}}';
  49. $outputs['blog_post'] = '{"id":"what_a_nice_id","title":"This is a nice title.","created_at":"2011-07-30T00:00:00+0000","is_published":false,"etag":"1edf9bf60a32d89afbb85b2be849e3ceed5f5b10","comments":[{"author":{"full_name":"Foo Bar"},"text":"foo"}],"comments2":[{"author":{"full_name":"Foo Bar"},"text":"foo"}],"metadata":{"foo":"bar"},"author":{"full_name":"Foo Bar"},"publisher":{"pub_name":"Bar Foo"}}';
  50. $outputs['blog_post_unauthored'] = '{"id":"what_a_nice_id","title":"This is a nice title.","created_at":"2011-07-30T00:00:00+0000","is_published":false,"etag":"1edf9bf60a32d89afbb85b2be849e3ceed5f5b10","comments":[],"comments2":[],"metadata":{"foo":"bar"},"author":null,"publisher":null}';
  51. $outputs['price'] = '{"price":3}';
  52. $outputs['currency_aware_price'] = '{"currency":"EUR","amount":2.34}';
  53. $outputs['order'] = '{"cost":{"price":12.34}}';
  54. $outputs['order_with_currency_aware_price'] = '{"cost":{"currency":"EUR","amount":1.23}}';
  55. $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"}]}';
  56. $outputs['lifecycle_callbacks'] = '{"name":"Foo Bar"}';
  57. $outputs['form_errors'] = '["This is the form error","Another error"]';
  58. $outputs['nested_form_errors'] = '{"errors":["This is the form error"],"children":{"bar":{"errors":["Error of the child form"]}}}';
  59. $outputs['constraint_violation'] = '{"property_path":"foo","message":"Message of violation"}';
  60. $outputs['constraint_violation_list'] = '[{"property_path":"foo","message":"Message of violation"},{"property_path":"bar","message":"Message of another violation"}]';
  61. $outputs['article'] = '{"custom":"serialized"}';
  62. $outputs['orm_proxy'] = '{"foo":"foo","moo":"bar","camel_case":"proxy-boo"}';
  63. $outputs['custom_accessor'] = '{"comments":{"Foo":{"comments":[{"author":{"full_name":"Foo"},"text":"foo"},{"author":{"full_name":"Foo"},"text":"bar"}],"count":2}}}';
  64. $outputs['mixed_access_types'] = '{"id":1,"name":"Johannes","read_only_property":42}';
  65. $outputs['accessor_order_child'] = '{"c":"c","d":"d","a":"a","b":"b"}';
  66. $outputs['accessor_order_parent'] = '{"a":"a","b":"b"}';
  67. $outputs['accessor_order_methods'] = '{"foo":"c","b":"b","a":"a"}';
  68. $outputs['inline'] = '{"c":"c","a":"a","b":"b","d":"d"}';
  69. $outputs['inline_child_empty'] = '{"c":"c","d":"d"}';
  70. $outputs['groups_all'] = '{"foo":"foo","foobar":"foobar","bar":"bar","none":"none"}';
  71. $outputs['groups_foo'] = '{"foo":"foo","foobar":"foobar"}';
  72. $outputs['groups_foobar'] = '{"foo":"foo","foobar":"foobar","bar":"bar"}';
  73. $outputs['groups_default'] = '{"bar":"bar","none":"none"}';
  74. $outputs['virtual_properties'] = '{"exist_field":"value","test":"other-name","virtual_value":"value","typed_virtual_property":1}';
  75. $outputs['virtual_properties_low'] = '{"low":1}';
  76. $outputs['virtual_properties_high'] = '{"high":8}';
  77. $outputs['virtual_properties_all'] = '{"low":1,"high":8}';
  78. $outputs['nullable'] = '{"foo":"bar","baz":null}';
  79. $outputs['null'] = 'null';
  80. $outputs['simple_object_nullable'] = '{"foo":"foo","moo":"bar","camel_case":"boo","null_property":null}';
  81. $outputs['input'] = '{"attributes":{"type":"text","name":"firstname","value":"Adrien"}}';
  82. $outputs['hash_empty'] = '{"hash":{}}';
  83. $outputs['object_when_null'] = '{"text":"foo"}';
  84. $outputs['object_when_null_and_serialized'] = '{"author":null,"text":"foo"}';
  85. $outputs['date_time'] = '"2011-08-30T00:00:00+0000"';
  86. $outputs['date_interval'] = '"PT45M"';
  87. $outputs['car'] = '{"km":5,"type":"car"}';
  88. $outputs['car_without_type'] = '{"km":5}';
  89. $outputs['garage'] = '{"vehicles":[{"km":3,"type":"car"},{"km":1,"type":"moped"}]}';
  90. $outputs['tree'] = '{"tree":{"children":[{"children":[{"children":[],"foo":"bar"}],"foo":"bar"}],"foo":"bar"}}';
  91. }
  92. if (!isset($outputs[$key])) {
  93. throw new RuntimeException(sprintf('The key "%s" is not supported.', $key));
  94. }
  95. return $outputs[$key];
  96. }
  97. public function testAddLinksToOutput()
  98. {
  99. $this->dispatcher->addSubscriber(new LinkAddingSubscriber());
  100. $this->handlerRegistry->registerHandler(GraphNavigator::DIRECTION_SERIALIZATION, 'JMS\Serializer\Tests\Fixtures\AuthorList', 'json',
  101. function(VisitorInterface $visitor, AuthorList $data, array $type, Context $context) {
  102. return $visitor->visitArray(iterator_to_array($data), $type, $context);
  103. }
  104. );
  105. $list = new AuthorList();
  106. $list->add(new Author('foo'));
  107. $list->add(new Author('bar'));
  108. $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));
  109. }
  110. public function getPrimitiveTypes()
  111. {
  112. return array(
  113. array(
  114. 'type' => 'boolean',
  115. 'data' => true,
  116. ),
  117. array(
  118. 'type' => 'boolean',
  119. 'data' => 1,
  120. ),
  121. array(
  122. 'type' => 'integer',
  123. 'data' => 123,
  124. ),
  125. array(
  126. 'type' => 'integer',
  127. 'data' => "123",
  128. ),
  129. array(
  130. 'type' => 'string',
  131. 'data' => "hello",
  132. ),
  133. array(
  134. 'type' => 'string',
  135. 'data' => 123,
  136. ),
  137. array(
  138. 'type' => 'double',
  139. 'data' => 0.1234,
  140. ),
  141. array(
  142. 'type' => 'double',
  143. 'data' => "0.1234",
  144. ),
  145. );
  146. }
  147. /**
  148. * @dataProvider getPrimitiveTypes
  149. */
  150. public function testPrimitiveTypes($primitiveType, $data)
  151. {
  152. $visitor = $this->serializationVisitors->get('json')->get();
  153. $functionToCall = 'visit' . ucfirst($primitiveType);
  154. $result = $visitor->$functionToCall($data, array(), $this->getMock('JMS\Serializer\Context'));
  155. if ($primitiveType == 'double') {
  156. $primitiveType = 'float';
  157. }
  158. $this->assertInternalType($primitiveType, $result);
  159. }
  160. /**
  161. * @group empty-object
  162. */
  163. public function testSerializeEmptyObject()
  164. {
  165. $this->assertEquals('{}', $this->serialize(new Author(null)));
  166. }
  167. /**
  168. * @group encoding
  169. * @expectedException RuntimeException
  170. * @expectedExceptionMessage Your data could not be encoded because it contains invalid UTF8 characters.
  171. */
  172. public function testSerializeWithNonUtf8EncodingWhenDisplayErrorsOff()
  173. {
  174. ini_set('display_errors', 1);
  175. $this->serialize(array('foo' => 'bar', 'bar' => pack("H*" ,'c32e')));
  176. }
  177. /**
  178. * @group encoding
  179. * @expectedException RuntimeException
  180. * @expectedExceptionMessage Your data could not be encoded because it contains invalid UTF8 characters.
  181. */
  182. public function testSerializeWithNonUtf8EncodingWhenDisplayErrorsOn()
  183. {
  184. ini_set('display_errors', 0);
  185. $this->serialize(array('foo' => 'bar', 'bar' => pack("H*" ,'c32e')));
  186. }
  187. public function testSerializeArrayWithEmptyObject()
  188. {
  189. $this->assertEquals('{"0":{}}', $this->serialize(array(new \stdClass())));
  190. }
  191. protected function getFormat()
  192. {
  193. return 'json';
  194. }
  195. }
  196. class LinkAddingSubscriber implements EventSubscriberInterface
  197. {
  198. public function onPostSerialize(Event $event)
  199. {
  200. $author = $event->getObject();
  201. $event->getVisitor()->addData('_links', array(
  202. 'details' => 'http://foo.bar/details/'.$author->getName(),
  203. 'comments' => 'http://foo.bar/details/'.$author->getName().'/comments',
  204. ));
  205. }
  206. public static function getSubscribedEvents()
  207. {
  208. return array(
  209. array('event' => 'serializer.post_serialize', 'method' => 'onPostSerialize', 'format' => 'json', 'class' => 'JMS\Serializer\Tests\Fixtures\Author'),
  210. );
  211. }
  212. }