PHP code example of rasuvaeff / result

1. Go to this page and download the library: Download rasuvaeff/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/ */

    

rasuvaeff / result example snippets


use Rasuvaeff\Result\Option;
use Rasuvaeff\Result\Result;

$user = Result::fromThrowable(
    fn (): array => ['id' => 42, 'email' => '[email protected]'],
)
    ->map(fn (array $row): string => $row['email'])
    ->unwrapOr(default: '[email protected]');

$name = Option::fromNullable(value: getenv('USER_NAME') ?: null)
    ->filter(fn (string $value): bool => $value !== '')
    ->unwrapOr(default: 'guest');

use Rasuvaeff\Result\Result;

$result = Result::ok(value: 21)
    ->map(fn (int $value): int => $value * 2)
    ->flatMap(fn (int $value): Result => $value > 40
        ? Result::ok(value: $value)
        : Result::err(error: 'too small'));

$message = $result->match(
    ok: fn (int $value): string => "Value: {$value}",
    err: fn (string $error): string => "Error: {$error}",
);

use Rasuvaeff\Result\Option;

$port = Option::fromNullable(value: getenv('PORT') ?: null)
    ->map(fn (string $value): int => (int) $value)
    ->filter(fn (int $value): bool => $value > 0)
    ->toResult(error: 'PORT is missing or invalid');