- var_dump: documentation ( source)
- mb_strlen: documentation ( source)
- trim: documentation ( source)
- get_object_vars: documentation ( source)
<?php
abstract class Constraint
{
public function __construct(array $options = null)
{
$defaultOptions = $this->getDefaultOptions();
foreach ($this as $option => $value) {
if (isset($defaultOptions[$option])) {
$this->{$option} = $defaultOptions[$option];
} else {
throw new Exception('Ошибочка');
}
}
if (null !== $options) {
$vars = get_object_vars($this);
foreach ($options as $option => $value) {
if (isset($vars[$option])) {
$this->{$option} = $value;
} else {
throw new Exception('Ошибочка 2');
}
}
}
}
abstract protected function getDefaultOptions(): array;
}
class Length extends Constraint
{
public $min = 1;
public $max;
public $minMessage;
public $maxMessage;
public function __construct(array $options = null)
{
parent::__construct($options);
}
protected function getDefaultOptions(): array
{
return [
'min' => 2,
'max' => 50,
'minMessage' => 'Значение меньше 2 символов',
'maxMessage' => 'Значение больше 50 символов'
];
}
}
interface ValidatorInterface
{
public function validate($value, Constraint $constraint): ?string;
}
class LengthValidator implements ValidatorInterface
{
public function validate($value, Constraint $constraint): ?string
{
if (!$constraint instanceof Length) {
throw new Exception();
}
$length = mb_strlen(trim($value));
if ($length < $constraint->min) {
return $constraint->minMessage;
} elseif ($length > $constraint->max) {
return $constraint->maxMessage;
}
return null;
}
}
$length = new Length([
'min' => 3,
'max' => 50
]);
$lengthValidator = new LengthValidator();
$result = $lengthValidator->validate('Ян', $length);
var_dump($result);