Skip to content

Commit

Permalink
Merge pull request #12 from petrknap/filter
Browse files Browse the repository at this point in the history
Implemented `filter` method
  • Loading branch information
petrknap authored May 19, 2024
2 parents 366e124 + 01aaae6 commit a94583f
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 a94583f

Please sign in to comment.