perf/type-validation

此包已被放弃且不再维护。作者建议使用 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: 2023-07-01 16:55:48 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);

        // ...
    }
}