silasyudi/optional

Portability of Java's java.util.Optional<T> class to PHP.

v2.0.0 2022-05-14 19:17 UTC

This package is auto-updated.

Last update: 2024-05-15 00:33:28 UTC


README

Tests Maintainability Test Coverage

Portability of Java's java.util.Optional<T> class to PHP, updated with Java 11 features.

Summary

Language / Idioma

Leia a versão em português 🇧🇷 aqui.

Instalation

composer require silasyudi/optional

Requirements

  • PHP 7.4+
  • Composer

Features

The Optional class encapsulates a value and can perform various operations on it.

Example without Optional:

    /** @var Entity|null $entity */
    $entity = $this->repository->find($id);

    if (!$entity) {
        throw new SomeException();
    }

    ...

Example with Optional:

    /** @var SilasYudi\Optional $optional */
    $optional = $this->repository->find($id);
    $entity = $optional->orElseThrow(new SomeException());
    ...

Differences

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 in map, flatMap and filter.
  • Optional.hashCode() was not imported into this package.
  • NullPointerException e NoSuchElementException of the Java was replaced by OptionalInvalidStateException when the Optional object cannot be empty and TypeError when attempting to pass null in callable 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 or null as parameter.
  • Consumer, Function, Predicate and Supplier was imported as callable.