texthtml / maybe
选项 & 结果类型
v0.6.0
2023-07-22 22:01 UTC
Requires (Dev)
- phpspec/prophecy-phpunit: ^2.0
- phpstan/extension-installer: ^1.1
- phpstan/phpstan: ^1.4
- phpstan/phpstan-phpunit: ^1.0
- phpstan/phpstan-strict-rules: ^1.1
- phpunit/phpunit: ^9.5
- slevomat/coding-standard: ^8.0
- squizlabs/php_codesniffer: ^3.6
- symfony/console: ^6.1
- symfony/finder: ^6.1
- texthtml/doctest: ^0.2
- vimeo/psalm: ^4.22
- dev-main
- v0.6.0
- v0.5.0
- v0.4.0
- v0.3.0
- v0.2.0
- v0.1.0
- dev-renovate/phpunit-phpunit-11.x
- dev-renovate/major-symfony
- dev-renovate/vimeo-psalm-5.x
- dev-renovate/actions-configure-pages-5.x
- dev-renovate/composer-2.x
- dev-renovate/php-8.x
- dev-renovate/actions-upload-pages-artifact-3.x
- dev-renovate/actions-checkout-4.x
- dev-renovate/actions-cache-4.x
This package is auto-updated.
Last update: 2024-09-23 22:53:50 UTC
README
通过使用 Option
& Result
代替返回 null
、false
、-1
或抛出异常,可以帮助你避免返回这些值,从而更好地管理代码。
使用这些类型可以使错误更难发生,更容易处理未知返回值,并有助于静态分析工具检测 PHP 代码中的错误逻辑。
安装
composer req texthtml/maybe
文档
阅读文档,了解完整的 API 描述、详细解释和用法。
用法
Option
TH\Maybe\Option
是一个表示可选值的类型:每个 Option
要么是 Some
并且包含一个值,要么是 None
,不包含值。
/** * @return Option<float> */ function divide(float $numerator, float $denominator): Option { return match ($denomintor) { 0.0 => Option\none(), default => Option\some($numerator / $denominator), }; } // The return value of the function is an option $result = divide(2.0, 3.0); // Pattern match to retrieve the value if ($result->isSome()) { // The division was valid echo "Result: {$option->unwrap()}"; } else { // The division was invalid echo "Cannot divide by 0"; }
Result
TH\Maybe\Result
是一个表示操作成功(Ok
)并包含操作结果的类型或失败(Err
)并包含失败原因的类型。
/** * @return Result<int,string> */ function parse_version(string $header): Result { return match ($header[0] ?? null) { null => Result\err("invalid header length"), "1" => Result\ok(1), "2" => Result\ok(2), default => Result\err("invalid version"), }; } $version = parse_version("1.x"); if ($version->isOk()) { echo "working with version: {$version->unwrap()}"; } else { echo "error parsing header: {$version->unwrapErr()}"; } // @prints working with version: 1