std-library / type-guard
该包已被废弃,不再维护。作者建议使用https://github.com/another-library/type-guard包。
类型守卫模块是Pinkary项目的组成部分,允许您将变量的类型缩小到更具体的类型。
v0.1.0
2024-04-28 10:20 UTC
Requires
- php: ^8.2.0
Requires (Dev)
- laravel/pint: ^1.15.2
- pestphp/pest: ^3.0.0
- pestphp/pest-plugin-type-coverage: 3.x-dev
- phpstan/phpstan: ^1.10.67
- rector/rector: ^1.0.4
- symfony/var-dumper: ^6.4.0|^7.0.6
This package is auto-updated.
Last update: 2024-04-28 10:28:59 UTC
README
这个库还在开发中,请勿在生产环境中使用。
类型守卫模块是Pinkary项目的组成部分,允许您将变量的类型缩小到更具体的类型。使用type
函数,您可以执行特定检查以确定对象的类型,然后以根据PHPStan和Psalm静态分析器的类型安全方式使用该对象。
以下是一个示例,其中我们使用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将Type Guard安装到您的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()
断言并缩小给定变量的类型到非null值。
$variable = type($variable)->not()->null();
asArray()
断言并缩小给定变量的类型到数组。
$variable = type($variable)->asArray();
asIterable()
断言并缩小给定变量的类型到可迭代。
$variable = type($variable)->asIterable();
类型守卫是Pinkary项目的一部分。它由Nuno Maduro创建,并开源在MIT许可证下。