keerill/php-java-optional

Full implementation of Java8 Optional for PHP

v1.0.2 2023-12-13 13:33 UTC

This package is auto-updated.

Last update: 2024-10-13 15:39:44 UTC


README

Full implementation of JAVA8 Optional for PHP

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Usage

// ofEmpty refers Optional#empty() in java
// It is renamed as ofEmpty() because of empty() is reserved by PHP 
Optional::ofEmpty()
    ->isPresent(); // false

Optional::of('value')
    ->orElse('elseValue'); // value
 
Optional::ofEmpty()
    ->orElseThrow(fn () => new InvalidArgumentException()); // throws exception

Optional::ofEmpty()
    ->filter(fn ($a) => (int) $a); // function is not executed

Optional::of(5)
    ->map(fn ($a) => $a * 2)
    ->get(); // returns 10

Optional::ofEmpty()
    ->orElseGet(fn () => 10); // returns 10

Installation

composer require keerill/php-java-optional

Resources

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Credits

License

The MIT License (MIT). Please see License File for more information.