pldin601 / php-result
Abstraction that represends ok/fail result primitives
Installs: 47
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 1
Forks: 0
pkg:composer/pldin601/php-result
Requires (Dev)
- codeclimate/php-test-reporter: ^0.3.2
- phpunit/phpunit: ^5.3
- squizlabs/php_codesniffer: ^2.6
This package is not auto-updated.
Last update: 2025-10-26 01:11:56 UTC
README
Result is an abstraction that can be used for returning and propagating errors.
Result can be ok, representing success and containing a value,
or fail, representing error and containing an error value.
Inspired by Rust's module std::result.
Functions
use Result as R; R\ok('foo'); R\fail($value); R\resultify($callable, ...$args); R\notNull($callable, ...$args); R\tryCatch($callable, $exceptionTransformCallable, ...$args); R\isOk($result); R\isFail($result); R\ifOk($result, $callable); R\ifFail($result, $callable); R\getOrThrow($result, $exceptionClass); R\bind($result, $callable); R\pipeline(...$callables);
Pipeline example
use Result as R; $readFile = function($filename) { return R\with($filename, 'file_exists', 'file_get_contents', function () { return "Can't read the file."; }); } $proceedFile = function($content) { $transform = function ($exception) { return $exception->getMessage(); }; return R\tryCatch('doSomethingWithContent', $transform, $content); } $saveFile = function($filename) { return function ($content) use ($filename) { $bytesWritten = file_put_contents($filename, $content); return $bytesWritten === false ? R\fail("Can't save the file!") : R\ok(); } } $pipeline = R\pipeline($readFile, $proceedFile, $saveFile('/tmp/output_file')); $result = $pipeline('/tmp/input_file'); R\ifOk($result, function () { echo 'File successfully saved.'; });