gloss-php / type-guard

该包已被废弃,不再维护。作者建议使用https://github.com/pinkary-project/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();

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

/** @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 许可证 下开源。