Skip to content

Commit

Permalink
add shortcut to specify the constraint of each element of a list
Browse files Browse the repository at this point in the history
  • Loading branch information
Baptouuuu committed Mar 24, 2024
1 parent f6cc250 commit 705bc63
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## [Unreleased]

### Added

- `Is::list()->and(Each::of(Constraint))` has been shortened to `Is::list(Constraint)`

### Changed

- `Is::array()->and(Is::list())` has been shortened to `Is::list()`
Expand Down
39 changes: 39 additions & 0 deletions proofs/is.php
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,45 @@ static function($assert, $array, $other) {
},
);

yield proof(
'Is::list() with inner type',
given(
Set\Sequence::of(
Set\Strings::any(),
)->atLeast(1),
Set\Sequence::of(
Set\Integers::any(),
)->atLeast(1),
),
static function($assert, $strings, $ints) {
$assert->true(
Is::list(Is::string())->asPredicate()($strings),
);
$assert->same(
$strings,
Is::list(Is::string())($strings)->match(
static fn($value) => $value,
static fn() => null,
),
);
$assert->false(
Is::list(Is::string())->asPredicate()($ints),
);
$assert->same(
[['$', 'Value is not of type string']],
Is::list(Is::string())($ints)->match(
static fn() => null,
static fn($failures) => $failures
->map(static fn($failure) => [
$failure->path()->toString(),
$failure->message(),
])
->toList(),
),
);
},
);

yield proof(
'Is::shape()',
given(
Expand Down
17 changes: 13 additions & 4 deletions src/Is.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,23 @@ public static function null(): self
/**
* @psalm-pure
*
* @return Constraint<mixed, list>
* @template E
*
* @param Constraint<mixed, E> $each
*
* @return Constraint<mixed, list<E>>
*/
public static function list(): Constraint
public static function list(Constraint $each = null): Constraint
{
/** @var self<array, list> */
/** @var self<array, list<mixed>> */
$list = new self(\array_is_list(...), 'list');

return self::array()->and($list);
$constraint = self::array()->and($list);

return match ($each) {
null => $constraint,
default => $constraint->and(Each::of($each)),
};
}

/**
Expand Down

0 comments on commit 705bc63

Please sign in to comment.