Page MenuHomeDevCentral

Introduce Result class with Ok and Err types for status handling
ClosedPublic

Authored by dereckson on Sep 2 2018, 00:02.
Tags
None
Referenced Files
Unknown Object (File)
Tue, Nov 19, 19:34
Unknown Object (File)
Tue, Nov 19, 18:51
Unknown Object (File)
Tue, Nov 19, 17:47
Unknown Object (File)
Tue, Nov 19, 14:57
Unknown Object (File)
Tue, Nov 19, 14:56
Unknown Object (File)
Tue, Nov 19, 14:55
Unknown Object (File)
Tue, Nov 19, 14:25
Unknown Object (File)
Tue, Nov 19, 10:29
Subscribers
None

Details

Summary

This change adds a Result class to improve error and success handling.

Inspired by Rust generic type Result, this approach allows functions to return
either an Ok type for successful outcomes or an Err type for errors.

In PHP, where generics and enums are not natively available, Result serves
as a base class with two implementations:

  • Err for exceptions
  • Ok for successful values

This pattern provides a more structured and readable way to handle
results and errors explicitly compared to traditional exception handling.

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

Test Plan

Implement in Zed story engine

Diff Detail

Repository
rKERUALD Keruald libraries development repository
Lint
Lint Not Applicable
Unit
Tests Not Applicable

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

Moved to keruald monorepo and rebased.

dereckson retitled this revision from Implement a similar datatype than Rust result to Introduce Result class with Ok and Err types for status handling.Mon, Nov 11, 13:59

Update PHPUnit tests for PHPUnit 10+

Switch from Exception to Thowrable. Implement constructors/map/mapErr/or_else per previous comment.

Switch method names to camel case

This revision is now accepted and ready to land.Mon, Nov 11, 15:16
This revision was landed with ongoing or failed builds.Mon, Nov 11, 15:17
This revision was automatically updated to reflect the committed changes.