Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/pyldin601/php-result
Abstraction that represents result of something
https://github.com/pyldin601/php-result
Last synced: about 1 month ago
JSON representation
Abstraction that represents result of something
- Host: GitHub
- URL: https://github.com/pyldin601/php-result
- Owner: pyldin601
- Created: 2016-06-01T06:57:21.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2023-12-15T05:53:30.000Z (about 1 year ago)
- Last Synced: 2024-12-08T22:00:13.090Z (about 2 months ago)
- Language: PHP
- Homepage:
- Size: 28.3 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# php-result
[![Build Status](https://travis-ci.org/pldin601/php-result.svg?branch=master)](https://travis-ci.org/pldin601/php-result)
[![Code Climate](https://codeclimate.com/github/pldin601/php-result/badges/gpa.svg)](https://codeclimate.com/github/pldin601/php-result)
[![Test Coverage](https://codeclimate.com/github/pldin601/php-result/badges/coverage.svg)](https://codeclimate.com/github/pldin601/php-result/coverage)
[![Issue Count](https://codeclimate.com/github/pldin601/php-result/badges/issue_count.svg)](https://codeclimate.com/github/pldin601/php-result)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
```php
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
```php
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.';
});```