PHP code example of pldin601 / php-result

1. Go to this page and download the library: Download pldin601/php-result library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

pldin601 / php-result example snippets


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);

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.';
});