texthtml/maybe

选项 & 结果类型


README

通过使用 Option & Result 代替返回 nullfalse-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