Skip to content

Commit e54b379

Browse files
committed
Added clouser custom rules support
1 parent 6a05dd3 commit e54b379

File tree

2 files changed

+37
-5
lines changed

2 files changed

+37
-5
lines changed

src/Envalid.php

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,17 @@ public function validate( $data, $rules )
106106
}
107107

108108
$ruleClass = @$this->rules[ $ruleName ];
109-
$valid = $ruleClass->validate($field, $value, $parsed[ 'args' ]);
109+
if (is_callable($ruleClass)) {
110+
$ruleMessage = call_user_func_array($ruleClass, [
111+
$field,
112+
$value,
113+
$parsed[ 'args' ]
114+
]);
115+
116+
$valid = $ruleMessage === true;
117+
} else {
118+
$valid = $ruleClass->validate($field, $value, $parsed[ 'args' ]);
119+
}
110120

111121
if (!$ruleMessage) {
112122
$ruleMessage = str_replace(['{field}'], $this->labelize($field), $ruleClass->message());
@@ -197,11 +207,16 @@ public function getFields()
197207
* Register a new Rule to validator
198208
*
199209
* @param $id
200-
* @param RuleInterface $rule
210+
* @param callable|RuleInterface $rule
201211
* @return $this
212+
* @throws \Exception
202213
*/
203-
public function addRule( $id, RuleInterface $rule )
214+
public function addRule( $id, $rule )
204215
{
216+
if (!is_callable($rule) && !$rule instanceof RuleInterface) {
217+
throw new \Exception("Rule must be callable or an instance of " . RuleInterface::class);
218+
}
219+
205220
$this->rules[ $id ] = $rule;
206221
return $this;
207222
}

tests/ValidatorTest.php

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<?php namespace azi\Tests;
22

3+
use azi\Arguments;
4+
35
/**
46
* Tests for azi\Validator
57
* Class ValidatorTest
@@ -39,6 +41,23 @@ public function testItSendsMultipleErrorMessagesAtTheSameTime()
3941
$this->assertEquals('Email must be a valid email address', $errors->get('email')->last());
4042
}
4143

44+
public function testItAllowsCallableCustomRules()
45+
{
46+
$this->validator->addRule('one_to_ten', function ( $field, $value, Arguments $args ) {
47+
if ($value >= 1 && $value <= 10) {
48+
return true;
49+
}
50+
51+
return "{field} must be between 1-10";
52+
});
53+
54+
$this->validator->validate(['kid_age' => '5'], [
55+
'kid_age' => 'one_to_ten'
56+
]);
57+
58+
$this->assertTrue($this->validator->passed());
59+
}
60+
4261
public function testItValidatesRequiredFields()
4362
{
4463
$this->validator->validate(['name' => 'Azeem Hassni'], [
@@ -58,6 +77,4 @@ public function testItValidatesEmailFields()
5877
}
5978

6079

61-
62-
6380
}

0 commit comments

Comments
 (0)