From 4002efb6f0b37ae109f9fa4ca3418d280f040cf1 Mon Sep 17 00:00:00 2001 From: Petr Knap <8299754+petrknap@users.noreply.github.com> Date: Wed, 28 Oct 2026 17:12:21 +0100 Subject: [PATCH] feat: implemented `JavaSe9\Optional` --- .github/workflows/java-test.yaml | 9 +++++-- README.md | 9 ++++--- phpdoc_check.php | 13 ++++++++++ src/JavaSe8/Optional.php | 2 ++ src/JavaSe9/Optional.php | 41 ++++++++++++++++++++++++++++++ src/Optional.php | 29 +++++++++++++++++++-- src/OptionalOverrides.php | 13 ++++++++++ tests/IdeTest.php | 1 + tests/JavaSe8/OptionalTestCase.php | 22 +++++++++++----- tests/JavaSe9/OptionalTest.java | 34 +++++++++++++++++++++++++ tests/JavaSe9/OptionalTestCase.php | 19 ++++++++++++++ tests/OptionalTest.php | 3 +-- tests/OptionalTestCase.php | 2 +- 13 files changed, 181 insertions(+), 16 deletions(-) create mode 100644 src/JavaSe9/Optional.php create mode 100644 tests/JavaSe9/OptionalTest.java create mode 100644 tests/JavaSe9/OptionalTestCase.php diff --git a/.github/workflows/java-test.yaml b/.github/workflows/java-test.yaml index 7a3867f..b7ec361 100644 --- a/.github/workflows/java-test.yaml +++ b/.github/workflows/java-test.yaml @@ -8,11 +8,16 @@ on: jobs: java-test: runs-on: ubuntu-latest + strategy: + matrix: + directory: + - tests/JavaSe8 + - tests/JavaSe9 steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: java-version: 21 distribution: corretto - - run: javac tests/JavaSe8/OptionalTest.java - - run: java -cp tests/JavaSe8 OptionalTest + - run: javac ${{ matrix.directory }}/OptionalTest.java + - run: java -cp ${{ matrix.directory }} OptionalTest diff --git a/README.md b/README.md index 7f129cd..603a1ab 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# Optional (like in Java Platform SE 8 but in PHP) +# Optional (like in Java Platform SE 8/9 but in PHP) It is an easy way to make sure that everyone has to check if they have (not) received a value. @@ -12,8 +12,11 @@ It is an easy way to make sure that everyone has to check if they have (not) rec > [Optional (Java Platform SE 8)](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html) This library delivers complete and reliable behavior of the `Optional`. -The entire feature set is [explicitly described and checked by an `OptionalTest.java`](./tests/JavaSe8/OptionalTest.java). -This ensures **absolute reliability and alignment with the Java specification**. +The **entire feature set is explicitly described and checked** by: +- [`JavaSe8/OptionalTest.java`](./tests/JavaSe8/OptionalTest.java) +- [`JavaSe9/OptionalTest.java`](./tests/JavaSe9/OptionalTest.java) + +This ensures absolute reliability and alignment with the Java specification. ## Basic usage diff --git a/phpdoc_check.php b/phpdoc_check.php index aacd8f9..1ad94c3 100644 --- a/phpdoc_check.php +++ b/phpdoc_check.php @@ -113,6 +113,13 @@ public function rawInputs(int $int = 0, string $string = ''): void {} $abstract->ifPresent(static fn (string $value): string => $value); // @phpstan-ignore argument.type $concrete->ifPresent(static fn (int $value): int => $value); $concrete->ifPresent(static fn (string $value): string => $value); // @phpstan-ignore argument.type +// - ifPresentOrElse +$abstract->ifPresentOrElse(static fn (int $value): int => $value, static fn () => null); +$abstract->ifPresentOrElse(static fn (string $value): string => $value, static fn () => null); // @phpstan-ignore argument.type +$abstract->ifPresentOrElse(static fn (int $value): int => $value, static fn (int $value): int => $value); // @phpstan-ignore argument.type +$concrete->ifPresentOrElse(static fn (int $value): int => $value, static fn () => null); +$concrete->ifPresentOrElse(static fn (string $value): string => $value, static fn () => null); // @phpstan-ignore argument.type +$concrete->ifPresentOrElse(static fn (int $value): int => $value, static fn (int $value): int => $value); // @phpstan-ignore argument.type // - map $abstractMapped = $abstract->map(static fn (int $value): string => ''); $abstract->map(static fn (string $value): int => 1); // @phpstan-ignore argument.type @@ -134,6 +141,9 @@ public function rawInputs(int $int = 0, string $string = ''): void {} // Check it // - abstract $check->genericInputOptions(abstract: $abstract); // @phpstan-ignore argument.type +$check->genericInputOptions(abstract: $abstractMapped); +$check->genericInputOptions(abstract: Optional::of('A')->or(static fn (): Optional => Optional::of('B'))); +$check->genericInputOptions(abstract: Optional::of('A')->or(static fn (): Optional => Optional::of(1))); // @phpstan-ignore argument.type $check->rawInputs(int: $abstract->get()); $check->rawInputs(int: $abstractOrElse); $check->rawInputs(int: $abstractOrElseGet); @@ -143,6 +153,9 @@ public function rawInputs(int $int = 0, string $string = ''): void {} $check->rawInputs(string: $abstractFlatMapped->orElseThrow()); // - concrete $check->genericInputOptions(concrete: $concrete); // @phpstan-ignore argument.type +$check->genericInputOptions(concrete: $concreteMapped); +$check->genericInputOptions(concrete: Some\Optional::of('A')->or(static fn (): Some\Optional => Some\Optional::of('B'))); +$check->genericInputOptions(concrete: Some\Optional::of('A')->or(static fn (): Some\Optional => Some\Optional::of(1))); // @phpstan-ignore argument.type $check->rawInputs(int: $concrete->get()); $check->rawInputs(int: $concreteOrElse); $check->rawInputs(int: $concreteOrElseGet); diff --git a/src/JavaSe8/Optional.php b/src/JavaSe8/Optional.php index d6ce153..2eca01e 100644 --- a/src/JavaSe8/Optional.php +++ b/src/JavaSe8/Optional.php @@ -12,6 +12,8 @@ * @template-covariant T of mixed type of non-null value * * @see https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html + * + * @note This interface does not define `hashCode()`. */ interface Optional { diff --git a/src/JavaSe9/Optional.php b/src/JavaSe9/Optional.php new file mode 100644 index 0000000..42753d6 --- /dev/null +++ b/src/JavaSe9/Optional.php @@ -0,0 +1,41 @@ + + * + * @note This interface does not define `stream()`. + */ +interface Optional extends JavaSe8\Optional +{ + /** + * If a value is present, performs the given action with the value, otherwise performs the given empty-based action. + * + * @param callable(T): mixed $action + * @param callable(): mixed $emptyAction + */ + public function ifPresentOrElse(callable $action, callable $emptyAction): void; + + /** + * If a value is present, returns an {@see Optional} describing the value, otherwise returns an {@see Optional} produced by the supplying function. + * + * @template U of mixed type of non-null value + * @template V of Optional + * + * @param callable(): V $supplier + * + * @return V|Optional + */ + public function or(callable $supplier): Optional; +} diff --git a/src/Optional.php b/src/Optional.php index c07ee06..095df2e 100644 --- a/src/Optional.php +++ b/src/Optional.php @@ -10,9 +10,9 @@ /** * @template-covariant T of mixed type of non-null value * - * @implements JavaSe8\Optional + * @implements JavaSe9\Optional */ -abstract class Optional implements JavaSe8\Optional +abstract class Optional implements JavaSe9\Optional { /** * @param T|null $value @@ -186,6 +186,14 @@ public function ifPresent(callable $consumer, callable|null $else = null): void } } + /** + * @see self::ifPresent() - shorter alternative + */ + public function ifPresentOrElse(callable $action, callable $emptyAction): void + { + $this->ifPresent($action, else: $emptyAction); + } + public function isPresent(): bool { return $this->value !== null; @@ -207,6 +215,23 @@ public function map(callable $mapper): self return static::ofNullable($mapper($this->value)); // @phpstan-ignore argument.type, argument.templateType } + /** + * @template U of mixed type of non-null value + * @template V of JavaSe9\Optional + * + * @param callable(): V $supplier + * + * @return V|self + */ + public function or(callable $supplier): JavaSe9\Optional + { + if ($this->value !== null) { + return $this; + } + + return $supplier(); + } + public function orElse(mixed $other): mixed { return $this->orElseGet(static fn (): mixed => $other); diff --git a/src/OptionalOverrides.php b/src/OptionalOverrides.php index ae6d0c3..62326d1 100644 --- a/src/OptionalOverrides.php +++ b/src/OptionalOverrides.php @@ -119,4 +119,17 @@ public function map(callable $callback): self { return parent::map($callback); } + + /** + * @template U of mixed type of non-null value + * @template V of JavaSe9\Optional + * + * @param callable(): V $supplier + * + * @return V|self + */ + public function or(callable $supplier): JavaSe9\Optional + { + return parent::or($supplier); + } } diff --git a/tests/IdeTest.php b/tests/IdeTest.php index c349275..862019e 100644 --- a/tests/IdeTest.php +++ b/tests/IdeTest.php @@ -22,6 +22,7 @@ public function testCheckThisInYourIde(): void $option->get()->tryIt(); # <--- HERE } + Optional::empty()->or(static fn (): Optional => $option)->get()->tryIt(); # <--- HERE Optional::empty()->orElse($instance)->tryIt(); # <--- HERE Optional::empty()->orElseGet(static fn (): Some\DataObject => $instance)->tryIt(); # <--- HERE $option->orElseThrow()->tryIt(); # <--- HERE diff --git a/tests/JavaSe8/OptionalTestCase.php b/tests/JavaSe8/OptionalTestCase.php index 6862c85..600a171 100644 --- a/tests/JavaSe8/OptionalTestCase.php +++ b/tests/JavaSe8/OptionalTestCase.php @@ -22,13 +22,8 @@ final public function testMatchesJavaBehavior(string $assert): void final public static function dataMatchesJavaBehavior(): iterable { - $javaLines = array_map( - trim(...), - explode("\n", file_get_contents(__DIR__ . '/OptionalTest.java')), - ); - $headers = 'namespace ' . __NAMESPACE__ . ';'; - foreach ($javaLines as $javaLine) { + foreach (static::getJavaLines() as $javaLine) { if (!str_starts_with($javaLine, '*') && str_contains($javaLine, 'assert (')) { yield $javaLine => [$headers . strtr($javaLine, [ 'assert (' => '\\' . self::class . '::assertTrue(', @@ -39,8 +34,10 @@ final public static function dataMatchesJavaBehavior(): iterable '.' => '->', ' == ' => ' === ', ' != ' => ' !== ', + '$v -> { }' => 'fn ($v) => null', '$v -> {' => 'function ($v) { return ', '$v -> ' => 'fn ($v) => ', + '() -> { }' => 'fn () => null', '() -> {' => 'function () { return ', '() -> ' => 'fn () => ', ])]; @@ -48,6 +45,19 @@ final public static function dataMatchesJavaBehavior(): iterable } } + final protected static function loadJavaLines(string $path): array + { + return array_map( + trim(...), + explode("\n", file_get_contents($path)), + ); + } + + protected static function getJavaLines(): array + { + return self::loadJavaLines(__DIR__ . '/OptionalTest.java'); + } + /** * @return class-string */ diff --git a/tests/JavaSe9/OptionalTest.java b/tests/JavaSe9/OptionalTest.java new file mode 100644 index 0000000..43565ae --- /dev/null +++ b/tests/JavaSe9/OptionalTest.java @@ -0,0 +1,34 @@ +import java.util.NoSuchElementException; +import java.util.Optional; + +/** + * @note `assert`s are written as `assert (...)` to simplify translate to PHP + * @note variable names are prefixed by `$` to simplify translate to PHP + */ +public class OptionalTest { + public static void main(String[] args) { + testIfPresentOrElse(); + testOr(); + } + + private static void testIfPresentOrElse() { + // present option calls action with value + Optional.of(1).ifPresentOrElse($v -> { assert ($v == 1); }, () -> { }); + // empty option calls empty action + Optional.empty().ifPresentOrElse($v -> { }, () -> { assert (true); }); + // present option does not call empty action + Optional.of(1).ifPresentOrElse($v -> { }, () -> { assert (false); }); + // empty option does not call action + Optional.empty().ifPresentOrElse($v -> { assert (false); }, () -> { }); + } + + private static void testOr() { + Optional $suppliedOption, $thisOption; + // present option returns itself + $thisOption = Optional.of(1); assert ($thisOption.or(() -> Optional.empty()) == $thisOption); + // empty option returns supplied option + $suppliedOption = Optional.empty(); assert (Optional.empty().or(() -> $suppliedOption) == $suppliedOption); + // present option does not call supplier + Optional.of(1).or(() -> { assert (false); return Optional.empty(); }); + } +} diff --git a/tests/JavaSe9/OptionalTestCase.php b/tests/JavaSe9/OptionalTestCase.php new file mode 100644 index 0000000..5102838 --- /dev/null +++ b/tests/JavaSe9/OptionalTestCase.php @@ -0,0 +1,19 @@ +