PHP code example of brimmar / phpoption

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

    

brimmar / phpoption example snippets




namespace Brimmar\PhpOption\Interfaces;

/**
 * @template T
 */
interface Option
{
    // ... (methods will be documented below)
}


use Brimmar\PhpOption\Some;
use Brimmar\PhpOption\None;
use Brimmar\PhpOption\Interfaces\Option;

class UserProfile
{
    private $data = [];

    public function setField(string $field, $value): void
    {
        $this->data[$field] = $value;
    }

    public function getField(string $field): Option
    {
        return isset($this->data[$field]) ? new Some($this->data[$field]) : new None();
    }

    public function getDisplayName(): string
    {
        return $this->getField('display_name')
            ->orElse(fn() => $this->getField('username'))
            ->unwrapOr('Anonymous');
    }

    public function getAge(): Option
    {
        return $this->getField('age')
            ->andThen(function($age) {
                return is_numeric($age) && $age > 0 && $age < 120 ? new Some((int)$age) : new None();
            });
    }
}

$profile = new UserProfile();
$profile->setField('username', 'johndoe');
$profile->setField('age', '30');

echo $profile->getDisplayName(); // Output: johndoe

$age = $profile->getAge()
    ->map(fn($age) => "User is $age years old")
    ->unwrapOr("Age not provided or invalid");
echo $age; // Output: User is 30 years old

$email = $profile->getField('email')
    ->map(fn($email) => "Contact: $email")
    ->unwrapOr("No email provided");
echo $email; // Output: No email provided


use Brimmar\PhpOption\Some;
use Brimmar\PhpOption\None;
use Brimmar\PhpResult\Ok;
use Brimmar\PhpResult\Err;

class ConfigManager
{
    private $configs = [];

    public function getConfig(string $key): Option
    {
        return isset($this->configs[$key]) ? new Some($this->configs[$key]) : new None();
    }

    public function setConfig(string $key, $value): void
    {
        $this->configs[$key] = $value;
    }

    public function getRequiredConfig(string $key): Result
    {
        return $this->getConfig($key)
            ->ok()
            ->mapErr(fn() => "Required configuration '$key' is missing");
    }

    public function getDatabaseUrl(): Result
    {
        return $this->getRequiredConfig('database_url')
            ->andThen(function($url) {
                $parsed = parse_url($url);
                return isset($parsed['scheme'], $parsed['host'], $parsed['path'])
                    ? new Ok($url)
                    : new Err("Invalid database URL format");
            });
    }
}

$manager = new ConfigManager();
$manager->setConfig('database_url', 'mysql://localhost/mydb');
$manager->setConfig('debug', true);

$debugMode = $manager->getConfig('debug')
    ->unwrapOr(false);
echo $debugMode ? "Debug mode is ON" : "Debug mode is OFF"; // Output: Debug mode is ON

$databaseUrl = $manager->getDatabaseUrl()
    ->map(fn($url) => "Connected to: $url")
    ->unwrapOr("Failed to connect to database");
echo $databaseUrl; // Output: Connected to: mysql://localhost/mydb

$apiKey = $manager->getRequiredConfig('api_key')
    ->match(
        Ok: fn($key) => "API Key: $key",
        Err: fn($error) => "Error: $error",
    );
echo $apiKey; // Output: Error: Required configuration 'api_key' is missing


use Brimmar\PhpOption\Some;
use Brimmar\PhpOption\None;
use Brimmar\PhpOption\Interfaces\Option;

class Address
{
    public function __construct(public string $street, public string $city, public string $country) {}
}

class User
{
    public function __construct(public string $name, private ?Address $address = null) {}

    public function getAddress(): Option
    {
        return $this->address ? new Some($this->address) : new None();
    }
}

class UserRepository
{
    private $users = [];

    public function addUser(User $user): void
    {
        $this->users[] = $user;
    }

    public function findUserByName(string $name): Option
    {
        $user = array_values(array_filter($this->users, fn($u) => $u->name === $name))[0] ?? null;
        return $user ? new Some($user) : new None();
    }
}

$repo = new UserRepository();
$repo->addUser(new User("Alice", new Address("123 Main St", "Springfield", "USA")));
$repo->addUser(new User("Bob"));

function getUserCountry(UserRepository $repo, string $name): string
{
    return $repo->findUserByName($name)
        ->andThen(fn($user) => $user->getAddress())
        ->map(fn($address) => $address->country)
        ->unwrapOr("Country not found");
}

echo getUserCountry($repo, "Alice"); // Output: USA
echo getUserCountry($repo, "Bob");   // Output: Country not found
echo getUserCountry($repo, "Charlie"); // Output: Country not found

$option = new Some(42);
echo $option->isSome(); // true

$option = new None();
echo $option->isSome(); // false

$option = new Some(42);
echo $option->isSomeAnd(fn($value) => $value > 40); // true
echo $option->isSomeAnd(fn($value) => $value < 40); // false

$option = new None();
echo $option->isSomeAnd(fn($value) => $value > 0); // false

$option = new Some(42);
echo $option->isNone(); // false

$option = new None();
echo $option->isNone(); // true

$option = new Some(42);
foreach ($option->iter() as $value) {
    echo $value; // 42
}

