carpediem/jsend

一个符合JSend规范的不可变值对象

2.0.0 2018-09-07 13:57 UTC

This package is auto-updated.

Last update: 2024-09-08 07:22:13 UTC


README

Latest Version Software License Build Status Coverage Status Quality Score Total Downloads

JSend 是一个简化JSend兼容对象使用的简单库。

<?php

use Carpediem\JSend\JSend;

$data = [
    'post' => [
        'id' => 1,
        'title' => 'foo',
        'author' => 'bar',
    ],
];
$response = JSend::success($data);
$response->send(['Access-Control-Allow-Origin' => 'example.com']);
die;

亮点

  • 简单API
  • 不可变值对象

系统需求

您需要 PHP >= 7.0 来使用 JSend,但建议使用最新的稳定版本的 PHP/HHVM。

安装

使用 Composer 安装 JSend

$ composer require carpediem/jsend

文档

类摘要

final class JSend implements JsonSerializable
{
    const STATUS_SUCCESS = 'success';
    const STATUS_ERROR = 'error';
    const STATUS_FAIL = 'fail';

    public static function fromJSON($json, int $depth = 512, int $options = 0): self;
    public static function fromArray(array $arr): self;
    public static function success($data = null): self;
    public static function fail($data = null): self;
    public static function error($errorMessage, int $errorCode = null, $data = null): self;
    public function getStatus(): string;
    public function getData(): array;
    public function getErrorMessage(): ?string;
    public function getErrorCode(): ?int;
    public function isSuccess(): bool;
    public function isFail(): bool;
    public function isError(): bool;
    public function toArray(): array;
    public function __toString(): string;
    public function jsonSerialize(): array;
    public function send(array $headers = []): int;
    public function withStatus(string $status): self;
    public function withData($data): self;
    public function withError($errorMessage, int $errorCode = null): self;
}

类导入

<?php

use Carpediem\JSend\JSend;

创建新实例

使用命名构造函数实例化 JSend 对象创建

$success = JSend::success($data);
$fail = JSend::fail($data);
$error = JSend::error('Not Found', 404, $data);
$response = JSend::fromJSON('{"status":"success","data":{"post":{"id":1,"title":"foo","author":"bar"}}}');
$altResponse = JSend::fromArray(['data' => ['post' => 1], 'code' => 404, 'message' => 'Post not Found']);

如果无法创建对象,将抛出 Carpediem\JSend\Exception

访问属性

$response = JSend::error('Not Found', 404, ['post' => 1234]);
$response->getStatus();       // returns 'success, 'error', 'fail'
$response->getErrorMessage(); // returns 'Not Found'
$response->getErrorCode();    // returns 404
$response->getData();         // returns $data
$response->isSuccess();       // boolean
$response->isFail();          // boolean
$response->isError();         // boolean
  • JSend::getErrorMessageJSend::getStatus 不等于 error 时返回 null
  • JSend::getErrorCode 是一个整数或 null

操作

$response = JSend::success(['post' => 1234]);
(string) $response;  // returns {"status": "success", "data": {"post": 1234}}
echo json_encode($response, JSON_PRETTY_PRINT);
// returns
// {
//    "status": "success",
//    "data": {
//        "post": 1234
//    }
//}
$response->toArray();
// returns
// [
//    'status' => 'success',
//    'data' => [
//        'post' => 1234,
//    ]
// ]

更新

JSend 对象是不可变的,因此对对象的任何更改都将返回一个新的对象

$response = JSend::success();
$newResponse = $response->withData(['post' => 1234]);
$failResponse = $response->witStatus(JSend::STATUS_FAIL);
$errorResponse = $response->withError('This is an error', 404);

echo $response;      // returns {"status": "success"}
echo $newResponse;   // returns {"status": "success", "data": {"post": 1234}}
echo $failResponse;  // returns {"status": "fail"}
echo $errorResponse; // returns {"status": "error", "message": "This is an error", code: 404}

JSend::withData 接受 null 值、一个 array 或一个其 jsonSerialize 方法返回一个 arrayJsonSerializable 对象

JSend::withError$errorCode 参数是可选的

创建HTTP响应

header('HTTP/1.1 404 Not Found'); // don't forget to add the HTTP header
$response = JSend::fail(['post' => 1234]);
$response->send(['Access-Control-Allow-Origin' => '*']);
die;

JSend::send 接受以键/值对形式提供的外部头信息。

测试

库有一个

  • 一个 PHPUnit 测试套件
  • 一个使用 PHP CS Fixer 的代码风格合规性测试套件。
  • 一个使用 PHPStan 的代码分析合规性测试套件。

要运行测试,请在项目文件夹中运行以下命令。

$ composer test

贡献

欢迎贡献,并将完全归功于您。请参阅 CONTRIBUTING 了解详细信息。

安全性

如果您发现任何与安全相关的问题,请通过电子邮件发送到 dev@carpediem.fr,而不是使用问题跟踪器。

鸣谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 LICENSE