PHP code example of jjware / option

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

    

jjware / option example snippets


$opt = Option::some('example value');

$opt = Option::nullable($value);

$opt = Option::none();

function getSetting(string $setting) : Option
{
    // Try to find the setting if it exists...
    return Option::nullable($result);
}

$port = getSetting('port')->getOrElse(8080);

$port = getSetting('port')->getOrElseGet(function () use ($db) {
    return $db->getDefaultPortFromDatabase();
});

// or using an instance method reference

$port = getSetting('port')->getOrElseGet([$db, 'getDefaultPortFromDatabase']);

$port = getSetting('port')->getOrThrow(function () {
   return new UnderflowException("setting does not exist");
});

$port = getSetting('port')->map(function ($x) {
   return intval($x);
})->getOrElse(8080);

// or using a function reference

$port = getSetting('port')->map('intval')->getOrElse(8080);

$scheme = getSetting('port')->flatMap(function ($x) {
   return getSchemeForPort($x);
})->getOrElse('http');

// or as a function reference

$scheme = getSetting('port')->flatMap('getSchemeForPort')->getOrElse('http');

$port = getSetting('port')->filter(function ($x) {
    return $x >= 1024 && $x <= 49151;
})->getOrElse(8080);

// or using a static method reference

$port = getSetting('port')->filter('Filters::registeredPort')->getOrElse(8080);

$port = getSetting('port');

if (!$port->isSome()) {
    $log->debug("port setting empty");
    throw new InvalidArgumentException("port not provided");
}