JSON Response

Testing Is Documentation

tests/Http/JsonResponseTest.phpJSON Response - 图1

QueryPHP 针对 API 开发可以直接返回一个 \Leevel\Http\JsonResponse 响应对象。

Uses

  1. <?php
  2. use JsonSerializable;
  3. use Leevel\Http\JsonResponse;
  4. use Leevel\Support\IArray;
  5. use Leevel\Support\IJson;

getEncodingOptions 获取 JSON 编码参数

  1. public function testGetEncodingOptions(): void
  2. {
  3. $response = new JsonResponse();
  4. $this->assertSame(JSON_UNESCAPED_UNICODE, $response->getEncodingOptions());
  5. }

setData 设置 JSON 数据支持 JSON 编码参数

  1. public function testSetDataWithEncodingOptions(): void
  2. {
  3. $response = new JsonResponse();
  4. $response->setData(['成都', 'QueryPHP']);
  5. $this->assertSame('["成都","QueryPHP"]', $response->getContent());
  6. $response->setEncodingOptions(0);
  7. $response->setData(['成都', 'QueryPHP']);
  8. $this->assertSame('["\u6210\u90fd","QueryPHP"]', $response->getContent());
  9. $response->setEncodingOptions(JSON_FORCE_OBJECT);
  10. $response->setData(['成都', 'QueryPHP']);
  11. $this->assertSame('{"0":"\u6210\u90fd","1":"QueryPHP"}', $response->getContent());
  12. }

支持 JSON 的对象

测试实现了 \Leevel\Support\IArray 的对象

  1. namespace Tests\Http;
  2. class JsonResponseMyArray implements IArray
  3. {
  4. public function toArray(): array
  5. {
  6. return ['hello' => 'IArray'];
  7. }
  8. }

测试实现了 \Leevel\Support\IJson 的对象

  1. namespace Tests\Http;
  2. class JsonResponseMyJson implements IJson
  3. {
  4. public function toJson(?int $option = null): string
  5. {
  6. if (null === $option) {
  7. $option = JSON_UNESCAPED_UNICODE;
  8. }
  9. return json_encode(['hello' => 'IJson'], $option);
  10. }
  11. }

测试实现了 \JsonSerializable 的对象

  1. namespace Tests\Http;
  2. class JsonResponseMyJsonSerializable implements JsonSerializable
  3. {
  4. public function jsonSerialize()
  5. {
  6. return ['hello' => 'JsonSerializable'];
  7. }
  8. }
  1. public function testSetEncodingOptions(): void
  2. {
  3. $response = new JsonResponse();
  4. $response->setData(['foo' => 'bar']);
  5. $this->assertSame('{"foo":"bar"}', $response->getContent());
  6. $response->setData(new JsonResponseMyArray());
  7. $this->assertSame('{"hello":"IArray"}', $response->getContent());
  8. $response->setData(new JsonResponseMyJson());
  9. $this->assertSame('{"hello":"IJson"}', $response->getContent());
  10. $response->setData(new JsonResponseMyJsonSerializable());
  11. $this->assertSame('{"hello":"JsonSerializable"}', $response->getContent());
  12. }