jmf/type-validation

允许通过类型规范字符串来检查一个变量是否为预期的类型,例如PHPDoc块中的类型(int, \Foo\Bar[], null|string, 等)。

4.0.0 2023-07-01 16:53 UTC

This package is auto-updated.

Last update: 2024-08-30 01:55:24 UTC


README

此包允许通过类型规范字符串来检查一个变量是否为预期的类型,例如PHPDoc块中的类型。

类型规范字符串可以像以下这样

- integer
- scalar
- mixed
- string
- float[]
- int[][]
- {string:float}
- {int:\My\Stuff}
- {int:string}[]
- resource
- int|string
- {string:{int:\My\Stuff|int[]}}[]

等。

用法

使用异常进行静态验证

<?php

use Jmf\TypeValidation\Type;

// Valid, will not throw an exception.
Type::mustBe('string', 'foo');

// Invalid, will throw an exception.
Type::mustBe('string', 123);

使用布尔值进行静态验证

<?php

use Jmf\TypeValidation\Type;

$variable = 'foo';

if (Type::is('string', $variable)) {
	// Valid
} else {
	// Invalid
}

具体验证

您还可以使用类型验证器的具体实例。

<?php

use Jmf\TypeValidation\TypeValidator;

$validator = new TypeValidator();

$variable = 'foo';

if ($validator->isValid('string', $variable)) {
	// Valid
} else {
	// Invalid
}

典型用法

<?php

namespace App;

use Jmf\TypeValidation\Type;

class PotatoPeeler
{
    /**
     * @param Potato[] $potatoes
     */
    public function peel(array $potatoes): void
    {
        Type::mustBe('\App\Potato[]', $potatoes);

        // ...
    }
}