joshbrw / type-enforcement
强制类型,在类型无效时抛出InvalidArgumentException异常。
v0.1.2
2018-02-01 10:45 UTC
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: ^6.5
This package is auto-updated.
Last update: 2024-08-28 22:37:28 UTC
README
如果你曾经遇到过这样的情况:你在编写松散耦合的代码,但想在方法开始时检查参数类型,那么这个库就是为你准备的。
你可能正在这样做
class UserRegistrar { public function register(array $usersDetails, $author) { if (!$author instanceof SomeAuthor) { throw new \InvalidArgumentException('The author must be an instance of SomeAuthor'); } } }
让我们重构!
use Joshbrw\TypeEnforcement\Type; class UserRegistrar { public function register(array $usersDetails, $author) { /* Throws \InvalidArgumentException on invalid input */ Type::enforce($author, SomeAuthor::class); } }
自定义异常消息
默认情况下,该包将提供一个有用的异常消息,说明期望的类型和提供的类型,例如:
Expected [Tests\NonExistentClass], [array '["array"]'] provided.
此异常消息可以通过提供自定义消息作为第三个参数来替换,例如:
Type::enforce($variable, Type::class, 'The variable must be a Type!');
不喜欢静态方法调用?
此包还包括一个辅助方法,它接受相同的参数
enforce_type($variable, Type::class, 'The variable must be a Type!');