diff --git a/CHANGELOG.md b/CHANGELOG.md index ef1e3b9..848b5ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Added + +- `Innmind\IO\Frame::keep()` + ### Fixed - Taking over a socket address in a simulated environment (as it tried to delete a concrete file) diff --git a/documentation/frames.md b/documentation/frames.md index 9ba71db..b5c8235 100644 --- a/documentation/frames.md +++ b/documentation/frames.md @@ -117,6 +117,25 @@ $nonErroneousFrame = Frame::line()->filter( ); ``` +## `->keep()` + +This is similar to `->filter()` with the advantage of psalm understanding the type in the new `Frame`. + +```php +use Innmind\IO\Frame; +use Innmind\Immutable\{ + Str, + Predicate\Instance, +}; + +$nonEmptyLineFrame = Frame::line() + ->map(static fn($line) => match ($line->empty()) { + true => null, + false => $line, + }) + ->keep(Instance::of(Str::class)); +``` + ## `->map()` This method allows to transform the read data to any type you want. diff --git a/proofs/frames.php b/proofs/frames.php index 365d92b..066d192 100644 --- a/proofs/frames.php +++ b/proofs/frames.php @@ -12,6 +12,7 @@ Str, Maybe, Sequence, + Predicate, }; use Innmind\BlackBox\Set; @@ -202,6 +203,37 @@ static function($assert, $string) use ($reader) { }, ); + yield proof( + 'Frame::keep()', + given( + Set::strings() + ->unicode() + ->map(Str::of(...)) + ->map(static fn($string) => $string->toEncoding(Str\Encoding::ascii)), + ), + static function($assert, $string) use ($reader) { + $frame = Frame::chunk($string->length())->strict(); + + $assert->same( + $string->toString(), + $frame + ->keep(Predicate::of(static fn() => true))($reader($string)) + ->match( + static fn($value) => $value->toString(), + static fn() => null, + ), + ); + $assert->null( + $frame + ->keep(Predicate::of(static fn() => false))($reader($string)) + ->match( + static fn($value) => $value, + static fn() => null, + ), + ); + }, + ); + yield proof( 'Frame::buffer()', given( diff --git a/src/Frame.php b/src/Frame.php index 1371c04..8c8739f 100644 --- a/src/Frame.php +++ b/src/Frame.php @@ -16,6 +16,7 @@ Maybe, Attempt, Sequence as Seq, + Predicate, }; /** @@ -178,6 +179,21 @@ public function filter(callable $predicate): self )); } + /** + * @psalm-mutation-free + * @template U + * + * @param Predicate $predicate + * + * @return self + */ + #[\NoDiscard] + public function keep(Predicate $predicate): self + { + /** @var self */ + return $this->filter($predicate); + } + /** * @psalm-mutation-free *