ObjectExceptionMatcher   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
c 2
b 0
f 0
dl 0
loc 46
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A withMessage() 0 5 1
A withMessageMatchesPattern() 0 5 1
A withCode() 0 5 1
A when() 0 11 2
1
<?php
2
3
namespace PHPKitchen\CodeSpecs\Expectation\Internal;
4
5
use PHPKitchen\CodeSpecs\Expectation\Matcher\Base\Matcher;
6
use PHPKitchen\CodeSpecs\Expectation\Matcher\ObjectMatcher;
7
8
/**
9
 * ExceptionMatcher is designed to check that object throws valid exception.
10
 * This matcher being used in pair with {@link ObjectMatcher}.
11
 *
12
 * @property \Exception $actual
13
 *
14
 * @package PHPKitchen\CodeSpecs\Expectation
15
 * @author Dima Kolodko <[email protected]>
16
 */
17
class ObjectExceptionMatcher extends Matcher {
18
    public $exceptionClassOrObject;
19
20
    public function withMessage($message) {
21
        $this->startStep('has message "' . $message . '"')
22
             ->expectExceptionMessage($message);
23
24
        return $this;
25
    }
26
27
    public function withMessageMatchesPattern($messagePattern) {
28
        $this->startStep('has message matching pattern "' . $messagePattern . '"')
29
             ->expectExceptionMessageRegExp($messagePattern);
30
31
        return $this;
32
    }
33
34
    public function withCode($code) {
35
        $this->startStep('has code "' . $code . '"')
36
             ->expectExceptionCode($code);
37
38
        return $this;
39
    }
40
41
    /**
42
     * Identifies a situation when exception should be raised.
43
     * Supposed to executes method of the object.
44
     * This methods should to be used after {@link throwsException} and "with*" methods to gain expression like:
45
     * <pre>
46
     * $I->seeObject($a)->throwsException(Exception::class)->when(function($object) {$object->doParty();});
47
     * // or
48
     * $I->seeObject($a)->throwsException(IronyException::class)->withCode(500)->when(function($object) {$object->doParty();});
49
     * <pre/>
50
     * and finish scenario.
51
     */
52
    public function when(callable $callback) {
53
        $exceptionClassOrObject = $this->exceptionClassOrObject;
54
        if (is_string($exceptionClassOrObject)) {
55
            $this->startStep('throws exception "' . $exceptionClassOrObject . '"')
56
                 ->expectException($this->exceptionClassOrObject);
57
        } else {
58
            $this->startStep('throws exception "' . get_class($exceptionClassOrObject) . '"')
59
                 ->expectExceptionObject($this->exceptionClassOrObject);
60
        }
61
62
        call_user_func_array($callback, [$this->getActualValue()]);
63
    }
64
}
65
66
67