another-library/type-guard

此包已被废弃,不再维护。作者建议使用 gloss-php/type-guard 包。

类型守卫模块是 Pinkary 项目的一部分,允许您将变量的类型缩小到更具体的类型。

v0.1.0 2024-04-28 10:20 UTC

This package is auto-updated.

Last update: 2024-04-28 10:28:58 UTC


README

GitHub Workflow Status (master) Total Downloads Latest Version License

此库仍在开发中。请勿在生产环境中使用。

类型守卫模块是 Pinkary 项目 的一部分,允许您将变量的类型缩小到更具体的类型。使用 type 函数,您可以对对象执行特定检查以确定其类型,然后以根据 PHPStanPsalm 静态分析器的 类型安全 方式使用该对象。

以下是一个示例,我们使用 type 函数缩小一个之前类型为 mixed 的变量的类型

function config(): mixed;

// At compile time, the type of $apiKey is `mixed`:
$apiKey = config('api_key');

// We instruct the static analyzer that $apiKey is a `string`:
$apiKey = type($apiKey)->asString();

以下是一个示例,我们使用 type 函数缩小一个之前可能为 null 的变量的类型。在这个过程中,没有丢失任何类型信息

/** @var array<int, User>|null $users */
$users = getUsers();

// Narrows down the type to `array<int, User>`
$users = type($users)->not()->null();

还有一个示例,我们将变量的类型缩小到集合,而没有丢失类型信息

/** @var Collection<int, User>|null $users */
$users = getUsers();

// Narrows down the type to `Collection<int, User>`
$users = type($users)->as(Collection::class);

安装

需要 PHP 8.2+

您可以使用 Composer 将类型守卫安装到您的 PHP 项目中

composer require pinkary-project/type-guard

用法

as

断言并缩小给定变量的类型到更具体的类型。

$variable = type($variable)->as(User::class);

asInt()

断言并缩小给定变量的类型到整数。

$variable = type($variable)->asInt();

asFloat()

断言并缩小给定变量的类型到浮点数。

$variable = type($variable)->asFloat();

asString()

断言并缩小给定变量的类型到字符串。

$variable = type($variable)->asString();

asBool()

断言并缩小给定变量的类型到布尔值。

$variable = type($variable)->asBool();

asNull()

断言并缩小给定变量的类型到 null。

$variable = type($variable)->asNull();

asCallable()

断言并缩小给定变量的类型到可调用。

$variable = type($variable)->asCallable();

not()->null()

断言并缩小给定变量的类型到非空值。

$variable = type($variable)->not()->null();

asArray()

断言并缩小给定变量的类型到数组。

$variable = type($variable)->asArray();

asIterable()

断言并缩小给定变量的类型到可迭代。

$variable = type($variable)->asIterable();

类型守卫Pinkary 项目 的一部分。它由 Nuno Maduro 创建,并在 MIT 许可证 下开源。