该包已废弃,不再维护。作者建议使用hamet-framework/type包代替。

Hamlet Framework / Cast

0.0.1 2019-04-18 11:21 UTC

This package is auto-updated.

Last update: 2019-05-01 09:19:58 UTC


README

在PHP中指定表达式类型的五个方面

  1. 类型的最精确指定(我们假设它是psalm语法),例如 array<int,DateTime|null>
  2. 需要执行的断言序列,以检查运行时实际对象是否具有此类型,伪代码如下:assert($records instanceof array<int,DateTime|null>)
  3. 类型转换将告诉静态分析器(目前指的是psalm)转换后的确切类型指定,伪代码如下:(array<int,DateTime|null>) $records
  4. 从其他类型推导类型的能力,无需进行字符串操作,伪代码如下:array<int,DateTime|null> || null

此库提供了类型指定的基本构建块。例如以下表达式

$type = _map(
  _int(), 
  _union(
    _class(DateTime::class), 
    _null()
  )
)

创建了一个类型为Type<array<int,DateTime|null>>的对象。

此对象可以以下方式进行使用

在运行时断言$records的类型为array<int,DateTime|null>>

assert($type($records));

$records转换为array<int,DateTime|null>>,如果启用断言并在转换失败时抛出异常

return $type->cast($records);

$records转换为array<int,DateTime|null>>,如果转换失败则抛出运行时异常

return $type->castOrFail($records);

将类型与其他类型组合,例如,使其可空:array<int,DateTime|null>>|null

_union($type, _null())

对象数组

对象数组指定为更简单属性类型的交集。例如,对于类型array{id:int,name:string,valid?:bool}对应于以下结构

$type = _intersection(
    _property('id', true, _int()),
    _property('name', true, _string()),
    _property('valid', false, _bool())
);

听起来有点复杂。但它允许我们进行如下操作