PHP code example of jimmyoak / optional

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

    

jimmyoak / optional example snippets


class Request
{
    private $date;
    // ... constructor and getter ...
}

$date = Optional::ofNullable($request->getDate())
    ->map(function ($dateString) {
        return DateTime::createFromFormat('Y-m-d', $dateString);
    })
    ->orElseGet(function () {
        return new \DateTime();
    });

echo $date->format('Y-m-d');

$request = new Request('1992-10-07');

$request = new Request(null);

$date = Optional::ofNullable($request->getDate())
    ->map(function ($dateString) {
        return DateTime::createFromFormat('Y-m-d', $dateString);
    })
    ->orElseThrow(new \Exception());

$request = new Request(null);

$findInMemory = function () {
    ...
    return Optional::ofNullable(...);
};

$findInDisc = function () {
    ...
    return Optional::ofNullable(...);
};

$findRemotely = function () {
    ...
    return Optional::ofNullable(...);
};

$optional = $findInMemory()
    ->or($findInDisc)
    ->or($findRemotely);

$findInMemory = function () {
    echo "Searching in memory...\n";
    return Optional::empty();
};

$findInDisc = function () {
    echo "Searching in disc...\n";
    return Optional::of("Awesome");
};

$findRemotely = function () {
    echo "Searching remotely...";
    return Optional::of("Not so awesome");
};

$findInMemory()
    ->or($findInDisc)
    ->or($findRemotely)
    ->ifPresent(function ($value) {
        echo $value;
    });

$request = new Request('1992-10-07');

$makeDateTime = function ($value) {
    return \DateTime::createFromFormat('Y-m-d', $value);
};

$beforeNow = function (\DateTime $date) {
    return $date->getTimestamp() > (new \DateTime())->getTimestamp();
};

$date = Optional::ofNullable($request->getDate())
    ->map($makeDateTime)
    ->filter($beforeNow)
    ->orElse(new \DateTime());

echo $date->format('Y-m-d');

Optional::ofNullable($request->getDate())
    ->ifPresent(function ($value) {
        echo "It's present: " . $value;
    });

Optional::ofNullable($request->getDate())
    ->ifPresentOrElse(function ($value) {
        echo "It's present: " . $value;
    }, function() {
        echo 'No value is present';
    });

Optional::of('something')->equals(Optional::of('something'));

Optional::of(5)->equals(Optional::of('something'));

Optional::empty()->equals(Optional::empty());

Optional::empty()->equals(Optional::of(5));

echo (string) Optional::of('something');

echo (string) Optional::empty();
text
Searching in memory...
Searching in disc...
Awesome