Portability of Java's java.util.Optional<T>
class to PHP, updated with Java 11 features.
Leia a versão em português 🇧🇷 aqui.
composer require silasyudi/optional
- PHP 7.4+
- Composer
The Optional class encapsulates a value and can perform various operations on it.
/** @var Entity|null $entity */
$entity = $this->repository->find($id);
if (!$entity) {
throw new SomeException();
}
...
/** @var SilasYudi\Optional $optional */
$optional = $this->repository->find($id);
$entity = $optional->orElseThrow(new SomeException());
...
Some differences could not be avoided due to the particularities of each language. The most important are listed below:
Optional.stream()
of the Java was not imported into this package, as it doesn't have something similar in PHP and already has similar methods inmap
,flatMap
andfilter
.Optional.hashCode()
was not imported into this package.NullPointerException
eNoSuchElementException
of the Java was replaced byOptionalInvalidStateException
when the Optional object cannot be empty andTypeError
when attempting to pass null incallable
parameters.Optional.orElseThrow
in Java 11 is overloaded, and expects no parameter or a Supplier parameter. In this package, this method expects a Throwable object ornull
as parameter.Consumer
,Function
,Predicate
andSupplier
was imported ascallable
.