Skip to content

Commit 8b3661a

Browse files
committed
Allow replace argument placeholders with data values
1 parent ba92b66 commit 8b3661a

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

src/Validation.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,7 @@ protected function validateField(string $field, array $rules, array $data) : boo
477477
}
478478
$status = true;
479479
foreach ($rules as $rule) {
480+
$rule['args'] = $this->replaceArgs($rule['args'], $data);
480481
$status = $this->validateRule($rule['rule'], $field, $rule['args'], $data);
481482
if ($status !== true) {
482483
$rule = $this->setEqualsField($rule);
@@ -487,6 +488,30 @@ protected function validateField(string $field, array $rules, array $data) : boo
487488
return $status;
488489
}
489490

491+
/**
492+
* Replace argument placeholders with data values.
493+
*
494+
* @param array<mixed> $args
495+
* @param array<string,mixed> $data
496+
*
497+
* @return array<mixed>
498+
*/
499+
protected function replaceArgs(array $args, array $data) : array
500+
{
501+
$result = [];
502+
foreach ($args as $arg) {
503+
if (\preg_match('#^{(\w+)}$#', $arg)) {
504+
$key = \substr($arg, 1, -1);
505+
if (isset($data[$key])) {
506+
$result[] = $data[$key];
507+
continue;
508+
}
509+
}
510+
$result[] = $arg;
511+
}
512+
return $result;
513+
}
514+
490515
/**
491516
* @param array<string,mixed> $rule
492517
*

tests/ValidationMock.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,11 @@ public function extractRules(string $rules) : array
2626
return parent::extractRules($rules);
2727
}
2828

29+
public function replaceArgs(array $args, array $data) : array
30+
{
31+
return parent::replaceArgs($args, $data);
32+
}
33+
2934
public function setError(string $field, string $rule, array $params) : static
3035
{
3136
return parent::setError($field, $rule, $params);

tests/ValidationTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,21 @@ public function testSetError() : void
381381
);
382382
}
383383

384+
public function testReplaceArgs() : void
385+
{
386+
$args = ['foo', 'bar', '{id}', '{x}', 'baz', '{email}'];
387+
$data = [
388+
'email' => 'me@domain.tld',
389+
'id' => 25,
390+
'bar' => 'Bar',
391+
'foo' => 'Foo',
392+
];
393+
self::assertSame(
394+
['foo', 'bar', 25, '{x}', 'baz', 'me@domain.tld'],
395+
$this->validation->replaceArgs($args, $data)
396+
);
397+
}
398+
384399
public function testValidate() : void
385400
{
386401
self::assertTrue($this->validation->validate([]));

0 commit comments

Comments
 (0)