Kolejna prosta reguła – MinRule. Do dzieła!
Na czym stanęliśmy:
<?php
/*
$form_rules = [
'email' => ['required', 'email'],
'password' => ['required'],
'confirmPassword' => ['required', 'match:password'],
'name' => ['unique:people.name'],
'country' => ['in:USA,Poland'],
'age' => ['min:18']
];
*/
$form_data = [
'email' => 'john.doe@gmail.com',
'password' => md5('helloworld'),
'confirmPassword' => md5('helloworld'),
'name' => 'Janet',
'country' => 'USA',
'age' => 19
];
interface RuleInterface
{
public function validate(array $data, string $field, array $params): bool;
public function getMessage(array $data, string $field, array $params): string;
}
class RequiredRule implements RuleInterface
{
//(...)
}
class EmailRule implements RuleInterface
{
//(...)
}
class UrlRule implements RuleInterface
{
//(...)
}
class MatchRule implements RuleInterface
{
//(...)
}
class ConfigINI {
//(...)
}
class PDOConnection {
//(...)
}
class UniqueRule implements RuleInterface
{
//(...)
}
class InRule implements RuleInterface
{
//(...)
}
Jak zbierzemy projekt do kupy to będziemy korzystać z autoloadingu composera. Na razie jednak dopisujemy kolejną regułę:
class MinRule implements RuleInterface
{
public function validate(array $data, string $field, array $params): bool
{
if (empty($params[0])) {
throw new InvalidArgumentException("Minimum length not specified");
}
$length = (int) $params[0];
return $data[$field] >= $length;
}
public function getMessage(array $data, string $field, array $params): string
{
return "Must be at least {$params[0]}";
}
}
Teraz postaram się odtworzyć proces parsowania naszego schema z regułami:
$field = 'age';
$rule = new MinRule;
$params = array_slice(explode(":", "min:18"), 1);
$in = $rule->validate($form_data, $field, $params);
if(!$in){
echo $rule->getMessage($form_data, $field, $params);
}
Sprawdźmy, czy działa podając jakąś większą liczbę:
$field = 'age';
$rule = new MinRule;
$params = array_slice(explode(":", "min:28"), 1);
$in = $rule->validate($form_data, $field, $params);
if(!$in){
echo $rule->getMessage($form_data, $field, $params);
}
//Must be at least 28