Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit f94f645

Browse files
committed
feat: allow values that implements Traversable and added the parameter name to messages
1 parent a6aeb6f commit f94f645

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

src/Rule/Collection.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,16 @@ public function assert(mixed $value, ?string $name = null): void
4040
throw new UnexpectedValueException($exception->getMessage());
4141
}
4242

43-
if (!\is_array($value)) {
44-
throw new UnexpectedTypeException('array', get_debug_type($value));
43+
if (!\is_iterable($value)) {
44+
throw new UnexpectedTypeException('array|\Traversable', get_debug_type($value));
4545
}
4646

4747
foreach ($this->fields as $field => $validator) {
4848
if (!isset($value[$field])) {
4949
throw new CollectionException(
5050
message: $this->missingFieldsMessage,
5151
parameters: [
52+
'name' => $name,
5253
'field' => $field
5354
]
5455
);
@@ -61,6 +62,7 @@ public function assert(mixed $value, ?string $name = null): void
6162
throw new CollectionException(
6263
message: $this->message,
6364
parameters: [
65+
'name' => $name,
6466
'field' => $field,
6567
'message' => $exception->getMessage()
6668
]
@@ -74,6 +76,7 @@ public function assert(mixed $value, ?string $name = null): void
7476
throw new CollectionException(
7577
message: $this->extraFieldsMessage,
7678
parameters: [
79+
'name' => $name,
7780
'field' => $field
7881
]
7982
);

tests/CollectionTest.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ class CollectionTest extends AbstractTest
2020
public static function provideRuleUnexpectedValueData(): \Generator
2121
{
2222
$unexpectedFieldValueMessage = '/At field (.*)\: (.*)\./';
23-
$unexpectedTypeMessage = '/Expected value of type "array", "(.*)" given\./';
23+
$unexpectedTypeMessage = '/Expected value of type "array\|\\\Traversable", "(.*)" given\./';
2424

2525
yield 'invalid field value' => [
2626
new Collection(fields: ['field' => 'invalid']),
@@ -67,10 +67,14 @@ public static function provideRuleFailureConditionData(): \Generator
6767

6868
public static function provideRuleSuccessConditionData(): \Generator
6969
{
70-
yield 'field' => [
70+
yield 'array' => [
7171
new Collection(fields: ['field' => Validator::notBlank()]),
7272
['field' => 'value'],
7373
];
74+
yield 'traversable' => [
75+
new Collection(fields: ['field' => Validator::notBlank()]),
76+
new \ArrayIterator(['field' => 'value'])
77+
];
7478
yield 'extra fields' => [
7579
new Collection(
7680
fields: ['field' => Validator::notBlank()],

0 commit comments

Comments
 (0)