1

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

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'它被认为是无效的

有没有办法简化这种方法?

4

1 回答 1

0

首先,尽量不要过度复杂化。在我看来,代码不够复杂,不足以证明使用面向对象的设计模式是合理的。

正如我所看到的,您的代码基本上归结为使用不同的正则表达式验证输入(这取决于一些用户指定的标志,如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;
}
于 2013-11-07T19:51:07.340 回答