Page MenuHomeDevCentral

Implement a similar datatype than Rust result
Changes PlannedPublic

Authored by dereckson on Sep 2 2018, 00:02.
Tags
None
Referenced Files
F2747632: D1656.id4230.diff
Fri, Mar 29, 06:29
Unknown Object (File)
Thu, Mar 28, 02:09
Unknown Object (File)
Fri, Mar 22, 21:06
Unknown Object (File)
Sun, Mar 17, 02:41
Unknown Object (File)
Tue, Mar 12, 22:24
Unknown Object (File)
Mon, Mar 11, 01:21
Unknown Object (File)
Mon, Mar 11, 01:18
Unknown Object (File)
Feb 22 2024, 00:16
Subscribers
None

Details

Reviewers
dereckson
Summary

When a library needs to communicate an error status, to be handled
only by an initial caller down in the task or a success, the Result
generic type from the Rust library is convenient.

If PHP doesn't have the generics and Rust-like enum, we can at least
provide a base class Result, with two concrete implementations:

  • Err for exceptions
  • Ok for actual values

Reference:
https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html

Test Plan

Implement in Zed story engine

Diff Detail

Repository
rKOT Keruald OmniTools
Lint
Lint Passed
Unit
Tests Passed
Branch
Result (branched from master)
Build Status
Buildable 2601
Build 2849: arc lint + arc unit

Event Timeline

dereckson created this revision.

Some ideas to make this code more useful:

  • a constructor to allow new Ok(42)
  • implement map methods:
    • or_else(defaultValue) -> return defaultValue for Err, $this->value for Ok
    • map() -> no op for Err, change value allowing type mutability for Value
    • map_err() -> no op for Value, change value allowing any Exception for Err

In PHP 8.1, could be interesting to do this:

Result sample use
use Keruald\OmniTools\DataTypes\Result;
use Keruald\OmniTools\DataTypes\ResultShape;

#[ResultShape(string, string)]
function doSomething() : Result {
    return ...;
}

$result = match (doSomething()) {
    $result->isOk() => $result->getValue(),
    default => throw new RuntimeException($result->getError()),
};

For this to work, we need two things:

  • Declare getError() in Result too
  • A ResultShape attribute to be able to typehint the Result