azjezz/input-hydrator

从请求输入中为数据传输对象(DTO)提供水分。

1.0.1 2020-11-01 04:02 UTC

This package is auto-updated.

Last update: 2024-08-29 05:43:35 UTC


README

Unit tests status Static analysis status Security analysis status Coding standards status TravisCI Build Status Coverage Status Type Coverage Mutation testing badge Total Downloads Latest Stable Version License

输入水分器是一个简单的水分器,专为提供数据传输对象(DTO)的水分而设计。

安装

$ composer require azjezz/input-hydrator

示例

use AzJezz\Input;

final class Search implements Input\InputInterface
{
    public string $query;
}

/**
 * @var Search $search
 */
$search = (new Input\Hydrator())->hydrate(Search::class, $_GET);

print $search->query;

在提供水分对象时,可能会抛出一些异常

  • AzJezz\Input\Exception\TypeException:这个异常应该导致500 HTTP状态码,因为它表示输入类本身存在问题。例如,使用非支持类型,或者缺少特定属性的类型。

  • AzJezz\Input\Exception\BadInputException:这个异常应该导致400 HTTP状态码,因为它意味着提供的请求数据与输入DTO结构不匹配。

目前,Input-Hydrator仅限于一组小类型

  • 标量字符串整数浮点数布尔值
  • 空值
  • 实现AzJezz\Input\InputInterface的任何对象

对于PHP >= 8.0,支持联合类型,例如

use AzJezz\Input;

final class Filter implements Input\InputInterface
{
    public ?int $maximumPrice;
    public ?int $minimumPrice;
}

final class Search implements Input\InputInterface
{
    public string $query;
    public null|Filter|string $filter = null;
}

/**
 * $filter is optional, and is missing from the request, therefore it's gonna contain the default value.
 *
 * @var Search $search
 */
$search = (new Input\Hydrator())->hydrate(Search::class, [
  'query' => 'hello'
]);

/**
 * $search->filter is now an instance of `Filter`
 *
 * @var Search $search
 */
$search = (new Input\Hydrator())->hydrate(Search::class, [
  'query' => 'hello',
  'filter' => [
    'maximum_price' => 1000,
    'minimum_price' => 10, // the field is optional ( nullable ), so we can remove this line.
  ]
]);

/**
 * $search->filter is now a string
 *
 * @var Search $search
 */
$search = (new Input\Hydrator())->hydrate(Search::class, [
  'query' => 'hello',
   // this is okay as the `null|Filter|string` union contains `string`
  'filter' => 'maximum_price=1000&minimum_price=10',
]);

print $search->query;

许可

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