pre/prop-types

Phpx 组件的 Prop 类型验证器

0.2.1 2019-03-19 15:58 UTC

This package is auto-updated.

Last update: 2024-08-30 01:20:17 UTC


README

Support on Gitstore

这是对 ReactJS Prop Types 检查的 PHP 实现。我之所以这样做,是因为我想找到一个更容易的方式来验证 Phpx 组件中属性的类型和存在性。

入门指南

git clone git@github.com:preprocess/pre-prop-types.git
cd pre-prop-types
composer install
composer test

定义类型

我们支持大多数内置类型

use App\Profile;
use Pre\PropTypes;

$profile = Profile::find(1);

$definitions = [
    "name" => PropTypes::string()->isRequired(),
    "age" => PropTypes::int(),
    "rating" => PropTypes::float(),
    "permissions" => PropTypes::arrayOf(PropTypes::string()),
    "thumbnail" => PropTypes::either(
        PropTypes::string(), // uri
        PropTypes::resource(), // file handle
    ),
    "profile" => PropTypes::objectOf(Profile::class)->isRequired(),
    "onMessage" => PropTypes::closure()->isRequired(),
    "isAdmin" => PropTypes::bool()->isRequired(),
];

$properties = [
    "name" => "Joe",
    "profile" => $profile,
    "onMessage" => function($message) use ($profile) {
        $profile->notify($message);
    },
    "isAdmin" => false,
];

try {
    PropTypes::validate($definitions, $properties);
} catch (InvalidArgumentException $e) {
    // ...handle the error
}
  • isRequired 将确保值存在于随附的属性数组中
  • either 允许一个或多个类型(最好是两种不同的类型)进行比较

这些类型还有变体

  • PropTypes::array() 期望任何数组值,没有特定的类型
  • PropTypes::boolean()PropTypes::bool() 相同
  • PropTypes::integer()PropTypes::int() 相同
  • PropTypes::double() 期望双精度值
  • PropTypes::iterable() 期望任何可迭代的值
  • PropTypes::numeric() 期望任何数值
  • PropTypes::object() 期望任何对象值,没有特定的类型

验证类型

我们不自动验证 props,这必须由消费者完成。以下是一个 Phpx 渲染方法的示例

use Pre\PropTypes;
use function Pre\Phpx\Html\render as renderHTML;

function render($type, $props = [])
{
    $props = (array) $props;

    if (class_exists($type)) {
        if (method_exists($type, "propTypes")) {
            PropTypes::validate($type::propTypes(), $props);
        }

        if (method_exists($type, "defaultProps")) {
            $props = array_merge($type::defaultProps(), $props);
        }
    }

    return renderHTML($type, $props);
}

render("App\\Custom\\Component");