Passed
Pull Request — master (#16)
by Donald
01:57
created

Expectation   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 62
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __call() 0 6 1
A verify() 0 15 3
1
<?php namespace Chekote\Phake;
2
3
use Phake_IMock;
4
use Phake_Proxies_StubberProxy;
5
use Phake_Proxies_VerifierProxy;
6
use RuntimeException;
7
8
/**
9
 * Combines a Phake Stubber and Verifier to create an expectation.
10
 *
11
 * This class is used to accomplish something similar to Prophecy predictions, but without the opinionated restrictions
12
 * that come with that mocking framework.
13
 */
14
class Expectation
15
{
16
    /** @var Phake_IMock the mock object */
17
    protected $mock;
18
19
    /** @var string the method expected to be called */
20
    protected $method;
21
22
    /** @var array the arguments expected to be passed to the method */
23
    protected $args;
24
25
    /** @var int the number of times the method is expected to be called */
26
    protected $count;
27
28
    /**
29
     * Expectation constructor.
30
     *
31
     * @param Phake_IMock $mock  the mock object
32
     * @param int         $count number of times the method is expected to be called
33
     */
34
    public function __construct(Phake_IMock $mock, int $count) {
35
        $this->mock = $mock;
36
        $this->count = $count;
37
    }
38
39
    /**
40
     * Verifies that the expected method was called.
41
     *
42
     * @throws RuntimeException if a method has not been set for the expectation.
43
     * @throws RuntimeException if args have not been set for the expectation.
44
     * @return Phake_Proxies_VerifierProxy
45
     */
46
    public function verify() {
47
        if (!isset($this->method)) {
48
            throw new RuntimeException('Expectation method was not set');
49
        }
50
51
        if (!isset($this->args)) {
52
            throw new RuntimeException('Expectation args were not set');
53
        }
54
55
        $method = $this->method;
56
57
        /** @var Phake_Proxies_VerifierProxy $verifier */
58
        $verifier = Phake::verify($this->mock, Phake::times($this->count))->$method(...$this->args);
59
60
        return $verifier;
61
    }
62
63
    /**
64
     * Sets the expected method to be called.
65
     *
66
     * @param  string $method the method that is expected to be called.
67
     * @param  array  $args   the args that are expected to be passed to the method.
68
     * @return Phake_Proxies_StubberProxy
69
     */
70
    public function __call(string $method, array $args) {
71
        // record the method and args for verification later
72
        $this->method = $method;
73
        $this->args = $args;
74
75
        return Phake::when($this->mock)->$method(...$args);
76
    }
77
}
78