Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .github/workflows/java-test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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
Expand Down
13 changes: 13 additions & 0 deletions phpdoc_check.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand All @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions src/JavaSe8/Optional.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
41 changes: 41 additions & 0 deletions src/JavaSe9/Optional.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

declare(strict_types=1);

namespace PetrKnap\Optional\JavaSe9;

use PetrKnap\Optional\JavaSe8;

/**
* A container object which may or may not contain a non-null value.
*
* @template-covariant T of mixed type of non-null value
*
* @see https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html
*
* @extends JavaSe8\Optional<T>
*
* @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<U>
*
* @param callable(): V $supplier
*
* @return V|Optional<U>
*/
public function or(callable $supplier): Optional;
}
29 changes: 27 additions & 2 deletions src/Optional.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@
/**
* @template-covariant T of mixed type of non-null value
*
* @implements JavaSe8\Optional<T>
* @implements JavaSe9\Optional<T>
*/
abstract class Optional implements JavaSe8\Optional
abstract class Optional implements JavaSe9\Optional
{
/**
* @param T|null $value
Expand Down Expand Up @@ -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;
Expand All @@ -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<U>
*
* @param callable(): V $supplier
*
* @return V|self<U>
*/
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);
Expand Down
13 changes: 13 additions & 0 deletions src/OptionalOverrides.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
/**
* @return self<T>
*/
public static function empty(): self

Check notice on line 21 in src/OptionalOverrides.php

View workflow job for this annotation

GitHub Actions / run

* [Useless overriding method] Possible useless method overriding detected
{
/** @var self<T> */
return parent::empty();
Expand All @@ -33,7 +33,7 @@
*
* @throws InvalidArgumentException
*/
public static function of(mixed $value): self

Check notice on line 36 in src/OptionalOverrides.php

View workflow job for this annotation

GitHub Actions / run

* [Useless overriding method] Possible useless method overriding detected
{
/** @var self<U> */
return parent::of($value);
Expand All @@ -50,7 +50,7 @@
*
* @throws InvalidArgumentException
*/
public static function ofFalsable(mixed $value): self

Check notice on line 53 in src/OptionalOverrides.php

View workflow job for this annotation

GitHub Actions / run

* [Useless overriding method] Possible useless method overriding detected
{
/** @var self<U> */
return parent::ofFalsable($value);
Expand All @@ -63,7 +63,7 @@
*
* @return self<U>
*/
public static function ofNullable(mixed $value): self

Check notice on line 66 in src/OptionalOverrides.php

View workflow job for this annotation

GitHub Actions / run

* [Useless overriding method] Possible useless method overriding detected
{
/** @var self<U> */
return parent::ofNullable($value);
Expand Down Expand Up @@ -119,4 +119,17 @@
{
return parent::map($callback);
}

/**
* @template U of mixed type of non-null value
* @template V of JavaSe9\Optional<U>
*
* @param callable(): V $supplier
*
* @return V|self<U>
*/
public function or(callable $supplier): JavaSe9\Optional
{
return parent::or($supplier);
}
}
1 change: 1 addition & 0 deletions tests/IdeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 16 additions & 6 deletions tests/JavaSe8/OptionalTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,14 @@
self::expectNotToPerformAssertions();
}

eval($assert);

Check notice on line 20 in tests/JavaSe8/OptionalTestCase.php

View workflow job for this annotation

GitHub Actions / run

* [Eval] Use of eval() is discouraged
}

final public static function dataMatchesJavaBehavior(): iterable

Check notice on line 23 in tests/JavaSe8/OptionalTestCase.php

View workflow job for this annotation

GitHub Actions / run

* [Return type hint] Method \PetrKnap\Optional\JavaSe8\OptionalTestCase::dataMatchesJavaBehavior() does not have @return annotation for its traversable return value. * [Function length] Your function is too long. Currently using 21 lines. Can be up to 20 lines.
{
$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 (')) {

Check notice on line 27 in tests/JavaSe8/OptionalTestCase.php

View workflow job for this annotation

GitHub Actions / run

* [Line length] Line exceeds 80 characters; contains 90 characters * [Space after not] Expected 1 space after NOT operator; 0 found
yield $javaLine => [$headers . strtr($javaLine, [
'assert (' => '\\' . self::class . '::assertTrue(',
'Optional.<Alternative>' => 'AlternativeOption::',
Expand All @@ -39,15 +34,30 @@
'.' => '->',
' == ' => ' === ',
' != ' => ' !== ',
'$v -> { }' => 'fn ($v) => null',
'$v -> {' => 'function ($v) { return ',
'$v -> ' => 'fn ($v) => ',
'() -> { }' => 'fn () => null',
'() -> {' => 'function () { return ',
'() -> ' => 'fn () => ',
])];

Check notice on line 43 in tests/JavaSe8/OptionalTestCase.php

View workflow job for this annotation

GitHub Actions / run

* [Array indent] Closing brace of array declaration must be on a new line
}
}
}

final protected static function loadJavaLines(string $path): array

Check notice on line 48 in tests/JavaSe8/OptionalTestCase.php

View workflow job for this annotation

GitHub Actions / run

* [Return type hint] Method \PetrKnap\Optional\JavaSe8\OptionalTestCase::loadJavaLines() does not have @return annotation for its traversable return value.
{
return array_map(
trim(...),
explode("\n", file_get_contents($path)),
);
}

protected static function getJavaLines(): array

Check notice on line 56 in tests/JavaSe8/OptionalTestCase.php

View workflow job for this annotation

GitHub Actions / run

* [Return type hint] Method \PetrKnap\Optional\JavaSe8\OptionalTestCase::getJavaLines() does not have @return annotation for its traversable return value.
{
return self::loadJavaLines(__DIR__ . '/OptionalTest.java');
}

/**
* @return class-string<Optional>
*/
Expand Down
34 changes: 34 additions & 0 deletions tests/JavaSe9/OptionalTest.java
Original file line number Diff line number Diff line change
@@ -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(); });
}
}
19 changes: 19 additions & 0 deletions tests/JavaSe9/OptionalTestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

namespace PetrKnap\Optional\JavaSe9;

use PetrKnap\Optional\JavaSe8;

abstract class OptionalTestCase extends JavaSe8\OptionalTestCase
{
#[\Override]
protected static function getJavaLines(): array
{
return array_merge(
parent::getJavaLines(),
self::loadJavaLines(__DIR__ . '/OptionalTest.java'),
);
}
}
3 changes: 1 addition & 2 deletions tests/OptionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
namespace PetrKnap\Optional;

use DomainException as SomeException;
use Override;

final class OptionalTest extends OptionalTestCase
{
Expand Down Expand Up @@ -57,7 +56,7 @@ public function testOrElseThrowsCustomException(): void
}
}

#[Override]
#[\Override]
public static function dataCustomFactoryWorks(): iterable
{
return [
Expand Down
2 changes: 1 addition & 1 deletion tests/OptionalTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;

abstract class OptionalTestCase extends JavaSe8\OptionalTestCase
abstract class OptionalTestCase extends JavaSe9\OptionalTestCase
{
final public static function dataOptions(): array
{
Expand Down
Loading