Completed
Push — master ( 93d6a3...bcdce7 )
by Christophe
14s queued 12s
created

CallCenter::formatExceptionMessage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.584
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Prophecy.
5
 * (c) Konstantin Kudryashov <[email protected]>
6
 *     Marcello Duarte <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Prophecy\Call;
13
14
use Prophecy\Exception\Prophecy\MethodProphecyException;
15
use Prophecy\Prophecy\ObjectProphecy;
16
use Prophecy\Argument\ArgumentsWildcard;
17
use Prophecy\Util\StringUtil;
18
use Prophecy\Exception\Call\UnexpectedCallException;
19
20
/**
21
 * Calls receiver & manager.
22
 *
23
 * @author Konstantin Kudryashov <[email protected]>
24
 */
25
class CallCenter
26
{
27
    private $util;
28
29
    /**
30
     * @var Call[]
31
     */
32
    private $recordedCalls = array();
33
34
    /**
35
     * Initializes call center.
36
     *
37
     * @param StringUtil $util
38
     */
39
    public function __construct(StringUtil $util = null)
40
    {
41
        $this->util = $util ?: new StringUtil;
42
    }
43
44
    /**
45
     * Makes and records specific method call for object prophecy.
46
     *
47
     * @param ObjectProphecy $prophecy
48
     * @param string         $methodName
49
     * @param array          $arguments
50
     *
51
     * @return mixed Returns null if no promise for prophecy found or promise return value.
52
     *
53
     * @throws \Prophecy\Exception\Call\UnexpectedCallException If no appropriate method prophecy found
54
     */
55
    public function makeCall(ObjectProphecy $prophecy, $methodName, array $arguments)
56
    {
57
        // For efficiency exclude 'args' from the generated backtrace
58
        if (PHP_VERSION_ID >= 50400) {
59
            // Limit backtrace to last 3 calls as we don't use the rest
60
            // Limit argument was introduced in PHP 5.4.0
61
            $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
62
        } elseif (defined('DEBUG_BACKTRACE_IGNORE_ARGS')) {
63
            // DEBUG_BACKTRACE_IGNORE_ARGS was introduced in PHP 5.3.6
64
            $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
65
        } else {
66
            $backtrace = debug_backtrace();
67
        }
68
69
        $file = $line = null;
70
        if (isset($backtrace[2]) && isset($backtrace[2]['file'])) {
71
            $file = $backtrace[2]['file'];
72
            $line = $backtrace[2]['line'];
73
        }
74
75
        // If no method prophecies defined, then it's a dummy, so we'll just return null
76
        if ('__destruct' === $methodName || 0 == count($prophecy->getMethodProphecies())) {
77
            $this->recordedCalls[] = new Call($methodName, $arguments, null, null, $file, $line);
78
79
            return null;
80
        }
81
82
        // There are method prophecies, so it's a fake/stub. Searching prophecy for this call
83
        $matches = array();
84
        foreach ($prophecy->getMethodProphecies($methodName) as $methodProphecy) {
85
            if (0 < $score = $methodProphecy->getArgumentsWildcard()->scoreArguments($arguments)) {
86
                $matches[] = array($score, $methodProphecy);
87
            }
88
        }
89
90
        // If fake/stub doesn't have method prophecy for this call - throw exception
91
        if (!count($matches)) {
92
            throw $this->createUnexpectedCallException($prophecy, $methodName, $arguments);
93
        }
94
95
        // Sort matches by their score value
96
        @usort($matches, function ($match1, $match2) { return $match2[0] - $match1[0]; });
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
97
98
        $score = $matches[0][0];
99
        // If Highest rated method prophecy has a promise - execute it or return null instead
100
        $methodProphecy = $matches[0][1];
101
        $returnValue = null;
102
        $exception   = null;
103
        if ($promise = $methodProphecy->getPromise()) {
104
            try {
105
                $returnValue = $promise->execute($arguments, $prophecy, $methodProphecy);
106
            } catch (\Exception $e) {
107
                $exception = $e;
108
            }
109
        }
110
111
        if ($methodProphecy->hasReturnVoid() && $returnValue !== null) {
112
            throw new MethodProphecyException(
113
                "The method \"$methodName\" has a void return type, but the promise returned a value",
114
                $methodProphecy
115
            );
116
        }
117
118
        $this->recordedCalls[] = $call = new Call(
119
            $methodName, $arguments, $returnValue, $exception, $file, $line
120
        );
121
        $call->addScore($methodProphecy->getArgumentsWildcard(), $score);
122
123
        if (null !== $exception) {
124
            throw $exception;
125
        }
126
127
        return $returnValue;
128
    }
129
130
    /**
131
     * Searches for calls by method name & arguments wildcard.
132
     *
133
     * @param string            $methodName
134
     * @param ArgumentsWildcard $wildcard
135
     *
136
     * @return Call[]
137
     */
138
    public function findCalls($methodName, ArgumentsWildcard $wildcard)
139
    {
140
        return array_values(
141
            array_filter($this->recordedCalls, function (Call $call) use ($methodName, $wildcard) {
142
                return $methodName === $call->getMethodName()
143
                    && 0 < $call->getScore($wildcard)
144
                ;
145
            })
146
        );
147
    }
148
149
    private function createUnexpectedCallException(ObjectProphecy $prophecy, $methodName,
150
                                                   array $arguments)
151
    {
152
        $classname = get_class($prophecy->reveal());
153
        $indentationLength = 8; // looks good
154
        $argstring = implode(
155
            ",\n",
156
            $this->indentArguments(
157
                array_map(array($this->util, 'stringify'), $arguments),
158
                $indentationLength
159
            )
160
        );
161
162
        $expected = array();
163
164
        foreach (call_user_func_array('array_merge', $prophecy->getMethodProphecies()) as $methodProphecy) {
165
            $expected[] = sprintf(
166
                "  - %s(\n" .
167
                "%s\n" .
168
                "    )",
169
                $methodProphecy->getMethodName(),
170
                implode(
171
                    ",\n",
172
                    $this->indentArguments(
173
                        array_map('strval', $methodProphecy->getArgumentsWildcard()->getTokens()),
174
                        $indentationLength
175
                    )
176
                )
177
            );
178
        }
179
180
        return new UnexpectedCallException(
181
            sprintf(
182
                "Unexpected method call on %s:\n".
183
                "  - %s(\n".
184
                "%s\n".
185
                "    )\n".
186
                "expected calls were:\n".
187
                "%s",
188
189
                $classname, $methodName, $argstring, implode("\n", $expected)
190
            ),
191
            $prophecy, $methodName, $arguments
192
193
        );
194
    }
195
196
    private function indentArguments(array $arguments, $indentationLength)
197
    {
198
        return preg_replace_callback(
199
            '/^/m',
200
            function () use ($indentationLength) {
201
                return str_repeat(' ', $indentationLength);
202
            },
203
            $arguments
204
        );
205
    }
206
}
207