N°6414 Validator refactoring

New AbstractValidator class, with new method Validate
All existing validators are now children of AbstractRegexpValidator
Handle validators JS counterparts in renderers : only regexp validators are implemented client side
This commit is contained in:
Pierre Goiffon
2023-06-29 10:41:51 +02:00
parent 52049b7837
commit 6606af71ff
26 changed files with 348 additions and 247 deletions

View File

@@ -0,0 +1,56 @@
<?php
/*
* @copyright Copyright (C) 2010-2023 Combodo SARL
* @license http://opensource.org/licenses/AGPL-3.0
*/
namespace Combodo\iTop\Form\Validator;
/**
* @since 3.1.0 N°6414
*/
abstract class AbstractRegexpValidator extends AbstractValidator
{
public const VALIDATOR_NAME = 'abstract_regexp';
/** @var string Override in children classes to set regexp to use for validation */
public const DEFAULT_REGEXP = '';
protected string $sRegExp;
public function __construct(?string $sErrorMessage = null)
{
$this->sRegExp = static::DEFAULT_REGEXP;
parent::__construct($sErrorMessage);
}
public function Validate($value): array
{
if (is_null($value)) {
$value = ''; // calling preg_match with null as subject is deprecated since PHP 8.1
}
if (preg_match($this->GetRegExp(true), $value)) {
return [true, null];
}
return [false, $this->sErrorMessage];
}
/**
* Returns the regular expression of the validator.
*
* @param boolean $bWithSlashes If true, surrounds $sRegExp with '/'. Used with preg_match & co
*
* @return string
*/
public function GetRegExp($bWithSlashes = false)
{
if ($bWithSlashes) {
$sRet = '/'.str_replace('/', '\\/', $this->sRegExp).'/';
} else {
$sRet = $this->sRegExp;
}
return $sRet;
}
}