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
20 changes: 5 additions & 15 deletions src/Optional.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@
*/
abstract class Optional implements JavaSe8\Optional
{
private bool|null $wasPresent = null;

/**
* @param T|null $value
*/
Expand Down Expand Up @@ -168,11 +166,11 @@ public function flatMap(callable $mapper): JavaSe8\Optional
return $mapper($this->value);
}

/**
* @see self::orElseThrow() - more explicit alternative
*/
public function get(): mixed
{
if ($this->wasPresent === null) {
self::triggerNotice('Call `isPresent()` before accessing the value.');
}
return $this->orElseThrow();
}

Expand All @@ -190,7 +188,7 @@ public function ifPresent(callable $consumer, callable|null $else = null): void

public function isPresent(): bool
{
return $this->wasPresent = $this->value !== null;
return $this->value !== null;
}

/**
Expand Down Expand Up @@ -230,7 +228,7 @@ public function orElseGet(callable $otherSupplier): mixed
*
* @return T
*
* @throws E
* @throws ($exceptionSupplier is null ? Exception\CouldNotGetValueOfEmptyOptional : E)
*/
public function orElseThrow(
null|string|callable $exceptionSupplier = null,
Expand Down Expand Up @@ -263,12 +261,4 @@ public function orElseThrow(
throw new InvalidArgumentException('Exception supplier must return ' . Throwable::class . '.');
});
}

private static function triggerNotice(string $message): void
{
trigger_error(
$message,
error_level: E_USER_NOTICE,
);
}
}
11 changes: 11 additions & 0 deletions tests/JavaSe8/AlternativeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

declare(strict_types=1);

namespace PetrKnap\Optional\JavaSe8;

use RuntimeException;

final class AlternativeException extends RuntimeException
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

use PetrKnap\Shorts\Exception\NotImplemented;

final class AnotherOption implements Optional
final class AlternativeOption implements Optional
{
public static function empty(): self
{
Expand Down
28 changes: 19 additions & 9 deletions tests/JavaSe8/OptionalTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ private static void testEquals() {
// two records
assert (Optional.of(new Record()).equals(Optional.of(new Record())) == true);
// two empties
assert (Optional.<Integer>empty().equals(Optional.<Another>empty()) == true);
assert (Optional.<Integer>empty().equals(Optional.<Alternative>empty()) == true);
// wrong type
assert (Optional.of(1).equals(Optional.of("1")) == false);
}
Expand All @@ -43,24 +43,31 @@ private static void testFilter() {
}

private static void testFlatMap() {
Optional $anotherOption, $thisOption;
Optional $alternativeOption, $thisOption;
// present option returns mapped option
$anotherOption = Optional.<Another>empty(); assert (Optional.of(1).flatMap($v -> $anotherOption) == $anotherOption);
$alternativeOption = Optional.<Alternative>empty(); assert (Optional.of(1).flatMap($v -> $alternativeOption) == $alternativeOption);
// empty option returns itself
$thisOption = Optional.empty(); assert ($thisOption.flatMap($v -> Optional.of(new Another())) == $thisOption);
$thisOption = Optional.empty(); assert ($thisOption.flatMap($v -> Optional.of(new Alternative())) == $thisOption);
// empty option does not call mapper
Optional.empty().flatMap($v -> { assert (false); return Optional.<Another>empty(); });
Optional.empty().flatMap($v -> { assert (false); return Optional.<Alternative>empty(); });
}

private static void testGetters() {
// present option returns value
assert (Optional.of(1).get() == 1);
assert (Optional.of(1).orElse(2) == 1);
assert (Optional.of(1).orElseGet(() -> 2) == 1);
assert (Optional.of(1).orElseThrow() == 1);
// empty option returns fallback
assert (Optional.<Integer>empty().orElse(1) == 1);
assert (Optional.<Integer>empty().orElseGet(() -> 1) == 1);
assert (Optional.of(1).orElseThrow() == 1);
// empty option throws
try { Optional.empty().get(); } catch (NoSuchElementException $e) { assert (true); }
try { Optional.empty().orElseThrow(); } catch (NoSuchElementException $e) { assert (true); }
// to nullable
assert (Optional.of(1).orElse(null) == 1);
try { Optional.empty().orElseThrow(() -> new AlternativeException()); } catch (AlternativeException $e) { assert (true); }
// fallback can be null
assert (Optional.empty().orElse(null) == null);
assert (Optional.empty().orElseGet(() -> null) == null);
}

private static void testIfPresent() {
Expand Down Expand Up @@ -90,6 +97,9 @@ private static void testMap() {
private static record Record() {
}

private static class Another {
private static class Alternative {
}

private static class AlternativeException extends RuntimeException {
}
}
2 changes: 1 addition & 1 deletion tests/JavaSe8/OptionalTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@
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 23 lines. Can be up to 20 lines.
{
$javaLines = array_map(
trim(...),
Expand All @@ -29,10 +29,10 @@

$headers = 'namespace ' . __NAMESPACE__ . ';';
foreach ($javaLines as $javaLine) {
if (!str_starts_with($javaLine, '*') && str_contains($javaLine, 'assert (')) {

Check notice on line 32 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.<Another>' => 'AnotherOption::',
'Optional.<Alternative>' => 'AlternativeOption::',
'Optional.' => '\\' . static::getClassName() . '::',
'Record' => '\\' . stdClass::class,
'<Integer>' => '',
Expand All @@ -43,7 +43,7 @@
'$v -> ' => 'fn ($v) => ',
'() -> {' => 'function () { return ',
'() -> ' => 'fn () => ',
])];

Check notice on line 46 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
}
}
}
Expand Down
Loading