$option = new None();
foreach ($option->iter() as $value) {
    // This block will never be executed
}

$option = new Some(42);
echo $option->unwrap(); // 42

$option = new None();
$option->unwrap(); // Throws RuntimeException

$option = new Some(42);
echo $option->expect("Value should be present"); // 42

$option = new None();
$option->expect("Value is 

$option = new Some(new Some(42));
$flattened = $option->flatten();
echo $flattened->unwrap(); // 42

$option = new Some(new None());
$flattened = $option->flatten();
echo $flattened->isNone(); // true

$option = new Some(42);
echo $option->unwrapOr(0); // 42

$option = new None();
echo $option->unwrapOr(0); // 0

$option = new Some(42);
echo $option->unwrapOrElse(fn() => 0); // 42

$option = new None();
echo $option->unwrapOrElse(fn() => 0); // 0

$option = new Some(42);
$mapped = $option->map(fn($x) => $x * 2);
echo $mapped->unwrap(); // 84

$option = new None();
$mapped = $option->map(fn($x) => $x * 2);
echo $mapped->isNone(); // true

$option = new Some(42);
echo $option->mapOr(0, fn($x) => $x * 2); // 84

$option = new None();
echo $option->mapOr(0, fn($x) => $x * 2); // 0

$option = new Some(42);
echo $option->mapOrElse(fn() => 0, fn($x) => $x * 2); // 84

$option = new None();
echo $option->mapOrElse(fn() => 0, fn($x) => $x * 2); // 0

$option = new Some(42);
$option->inspect(function($x) { echo "Got: $x"; }); // Outputs: Got: 42
echo $option->unwrap(); // 42

$option = new None();
$option->inspect(function($x) { echo "Got: $x"; }); // No output

$option = new Some(42);
$result = $option->okOr("No value");
echo $result->unwrap(); // 42

$option = new None();
$result = $option->okOr("No value");
echo $result->unwrapErr(); // "No value"

$option = new Some(42);
$result = $option->okOrElse(fn() => "No value");
echo $result->unwrap(); // 42

$option = new None();
$result = $option->okOrElse(fn() => "No value");
echo $result->unwrapErr(); // "No value"

$option1 = new Some(42);
$option2 = new Some(10);
$result = $option1->and($option2);
echo $result->unwrap(); // 10

$option1 = new None();
$option2 = new Some(10);
$result = $option1->and($option2);
echo $result->isNone(); // true

$option = new Some(42);
$result = $option->andThen(fn($x) => new Some($x * 2));
echo $result->unwrap(); // 84

$option = new None();
$result = $option->andThen(fn($x) => new Some($x * 2));
echo $result->isNone(); // true

$option1 = new Some(42);
$option2 = new Some(10);
$result = $option1->or($option2);
echo $result->unwrap(); // 42

$option1 = new None();
$option2 = new Some(10);
$result = $option1->or($option2);
echo $result->unwrap(); // 10

$option = new Some(42);
$result = $option->orElse(fn() => new Some(10));
echo $result->unwrap(); // 42

$option = new None();
$result = $option->orElse(fn() => new Some(10));
echo $result->unwrap(); // 10

$option = new Some(new Ok(42));
$result = $option->transpose();
echo $result->unwrap()->unwrap(); // 42

$option = new Some(new Err("error"));
$result = $option->transpose();
echo $result->unwrapErr(); // "error"

$option = new None();
$result = $option->transpose();
echo $result->unwrap()->isNone(); // true

$option1 = new Some(42);
$option2 = new None();
$result = $option1->xor($option2);
echo $result->unwrap(); // 42

$option1 = new Some(42);
$option2 = new Some(10);
$result = $option1->xor($option2);
echo $result->isNone(); // true

$option1 = new Some(42);
$option2 = new Some("hello");
$result = $option1->zip($option2);
print_r($result->unwrap()); // [42, "hello"]

$option1 = new Some(42);
$option2 = new None();
$result = $option1->zip($option2);
echo $result->isNone(); // true

$option1 = new Some(42);
$option2 = new Some(10);
$result = $option1->zipWith($option2, fn($a, $b) => $a + $b);
echo $result->unwrap(); // 52

$option1 = new Some(42);
$option2 = new None();
$result = $option1->zipWith($option2, fn($a, $b) => $a + $b);
echo $result->isNone(); // true

$option = new Some([42, "hello"]);
[$a, $b] = $option->unzip();
echo $a->unwrap(); // 42
echo $b->unwrap(); // "hello"

$option = new None();
[$a, $b] = $option->unzip();
echo $a->isNone(); // true
echo $b->isNone(); // true

$option = new Some(42);
$result = $option->match(
    Some: fn($x) => "Value is $x",
    None: fn() => "No value"
);
echo $result; // "Value is 42"

$option = new None();
$result = $option->match(
    Some: fn($x) => "Value is $x",
    None: fn() => "No value"
);
echo $result; // "No value"

$option = new Some(42);
$result = $option->filter(fn($x) => $x > 40);
echo $result->unwrap(); // 42

$option = new Some(42);
$result = $option->filter(fn($x) => $x < 40);
echo $result->isNone(); // true

$option = new None();
$result = $option->filter(fn($x) => $x > 0);
echo $result->isNone(); // true