Hier ist eine vereinfachte Version einer Methode, die ich habe.
Sieht immer noch sehr komplex aus
Wie würde man diesen Wahnsinn refaktor?
protected function isTextValid()
{
if( $this->data['allow_num'] ){
if( $this->data['allow_space'] ){
if( preg_match( '#^[a-zA-Z0-9\s]$#', $this->val ) ){
return true;
}
else{
$this->messages = foo ? foo : bar;
return false;
}
}
else{
if( preg_match( '#^[a-zA-Z0-9]$#', $this->val ) ){
return true;
}
else{
$this->messages = foo? foor : bar;
return false;
}
}
}
else{
if( $this->data['allow_space'] ){
if( preg_match( '#^[a-zA-Z\s]$#', $this->val ) ){
return true;
}
else{
$this->messages = foo ? foor : bar;
return false;
}
}
else{
if( preg_match( '#^[a-zA-Z]$#', $this->val ) ){
return true;
}
else{
$this->messages = foo ? foo: bar;
return false;
}
}
}
}
Ich versuche es mit dem Statusmuster zu refaktor, aber bis zum Vergeben, da ich mit dem Muster nicht ganz vertraut bin.
Das habe ich getan, aber schnell abondon.
interface ValidatorState{
public function isValid();
}
class AllowNumberAndSpace implement ValidatorState{
protected $context;
public function __construct(Context $context){$this->context = $context}
public function isValid(){
if( preg_match( .. ) ){
return true;
}
else{
$this->messages = foo ? foo : bar;
return false;
}
$this->context->setState(OtherState);
}
}
Class Context{
protected $state;
protected $allow_num_space_state;
public function __construct(){
$this->allow_num_space_state = new AllowNumberAndSpace($this);
$this->state = $this->allow_num_space_state;
}
public function isValid(){
return $this->state->isValid();
}
public function setState($state){$this->state = $state}
}
Offensichtlich dieser Test nur zuerst if
Zweig, wie kann ich auch andere Filiale automatisch überprüfen?
Ich bin mir ziemlich sicher, dass mit meinem Ansatz etwas nicht stimmt.
Gibt es eine Möglichkeit, dieses Statusmuster für alle zu testen? if
Zweig?
Bearbeitet
Was diese Methode tut, ist, ob sie überprüft, ob $this->value
enthalten den erwarteten Wert basierend auf Konfigurationsattribut, das in gespeicherter in gespeicherter in gespeicherter in gespeichertem Wert ist $this->data
Beispiel $this->data = array('allow_num'=>true)
, wenn $this->value='a1'
Es wird als gültiges Beispiel betrachtet $this->data = array('allow_num'=>false)
, wenn $this->value='a1'
Es wird als ungültig berücksichtigt
Gibt es eine Möglichkeit, diese Methode zu vereinfachen?