germania-kg/response-decoder

API响应解码器的接口和特性

1.1.1 2022-03-30 09:52 UTC

This package is auto-updated.

Last update: 2024-08-29 05:33:55 UTC


README

Germania KG · ResponseDecoder

安装

$ composer require germania-kg/response-decoder

用法

JsonApiResponseDecoder旨在处理符合JSON:API标准的响应。它实现了Psr\Http\Message\ResponseInterface,并提供两个公开方法

  • getResource( ResponseInterface $response) : array
  • getResourceCollection( ResponseInterface $response) : array
<?php
use Germania\ResponseDecoder\ResponseDecoderInterface;
use Germania\ResponseDecoder\JsonApiResponseDecoder;

$response = ...
  
$decoder = new JsonApiResponseDecoder;

// Both are arrays
$resourceCollection = $decoder->getResourceCollection($response);
$singleResource = $decoder->getResource($response);

示例

物品集合

给定这个物品集合,每个物品都是位于data元素中的对象。

HTTP/1.1 200 OK
Content-Type: application/vnd.api+json

{
  "links": {
    "self": "http://example.com/articles"
  },
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!"
    }
  }, {
    "type": "articles",
    "id": "2",
    "attributes": {
      "title": "Rails is Omakase"
    }
  }]
}

JsonApiResponseDecoder将现在从data元素中收集每个对象并提取attributes

<?php
use Germania\ResponseDecoder\JsonApiResponseDecoder;
  
$response = ...
$items = (new JsonApiResponseDecoder)->getResourceCollection($response);

print_r($items);
// Array {
//   Array {
//     "title" => "JSON:API paints my bikeshed!"
//   },
//   Array {
//     "title" => "Rails is Omakase"
//   }
// }

单个物品

HTTP/1.1 200 OK
Content-Type: application/vnd.api+json

{
  "links": {
    "self": "http://example.com/articles/1"
  },
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!"
    },
    "relationships": {
      "author": {
        "links": {
          "related": "http://example.com/articles/1/author"
        }
      }
    }
  }
}

JsonApiResponseDecoder将现在从data元素中提取attributes

<?php
use Germania\ResponseDecoder\JsonApiResponseDecoder;
  
$response = ...

$item = (new JsonApiResponseDecoder)->getResource($response);

print_r($item);
// Array {
//   "title" => "JSON:API paints my bikeshed!"
// }

开发

$ git clone git@github.com:GermaniaKG/ResponseDecoder.git
$ cd ResponseDecoder
$ composer install

单元测试

要么将phpunit.xml.dist复制到phpunit.xml并适应您的需求,要么保持原样。运行PhpUnit测试或composer脚本,如下所示

$ composer test
# or
$ vendor/bin/phpunit