Completed
Push — master ( 7cb054...584ba8 )
by Tim
44:11 queued 26:38
created

CatchExceptionAssert   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 53
rs 10
wmc 9
lcom 1
cbo 1
1
<?php
2
/*
3
 * Copyright (c) Ouzo contributors, http://ouzoframework.org
4
 * This file is made available under the MIT License (view the LICENSE file for more information).
5
 */
6
namespace Ouzo\Tests;
7
8
use Exception;
9
10
class CatchException
11
{
12
    public static $exception;
13
14
    public static function when($object)
15
    {
16
        self::$exception = null;
17
        return new CatchExceptionObject($object);
18
    }
19
20
    public static function assertThat()
21
    {
22
        return new CatchExceptionAssert(self::$exception);
23
    }
24
25
    public static function get()
26
    {
27
        return self::$exception;
28
    }
29
}
30
31
class CatchExceptionObject
32
{
33
    private $object;
34
35
    public function __construct($object)
36
    {
37
        $this->object = $object;
38
    }
39
40
    public function __call($method, $args)
41
    {
42
        try {
43
            call_user_func_array(array($this->object, $method), $args);
44
        } catch (Exception $exception) {
45
            CatchException::$exception = $exception;
46
        }
47
    }
48
}
49
50
class CatchExceptionAssert
51
{
52
    /**
53
     * @var Exception
54
     */
55
    private $exception;
56
57
    public function __construct($exception)
58
    {
59
        $this->exception = $exception;
60
    }
61
62
    public function isInstanceOf($exception)
63
    {
64
        AssertAdapter::assertInstanceOf($exception, $this->exception);
65
        return $this;
66
    }
67
68
    public function isEqualTo($exception)
69
    {
70
        AssertAdapter::assertEquals($exception, $this->exception);
71
        return $this;
72
    }
73
74
    public function notCaught()
75
    {
76
        if ($this->exception) {
77
            throw $this->exception;
78
        }
79
        return $this;
80
    }
81
82
    public function hasMessage($message)
83
    {
84
        $this->_validateExceptionThrown();
85
        AssertAdapter::assertEquals($message, $this->exception->getMessage());
86
        return $this;
87
    }
88
89
    public function hasCode($code)
90
    {
91
        $this->_validateExceptionThrown();
92
        AssertAdapter::assertEquals($code, $this->exception->getCode());
93
        return $this;
94
    }
95
96
    private function _validateExceptionThrown()
97
    {
98
        if (!$this->exception) {
99
            AssertAdapter::fail('Exception was not thrown.');
100
        }
101
    }
102
}
103