prezly/prop-types

React PropTypes 的完整 PHP 端口

1.3.3 2023-10-05 13:33 UTC

This package is auto-updated.

Last update: 2024-09-05 15:43:07 UTC


README

React PropTypes 的完整 PHP 端口。

对复杂属性结构的运行时类型检查。

您可以使用 prop-types 来记录传递到您的代码中的属性预期类型。PropTypes 将检查传递给您的函数的 props 与这些定义是否匹配,如果不匹配则抛出错误。

Build status

安装

composer require prezly/prop-types

用法

PropTypes最初作为React核心模块的一部分公开,通常与React组件一起使用。我们尝试将React PropTypes的熟悉感引入PHP。

您可以通过调用PropTypes::check()来验证一个props数组,并为其提供一个如下所示的props规范

<?php

use Prezly\PropTypes\Exceptions\PropTypeException;
use Prezly\PropTypes\PropTypes;

function myFunction(array $options): void
{
    PropTypes::check([
        // You can declare that a prop has a specific type.
        // By default, these are all required and not nullable.
        'requiredFoo' => PropTypes::equals('foo'),
        'requiredArray' => PropTypes::array(),
        'requiredBool' => PropTypes::bool(),
        'requiredInteger' => PropTypes::int(),
        'requiredFloat' => PropTypes::float(),
        'requiredObject' => PropTypes::object(),
        'requiredString' => PropTypes::string(),
        // You can also declare that a prop is an instance of a class.
        // This uses `instanceof` operator.
        'requiredDateTime' => PropTypes::instanceOf(DateTime::class),
        // You can ensure that your prop is limited to specific values
        // by treating it as an enum.
        'requiredEnum' => PropTypes::oneOf(['News', 'Photos']),
        // An object that could be one of many types
        'requiredUnion' => PropTypes::oneOfType([
            PropTypes::string(),
            PropTypes::int(),
            PropTypes::instanceOf(DateTime::class),
        ]),
        'requiredCallable' => PropTypes::callable(),

        // An array of a certain type
        'requiredArrayOf' => PropTypes::arrayOf(PropTypes::int()),

        // You can chain any of the above with `isOptional()`
        // to make sure an error is not thrown if the prop isn't provided.

        // An object taking on a particular shape
        'requiredArrayWithShape' => PropTypes::shape([
            'requiredProperty' => PropTypes::int(),
            'optionalProperty' => PropTypes::string()->isOptional(),
        ]),

        // An object with errors on extra properties
        'requiredObjectWithStrictShape' => PropTypes::exact([
            'requiredProperty' => PropTypes::int(),
            'optionalProperty' => PropTypes::string()->isOptional(),
        ]),
    
        // You can chain any of the above with `isNullable()`
        // to allow passing `null` as a value.

        'requiredNullableString' => PropTypes::string()->isNullable(),
        'optionalNullableString' => PropTypes::string()->isNullable()->isOptional(),
        
        // A value of any data type (except null)
        'requiredAny' => PropTypes::any(),
        // A value of any data type (including null)
        'requiredNullableAny' => PropTypes::any()->isNullable(),

        // You can also specify a custom validator.
        // It should *return* a PropTypeException instance if the validation fails.
        'customProp' => PropTypes::callback(
            function (array $props, string $prop_name, string $prop_full_name): ?PropTypeException {
                if (! preg_match('/matchme /', $props[$prop_name])) {
                    return new PropTypeException(
                        $prop_name,
                        'Invalid prop `' . $prop_full_name . '` supplied. Validation failed.'
                    );
                }
                return null;
            }
        ),

        // You can also supply a custom validator to `arrayOf` and `objectOf`.
        // It should return an Error object if the validation fails. The validator
        // will be called for each key in the array or object. The first two
        // arguments of the validator are the array or object itself, and the
        // current item's key.
        'customArrayProp' => PropTypes::arrayOf(
            PropTypes::callback(function (array $props, string $prop_name, string $prop_full_name) {
                if (! preg_match('/matchme /', $props[$prop_name])) {
                    return new PropTypeException(
                        $prop_name,
                        'Invalid prop `' . $prop_full_name . '` supplied. Validation failed.'
                    );
                }
                return null;
            })
        ),
    ], $options);
}

与React PropTypes的区别

  1. 在这个包中,我们将可选的可空的检查分成了不同的特性

    • 可选的意味着一个属性可以从props对象中省略
    • 可空的意味着属性值可以设置为null

    React PropTypes关于必需的、null和undefined的逻辑不太直接。

  2. 与React PropTypes不同,我们没有为null(PropTypes::null())提供一个单独的检查器。相反,任何属性都可以通过在其检查器上调用->isNullable()来变为可空的

    [
       'title' => PropTypes::string()->isNullable(),
    ]
  3. 与React PropTypes不同,所有属性默认都是必需的(这意味着它们不能被省略)。除非明确在其类型检查器上调用isOptional()

    这样做是为了更接近原生的PHP语言语义。

变更日志

此项目的所有显著更改都将记录在CHANGELOG文件中。

格式基于Keep a Changelog,本项目遵循语义版本控制

Prezly倾情奉献。