pinkary-project/type-guard

GitHub: pinkary-project/type-guard

Type Guard 是一个 PHP 库,通过缩窄变量类型来增强代码的类型安全性和可维护性。

Stars: 197 | Forks: 25

GitHub Workflow Status (master) Total Downloads Latest Version License

Type Guard 模块是 [Pinkary 项目](https://github.com/pinkary-project)的一部分,它允许你将变量的类型**缩窄**为更具体的类型。使用 `type` 函数,你可以执行特定的检查来确定对象的类型,然后以一种符合 [PHPStan](https://phpstan.org/) 和 [Psalm](https://psalm.dev/) 静态分析器要求的、**类型安全**的方式使用该对象。 下面是一个示例,我们使用 `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|null $users */ $users = getUsers(); // Narrows down the type to `array` $users = type($users)->not()->null(); ``` 再来一个例子,我们将一个变量的类型缩窄为 Collection,同时不丢失类型信息: ``` /** @var Collection|null $users */ $users = getUsers(); // Narrows down the type to `Collection` $users = type($users)->as(Collection::class); ``` ## 安装说明 你可以使用 [Composer](https://getcomposer.org) 将 Type Guard 安装到你的 PHP 项目中: ``` composer require pinkary-project/type-guard ``` ## 使用方法 - [`as`](#as) - [`asInt()`](#asint) - [`asFloat()`](#asfloat) - [`asString()`](#asstring) - [`asBool()`](#asbool) - [`asNull()`](#asnull) - [`asCallable()`](#ascallable) - [`not()->null()`](#notnull) - [`asArray()`](#asarray) - [`asIterable()`](#asiterable) ### `作为` 断言并将给定变量的类型缩窄为更具体的类型。 ``` $variable = type($variable)->as(User::class); ``` ### `转换为 Int()` 断言并将给定变量的类型缩窄为整数。 ``` $variable = type($variable)->asInt(); ``` ### `转换为 Float()` 断言并将给定变量的类型缩窄为浮点数。 ``` $variable = type($variable)->asFloat(); ``` ### `转换为 String()` 断言并将给定变量的类型缩窄为字符串。 ``` $variable = type($variable)->asString(); ``` ### `转换为 Bool()` 断言并将给定变量的类型缩窄为布尔值。 ``` $variable = type($variable)->asBool(); ``` ### `转换为 Null()` 断言并将给定变量的类型缩窄为 null。 ``` $variable = type($variable)->asNull(); ``` ### `转换为 Callable()` 断言并将给定变量的类型缩窄为可调用类型。 ``` $variable = type($variable)->asCallable(); ``` ### `not()->null()` 断言并将给定变量的类型缩窄为非 null 值。 ``` $variable = type($variable)->not()->null(); ``` ### `转换为 Array()` 断言并将给定变量的类型缩窄为数组。 ``` $variable = type($variable)->asArray(); ``` ### `转换为 Iterable()` 断言并将给定变量的类型缩窄为可迭代对象。 ``` $variable = type($variable)->asIterable(); ``` **Type Guard** 是 [Pinkary 项目](https://github.com/pinkary-project)的一部分。它由 **[Nuno Maduro](https://twitter.com/enunomaduro)** 创建,并以 **[MIT 许可证](https://opensource.org/licenses/MIT)** 开源。
标签:Composer, ffuf, OpenVAS, PHP, PHPStan, Psalm, SOC Prime, 云安全监控, 变量类型检查, 开发工具, 数据管道, 类型守卫, 类型安全, 类型窄化, 软件工程, 轻量级库, 静态分析