JSend API 转换器,输出有效的 API 响应。

1.0.3 2015-10-17 00:19 UTC

This package is not auto-updated.

Last update: 2024-09-14 18:14:57 UTC


README

构建状态 Scrutinizer 代码质量 [SensioLabsInsight] (https://insight.sensiolabs.com/projects/2ee8556c-d480-4f6f-a645-0ee18c271867) [最新稳定版本] (https://packagist.org.cn/packages/nilportugues/jsend) [总下载量] (https://packagist.org.cn/packages/nilportugues/jsend) 许可证 捐赠

安装

使用 Composer 安装包

$ composer require nilportugues/jsend

用法

给定一个 PHP 对象和一系列映射,JSend 转换器 将将数据表示为 JSON 对象。

例如,给定以下代码片段,定义一个博客文章和一些评论

$post = new Post(
  new PostId(9),
  'Hello World',
  'Your first post',
  new User(
      new UserId(1),
      'Post Author'
  ),
  [
      new Comment(
          new CommentId(1000),
          'Have no fear, sers, your king is safe.',
          new User(new UserId(2), 'Barristan Selmy'),
          [
              'created_at' => (new DateTime('2015/07/18 12:13:00'))->format('c'),
              'accepted_at' => (new DateTime('2015/07/19 00:00:00'))->format('c'),
          ]
      ),
  ]
);

以及所有涉及类的映射数组

use NilPortugues\Api\Mapping\Mapper;

$mappings = [
    [
        'class' => Post::class,
        'alias' => 'Message',
        'aliased_properties' => [
            'author' => 'author',
            'title' => 'headline',
            'content' => 'body',
        ],
        'hide_properties' => [

        ],
        'id_properties' => [
            'postId',
        ],
        'urls' => [
            'self' => 'http://example.com/posts/{postId}',
            'comments' => 'http://example.com/posts/{postId}/comments'
        ],
    ],
    [
        'class' => PostId::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'postId',
        ],
        'urls' => [
            'self' => 'http://example.com/posts/{postId}',
        ],
    ],
    [
        'class' => User::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'userId',
        ],
        'urls' => [
            'self' => 'http://example.com/users/{userId}',
            'friends' => 'http://example.com/users/{userId}/friends',
            'comments' => 'http://example.com/users/{userId}/comments',
        ],
    ],
    [
        'class' => UserId::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'userId',
        ],
        'urls' => [
            'self' => 'http://example.com/users/{userId}',
            'friends' => 'http://example.com/users/{userId}/friends',
            'comments' => 'http://example.com/users/{userId}/comments',
        ],
    ],
    [
        'class' => Comment::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'commentId',
        ],
        'urls' => [
            'self' => 'http://example.com/comments/{commentId}',
        ],
    ],
    [
        'class' => CommentId::class,
        'alias' => '',
        'aliased_properties' => [],
        'hide_properties' => [],
        'id_properties' => [
            'commentId',
        ],
        'urls' => [
            'self' => 'http://example.com/comments/{commentId}',
        ],
    ],
];

$mapper = new Mapper($mappings);

调用转换器将输出使用正确格式的 有效 JSON 响应

use NilPortugues\Api\JSend\JSendTransformer;
use NilPortugues\Api\JSend\Http\Message\Response;
use NilPortugues\Serializer\DeepCopySerializer;

$transformer = new JSendTransformer($mapper);

//Output transformation
$serializer = new DeepCopySerializer($transformer);
$serializer->setSelfUrl('http://example.com/posts/9');
$serializer->setNextUrl('http://example.com/posts/10');
$serializer->addMeta('author',[['name' => 'Nil Portugués Calderó', 'email' => 'contact@nilportugues.com']]);

$output = $serializer->serialize($post);

//PSR7 Response with headers and content.
$response = new Response($output);

header(
    sprintf(
        'HTTP/%s %s %s',
        $response->getProtocolVersion(),
        $response->getStatusCode(),
        $response->getReasonPhrase()
    )
);
foreach($response->getHeaders() as $header => $values) {
    header(sprintf("%s:%s\n", $header, implode(', ', $values)));
}

echo $response->getBody();

输出

HTTP/1.1 200 OK
Cache-Control: private, max-age=0, must-revalidate
Content-type: application/json; charset=utf-8
{
    "status": "success",
    "data": {
        "post_id": 9,
        "title": "Hello World",
        "content": "Your first post",
        "author": {
            "user_id": 1,
            "name": "Post Author"
        },
        "comments": [
            {
                "comment_id": 1000,
                "dates": {
                    "created_at": "2015-07-18T12:13:00+00:00",
                    "accepted_at": "2015-07-19T00:00:00+00:00"
                },
                "comment": "Have no fear, sers, your king is safe.",
                "user": {
                    "user_id": 2,
                    "name": "Barristan Selmy"
                }
            }
        ]
    },
    "links": {
        "self": {
            "href": "http://example.com/post/9"
        },
        "next": {
            "href": "http://example.com/post/10"
        },
        "comments": {
            "href": "http://example.com/post/9/comments"
        }
    }
}

质量

要运行 PHPUnit 测试,请转到测试目录并运行 phpunit。

此库试图遵守 PSR-1PSR-2PSR-4PSR-7

如果您注意到合规性疏忽,请通过 Pull Request 提交补丁。

贡献

欢迎对包的贡献!

支持

您可以通过以下方式之一与我联系

作者

许可协议

代码库采用MIT许可协议