条件打印调试工具类

心随所遇 / 2023-06-30 / 原文

有时候用不了 debug,还是打印输出更直白些,定义了一个工具类,可方便调试代码。

用法大概如图:

 

 

class debugif {

    protected $conditions = [];

    protected $values = ['the $conditions is true!'];

    public function __construct($value1 = true, $value2 = true)
    {
        if(func_num_args() == 1){
            $this->if($value1);
        }else{
            $this->eq($value1, $value2);
        }

    }

    public function if(bool $condition = true)
    {
        $this->conditions[] = $condition;
        return $this;
    }


    public function eq($value1 = true, $value2 = true)
    {
        $this->if($value1 == $value2);
        return $this;
    }

    public function equal($value1 = true, $value2 = true)
    {
        $this->if($value1 == $value2); //绝对等于
        return $this;
    }

    public function empty($value = false)
    {
        $this->if(empty($value));
        return $this;
    }

    public function full($value = true)
    {
        $this->if(!empty($value));
        return $this;
    }

    public function true($value = true)
    {
        $this->if(boolval($value));
        return $this;
    }

    public function false($value = false)
    {
        $this->if(!boolval($value));
        return $this;
    }


    protected function conditionsIsTrue()
    {
        return count($this->conditions) == count(array_filter($this->conditions));
    }

    public function call($callback)
    {
        if($this->conditionsIsTrue()){
            $callback();
        }
        return $this;
    }

    public function dump(...$values)
    {
        if($this->conditionsIsTrue()){
            if(func_num_args() == 0) $values = $this->values;
            dump(...$values);
        }
        return $this;
    }

    public function dd(...$values)
    {
        if($this->conditionsIsTrue()){
            if(func_num_args() == 0) $values = $this->values;
            dd(...$values);
        }
        return $this;
    }

    public function return($value, $when = true)
    {
        return $this->conditionsIsTrue() == $when ? $value : null;
    }

}


function ifif($value1 = true, $value2 = true)
{
    if(func_num_args() == 2){
        return new \debugif($value1, $value2);
    }else{
        return new \debugif($value1);
    }

}