Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Result Type for handling Exceptions #2

Open
witling opened this issue Sep 3, 2021 · 1 comment
Open

Add Result Type for handling Exceptions #2

witling opened this issue Sep 3, 2021 · 1 comment

Comments

@witling
Copy link

witling commented Sep 3, 2021

Idea: Introduce a new class for wrapping up operation results or errors like a sum type.

Old code:

$env = lowebf\Environment::getInstance();
// will throw an exception
$posts = $env->posts()->loadPage(null);
// ...

New code:

$env = lowebf\Environment::getInstance();
// throws an exception like previous example
$posts = $env->posts()->loadPage(null)->unwrap();
// returns the result if found or exits script if not
$posts = $env->posts()->loadPage(null)->unwrapOrExit($env);
// ...

$env->listDirectory(null)
        ->mapOk(function ($folders) {
            // ... do something with folders ...
            return $folders;
        });

Mockup

class Result {
    const OK_STATE = 1;
    const ERROR_STATE = 2;

    /** @var int */
    private $state;
    private $argument;

    private function __construct(int $state, $argument);

    public static function ok($value) : Result;

    public static function error(Exception $e) : Result;

    public function isOk() : bool;

    public function isError() : bool;

    // try to return operations result.
    // throws exception if result is not successful.
    public function unwrap();

    // unwrap the result or use default
    public function unwrapOr($default);

    // clear output buffer and set status code
    public function unwrapOrExit(Environment $env, $statusCode = null);
   
    // if the result is ok -> pass it to $mapper and wrap it in a new result.
    // returns itself otherwise.
    public function mapOk(callable $mapper) : Result;
}
@lausek
Copy link
Owner

lausek commented Oct 8, 2021

Implemented but needs more testing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants