这是我拥有的一种方法的简化版本。
看起来仍然很复杂
这种精神错乱将如何重构?

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;
            }
        }
    }
}

我尝试使用状态模式进行重构,但无济于事,因为我对模式不太熟悉。
这就是我所做的,但很快就可以了。

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}
}

显然,这只是首先测试 if 分支,我如何也可以自动检查其他分支?
我非常确定我的方法有问题。
有没有办法修复此状态模式以测试所有状态 if 分支?

编辑
这种方法的作用是,它检查是否 $this->value 根据存储在中的配置属性中包含期望值 $this->data

例子 $this->data = array('allow_num'=>true), , 如果 $this->value='a1' 考虑有效的示例 $this->data = array('allow_num'=>false), , 如果 $this->value='a1' 认为这是无效的

有没有办法简化此方法?

有帮助吗?

解决方案

首先,尽量不要过分简单。我认为,代码不够复杂,无法证明使用面向对象的设计模式的使用是合理的。

如我所见,您的代码基本上归结为验证具有不同正则表达式的输入(这取决于某些用户指定的标志,例如 allow_numallow_space.

因此,我的建议是以下(基本重构是基于配置之前的正则表达式的一部分 使用 此表达在任何验证逻辑中):

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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top