plook/type-guard

提供可读接口的类型正确性库。

0.8.0 2024-02-19 08:31 UTC

This package is auto-updated.

Last update: 2024-09-24 02:47:24 UTC


README

codecov

一个用于确保类型正确性并提供可读接口的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);