Skip to content

Commit

Permalink
feat: implemented filter method
Browse files Browse the repository at this point in the history
  • Loading branch information
petrknap committed May 19, 2024
1 parent 50f5b81 commit 01aaae6
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/AbstractOptional.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,25 @@ public function equals(mixed $obj): bool
return ($obj === null || static::isSupported($obj)) && $this->value == $obj;
}

/**
* @param callable(T): bool $predicate
*
* @return static
*/
public function filter(callable $predicate): static
{
if ($this->value !== null) {
$matches = $predicate($this->value);
if (!is_bool($matches)) {
throw new InvalidArgumentException('Predicate must return boolean.');
}
if (!$matches) {
return static::empty();
}
}
return $this;
}

/**
* @template U of mixed
*
Expand Down
17 changes: 17 additions & 0 deletions tests/OptionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,23 @@ public static function dataMethodEqualsWorks(): array
];
}

#[DataProvider('dataMethodFilterWorks')]
public function testMethodFilterWorks(Optional $optional, bool $expected): void
{
self::assertEquals(
$expected ? $optional : Optional::empty(),
$optional->filter(static fn (string $value): bool => $value === self::VALUE),
);
}

public static function dataMethodFilterWorks(): array
{
return [
self::VALUE => [Optional::of(self::VALUE), true],
self::OTHER => [Optional::of(self::OTHER), false],
];
}

#[DataProvider('dataMethodFlatMapWorks')]
public function testMethodFlatMapWorks(Optional $optional, Optional $expectedResult): void
{
Expand Down

0 comments on commit 01aaae6

Please sign in to comment.