Completed
Push — master ( 958f25...396f9a )
by Hannes
02:12
created

ReturnExpectation::makeString()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 12
rs 8.8571
cc 5
eloc 8
nc 4
nop 1
1
<?php
2
3
namespace hanneskod\readmetester\Expectation;
4
5
use hanneskod\readmetester\Result;
6
use UnexpectedValueException;
7
8
/**
9
 * Validate that correct data is returned
10
 */
11
class ReturnExpectation implements ExpectationInterface
12
{
13
    /**
14
     * @var Regexp Expression matching return value
15
     */
16
    private $regexp;
17
18
    /**
19
     * Set regular expression matching return value
20
     *
21
     * @param Regexp $regexp
22
     */
23
    public function __construct(Regexp $regexp)
24
    {
25
        $this->regexp = $regexp;
26
    }
27
28
    /**
29
     * Validate that correct value is returned
30
     *
31
     * @param  Result $result
32
     * @return null
33
     * @throws UnexpectedValueException If return value does not match regular expression
34
     */
35
    public function validate(Result $result)
36
    {
37
        $return = $this->makeString($result->getReturnValue());
38
39
        if (!$this->regexp->isMatch($return)) {
40
            throw new UnexpectedValueException(
41
                "Failed asserting that return value matches {$this->regexp}"
42
            );
43
        }
44
    }
45
46
    private function makeString($value)
47
    {
48
        if (is_scalar($value)) {
49
            return (string)$value;
50
        } elseif (is_null($value)) {
51
            return '';
52
        } elseif (is_object($value) && method_exists($value, '__toString' )) {
53
            return (string)$value;
54
        }
55
56
        throw new UnexpectedValueException("Unable to convert return value into string");
57
    }
58
}
59