PHP code example of helloimalemur / rustify-php

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

    

helloimalemur / rustify-php example snippets


use Rustify\Json;
use function Rustify\{ok, err, some, none};

$raw = '{"name":"James"}';

$res = Json::decodeObject($raw);

if ($res->isErr()) {
    $err = $res->unwrapErr();
    // handle error
} else {
    $data = $res->unwrap();
    // handle data
}

use Rustify\Option;
use function Rustify\{some, none};

$optA = some("value");
$optB = none();

if ($optA->isSome()) {
    $v = $optA->unwrap();
}

$nameOpt = some("James")
    ->map(fn($name) => strtoupper($name))
    ->andThen(fn($name) => strlen($name) > 0 ? some($name) : none());

$final = $nameOpt->unwrapOr("Unknown");


use Rustify\Result;
use function Rustify\{ok, err};

function open_file(string $path): Result
{
    return is_readable($path)
        ? ok(file_get_contents($path))
        : err("File not readable");
}

$res = open_file("config.json");

if ($res->isOk()) {
    $content = $res->unwrap();
} else {
    $error = $res->unwrapErr();
}

$parsed = open_file("config.json")
    ->andThen(fn($s) => ok(json_decode($s, true)))
    ->map(fn($arr) => $arr["name"] ?? "none")
    ->unwrapOr("missing");

use function Rustify\{some, none, option_or_else_value};

$a = some('A');
$b = some('B');

// Eager: returns $a because it's Some
$x = $a->orElseValue($b);         // Some('A')

// Lazy: closure will NOT be called because $a is Some
$y = $a->orElse(fn() => some('C')); // Some('A')

// When None, eager uses provided value; lazy executes the closure
$n = none();
$x2 = $n->orElseValue($b);          // Some('B')
$y2 = $n->orElse(fn() => some('C')); // Some('C')

// The same using the helper function:
$x3 = option_or_else_value($a, $b); // Some('A')
$x4 = option_or_else_value($n, $b); // Some('B')

use function Rustify\{ok, err, result_or_else_value};

$r1 = ok(10);
$r2 = err('network');

// Eager: value provided upfront
$a = $r1->orElseValue(ok(0)); // Ok(10)
$b = $r2->orElseValue(ok(0)); // Ok(0)

// The same using the helper function:
$a2 = result_or_else_value($r1, ok(0)); // Ok(10)
$b2 = result_or_else_value($r2, ok(0)); // Ok(0)

// Lazy: closure gets the error when called
$c = $r1->orElse(fn(string $e) => ok(0));     // Ok(10), closure not called
$d = $r2->orElse(fn(string $e) => ok(strlen($e))); // Ok(7)

// Likewise for unwrap defaults:
$n = $r2->unwrapOrElse(fn(string $e) => strlen($e)); // 7

function validateUser(array $body): Result
{
    if (!isset($body["email"]) || !is_string($body["email"])) {
    return err("Invalid email");
}
    if (!isset($body["name"]) || !is_string($body["name"])) {
    return err("Invalid name");
}

    return ok([
        "name" => $body["name"],
        "email" => $body["email"],
    ]);
}

use function Rustify\{if_some, if_ok};

$maybeToken = some("abc123");

if_some($maybeToken, function ($token) {
    error_log("Token = $token");
});

$result = ok(42);

if_ok($result, function ($v) {
    echo "Result: $v";
});


use function Rustify\{option_match, result_match};

$opt = none();

$msg = option_match(
    $opt,
    fn($v) => "Some: $v",
    fn()   => "None"
);

$res = err("bad input");

$message = result_match(
    $res,
    fn($v) => "OK: $v",
    fn($e) => "ERR: $e"
);


use Rustify\Result;
use function Rustify\{ok, err};

function doWork(): Result
{
    // ... return ok($value) or err($reason)
}

$res = doWork();

$res->ifErr(function ($e) {
    // $e can be a string, array, or an Exception/Throwable you put there
    error_log('[doWork] failed: ' . (is_string($e) ? $e : (is_object($e) ? $e->getMessage() : json_encode($e))));
});

// Continue with a default if needed
$value = $res->unwrapOr('default');

$res = doWork()
    ->mapErr(function ($e) {
        error_log('[doWork] error: ' . (is_string($e) ? $e : (is_object($e) ? $e->getMessage() : json_encode($e))));
        // Optionally normalize to a domain error type/value
        return is_string($e) ? $e : 'internal_error';
    });

use function Rustify\{ok};

$safe = doWork()
    ->orElse(function ($e) {
        error_log('[doWork] recovered: ' . (is_string($e) ? $e : (is_object($e) ? $e->getMessage() : json_encode($e))));
        return ok('fallback'); // provide a fallback Ok value
    })
    ->unwrap(); // safe because we've recovered

$value = doWork()->unwrapOrElse(function ($e) {
    error_log('[doWork] defaulted: ' . (is_string($e) ? $e : (is_object($e) ? $e->getMessage() : json_encode($e))));
    return 'default';
});

use Rustify\Result;
use function Rustify\{ok, err};

function parseJsonSafe(string $raw): Result
{
    try {
        $data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        return ok($data);
    } catch (\Throwable $e) {
        return err($e); // store the Throwable in Err
    }
}

$res = parseJsonSafe($input);
$data = $res->unwrapOrElse(function ($e) {
    // $e is the Throwable we stored
    error_log('[parseJsonSafe] ' . $e->getMessage());
    return [];
});

use function Rustify\{some, none};

/** @return Rustify\Option */
function maybeEnv(string $key)
{
    $v = getenv($key);
    return $v === false ? none() : some($v);
}

$opt = maybeEnv('API_TOKEN');
$opt->ifNone(fn() => error_log('[env] API_TOKEN is not set'));
$token = $opt->unwrapOr('');

function findUser(int $id) {
    if ($id === 1) return ['id'=>1, 'name'=>'James'];
    return null;
}

$user = findUser($id);
    if ($user === null) {
    // handle maybe-error maybe-not-error?
}

$total = $invoice['amount'] + $invoice['tax'];

return err("Invoice not found");

function maybeGetEmail(User $u): ?string

// vs

function maybeGetEmail(User $u): Option<string>

if ($result->isErr()) {
    return $result->unwrapErr();
}

return err("Invalid request");
return ok($user);

Option<User>
Result<User, Error>
bash
composer