germania-kg / response-decoder
API响应解码器的接口和特性
1.1.1
2022-03-30 09:52 UTC
Requires
- php: ^7.1|^8.0
- germania-kg/jsondecoder: ^1.0
- psr/http-message: ^1.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.0
- php-coveralls/php-coveralls: ^2.0
- phpspec/prophecy-phpunit: ^2.0
- phpunit/phpunit: ^9.0
- spatie/phpunit-watcher: ^1.0
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