First of all, try not to over-complicate this. In my opinion, the code is not complex enough to justify the use of object-oriented design patterns.
As I see it, your code basically boils down to validating an input with different regular expressions (which depend on some user-specified flags like allow_num
and allow_space
.
So my suggestion is the following (the basic refactoring is constructing part of the regular expression based on configuration before using this expression in any validation logic):
protected function isTextValid() {
$allowedCharacters = 'A-Za-z';
if ($this->data['allow_spaces']) {
$allowedCharacters .= '\s';
}
if ($this->data['allow_num']) {
$allowedCharacters .= '\d';
}
if (!preg_match("#^[{$allowedCharacters}]+\$#", $this->value)) {
$this->messages = foo ? foor : bar;
return false;
}
return true;
}