plook / type-guard
提供可读接口的类型正确性库。
0.8.0
2024-02-19 08:31 UTC
Requires
- php: ^8.2
Requires (Dev)
- brainbits/phpcs-standard: ^7.0
- ergebnis/phpstan-rules: ^2.2.0
- phpstan/phpstan: ^1.10.58
- phpstan/phpstan-phpunit: ^1.3.15
- phpunit/phpunit: ^11.0.3
- rector/rector: ^1.0.1
- squizlabs/php_codesniffer: ^3.9.0
- thecodingmachine/phpstan-safe-rule: ^1.2.0
- thecodingmachine/phpstan-strict-rules: ^1.0.0
README
一个用于确保类型正确性并提供可读接口的PHP库。
安装
$ composer require plook/type-guard
示例
use function Plook\TypeGuard\asBool; use function Plook\TypeGuard\asDateTimeImmutable; use function Plook\TypeGuard\asFloat; use function Plook\TypeGuard\asInt; use function Plook\TypeGuard\asString; use function Plook\TypeGuard\notNull; $row = $this->fetchProjectRow(123); $project = new Project( notNull(asInt($row['id'])), notNull(asString($row['name'])), notNull(asDateTimeImmutable($row['createdAt'])), notNull(asBool($row['is_assigned'])), asDateTimeImmutable($row['closedAt']), asFloat($row['rating']), );
提供的辅助函数
确保类型
asBool($value)
将输入值转换为布尔值,但传递null
。asFloat($value)
将输入值转换为浮点数,但传递null
。asInt($value)
将输入值转换为整数,但传递null
。asDateTimeImmutable($value)
将输入值转换为DateTimeImmutable
对象,但传递null
。asDateTimeString($value)
将输入值转换为包括时区的日期字符串,但传递null
。asString($value)
将输入值转换为字符串,但传递null
。
断言
notNull($value)
如果值是null
则抛出异常,否则传递原始值。
配置
设置 DateTimeImmutable
对象的默认目标时区
use Plook\TypeGuard\TypeGuard; TypeGuard::instance()->timeZone('Australia/Adelaide'); TypeGuard::instance()->timeZone(new DateTimeZone('Australia/Adelaide'));
设置日期时间字符串的默认格式
use Plook\TypeGuard\TypeGuard; TypeGuard::instance()->dateTimeFormat(DateTimeInterface::ATOM);