JSend规范的简单PHP实现。

v6.0.0 2023-12-15 13:04 UTC

This package is auto-updated.

Last update: 2024-09-21 10:27:26 UTC


README

Build Status Build Status Build Status Build Status

Code Climate
Issue Count

Total Downloads

JSend

JSend规范的简单PHP实现。JSend规范

用法

use JSend\JSendResponse;

新响应

$success = new JSendResponse('success', $data);
$fail = new JSendResponse('fail', $data);
$error = new JSendResponse('error', $data, 'Not cool.', 9001);
$success = JSendResponse::success($data);
$fail = JSendResponse::fail($data);
$error = JSendResponse::error('Not cool.', 9001, $data);

注意:如果状态无效或创建一个没有消息的 error,将抛出 InvalidJSendException

将JSendResponse转换为JSON

__toString() 被重写来自动编码JSON。

$json = $success->encode();
$json = (string) $success;

由于JSendResponse是 JsonSerializable,可以直接在 json_encode 中使用该对象。

json_encode($success);

设置标志

如果需要,可以设置标志。

$success->setEncodingOptions(\JSON_PRETTY_PRINT | \JSON_BIGINT_AS_STRING);
$json = $success->encode();

将JSON转换为JSendResponse

try {
    $response = JSendResponse::decode($json);
} catch (InvalidJSendException $e) {
    echo "You done gone passed me invalid JSend.";
}

将JSON作为HTTP响应发送

这会将 Content-Type 标头设置为 application/json 并输出JSON。

$jsend = new JSendResponse('success', $data);
$jsend->respond();

获取信息

$isSuccess = $response->isSuccess();
$isError = $response->isError();
$isFail = $response->isFail();
$status = $response->getStatus();
$data = $response->getData();
$array = $response->asArray();

此外,还可以在错误上调用以下方法。如果状态不是 error,将抛出 BadMethodCallException,因此请先进行检查。

if ($response->isError()) {
    $code = $response->getErrorCode;
    $message = $response->getErrorMessage;
}

开发

为了您的方便,有一个包含正确依赖项(PHP、composer)的Dockerfile可用。请使用这些依赖项运行各种操作(composer、phpunit等)。您需要安装 docker,但不需要 PHPcomposer 或其他依赖项。

设置和使用本地环境

要开始使用本地环境进行测试和调试,只需在项目的根目录中打开一个shell。然后运行以下命令。

make build install

此命令应偶尔运行以保持本地环境最新。例如,当composer依赖项更改时。

使用shell

要打开Docker容器中的shell,请运行以下命令。

make shell

可用的命令在 /bin

在本地运行代码质量工具

我们使用各种工具来保持库的代码质量。要运行其中一个工具,只需运行

make <tool_name>

可用的工具

  • phpstan PHPStan 是一种静态分析工具,可以检测各种代码问题。
  • phpunit PHPUnit 是我们用于此库的单元测试框架。
  • codeclimate CodeClimate

注意

  • 请注意,composer.lock 文件被忽略。

鸣谢

此库由 Jamie Schembri 编写。它于2015年12月转移到当前账户 Nanne Huiges