crell/api-problem

PHP 对 IETF api-problem 规范的包装器

资助包维护!
Crell

安装次数: 1,670,505

依赖项: 23

建议者: 1

安全: 0

星标: 239

关注者: 10

分支: 21

开放问题: 1

3.6.1 2022-01-04 15:47 UTC

This package is auto-updated.

Last update: 2024-09-10 20:51:42 UTC


README

Build Status

此库提供了一个简单直接的 IETF HTTP API 问题详情实现,RFC 7807

RFC 7807 是一个简单的规范,用于格式化 Web 上 RESTful API 的错误响应。此库提供了一个简单方便的方式来与该规范交互。它支持生成和解析 RFC 7807 消息,包括 JSON 和 XML 变体。

生成响应

你说了什么?有人向你的 API 发送了错误的请求?告诉他们这是个问题!

use Crell\ApiProblem\ApiProblem;

$problem = new ApiProblem("You do not have enough credit.", "http://example.com/probs/out-of-credit");
// Defined properties in the API have their own setter methods.
$problem
  ->setDetail("Your current balance is 30, but that costs 50.")
  ->setInstance("http://example.net/account/12345/msgs/abc");
// But you can also support any arbitrary extended properties!
$problem['balance'] = 30;
$problem['accounts'] = [
  "http://example.net/account/12345",
  "http://example.net/account/67890"
];

$json_string = $problem->asJson();

// Now send that JSON string as a response along with the appropriate HTTP error
// code and content type which is available via ApiProblem::CONTENT_TYPE_JSON.
// Also check out asXml() and ApiProblem::CONTENT_TYPE_XML for the angle-bracket fans in the room.

或者,更好的是,你可以为特定的问题类型子类化 ApiProblem(因为类型和标题应该一起使用且相对固定),然后只填充你自己的错误特定数据。就像扩展异常一样!

如果你使用的是一个想要自己进行 JSON 序列化的库或框架,这也完全支持。ApiProblem 实现了\JsonSerializable,所以你可以直接将它传递给 json_encode(),就像它是一个裸数组一样。

$response = new MyFrameworksJsonResponse($problem);

// Or do it yourself
$body = json_encode($problem);

发送响应

你可能使用 PSR-7 来处理你的响应。这就是为什么这个库包括一个将你的 ApiProblem 对象转换为 PSR-7 ResponseInterface 对象的工具,使用你选择的 PSR-17 工厂。如下所示

use Crell\ApiProblem\HttpConverter;

$factory = getResponseFactoryFromSomewhere();

// The second parameter says whether to pretty-print the output.
$converter = new HttpConverter($factory, true);

$response = $converter->toJsonResponse($problem);
// or
$response = $converter->toXmlResponse($problem);

这将返回一个完整功能的标记响应对象,准备好发送回客户端。

接收响应

你是否向一个返回 API-Problem 错误的 API 发送消息?没问题!你可以轻松地这样处理响应

use Crell\ApiProblem\ApiProblem;

$problem = ApiProblem::fromJson($some_json_string);
$title = $problem->getTitle();
$type = $problem->getType();
// Great, now we know what went wrong, so we can figure out what to do about it.

(这也适用于 fromXml()!)

安装

像安装任何其他 Composer 包一样安装 ApiProblem

composer require crell/api-problem

有关更多信息,请参阅 Composer 文档

安全

如果你发现任何与安全相关的问题,请使用 GitHub 安全报告表单 而不是问题队列。

致谢

  • [Larry Garfield][link-author]
  • [所有贡献者][link-contributors]

许可证

此库在 MIT 许可下发布。简而言之,“保留版权声明,否则请随意。”有关更多信息,请参阅 LICENSE。

贡献

接受拉取请求!目标是完全符合 IETF 规范。