ExceptionCatcher.php

<?php

namespace Taeluf\Tester;

class ExceptionCatcher {

    protected $strict;
    protected $targetClass;
    protected $contains = [];

    public function __construct($expectingClass, $strict=false){
        $this->strict = $strict;
        $this->targetClass = $expectingClass;
    }

    public function containing($msg){
        $this->contains[] = $msg;
        return $this;
    }

    public function shortenMessage($msg){
        $oneLine = implode(" ",array_map('trim',explode("\n",$msg)));
        $output = substr($oneLine,0,200);
        if (strlen($output)>200)$output .= '...';

        return $output;
    }

    public function matches($exception){
        //@TODO improve error output for exception testing. I'd like to report failures with details as well
        $strict = $this->strict;
        $eClass = get_class($exception);
        $eMessage = $exception->getMessage();
        if ($strict
            &&$eClass!=$this->targetClass)return false;
        else if (!($exception instanceof $this->targetClass))return false;

        foreach ($this->contains as $str){
            if (strpos($eMessage,$str)===false){
                return false;
            }
        }

        
        $output = $this->shortenMessage(var_export($this->contains,true));
        $eMessage = $this->shortenMessage(var_export($eMessage,true));



        echo "+++pass-exception+++";
        if ($strict)echo "\n strict classname comparison";
        echo "\nTarget:";
        echo "\n- Class: {$this->targetClass}";
        echo "\n- Containing: ".$output;
        echo "\n--";
        echo "\nActual:";
        echo "\n- Class: ".$eClass;
        echo "\n- Msg: ".$eMessage;

        echo "\n------------\n";
        return true;
    }

}