Passed
Push — master ( a7f03b...b76a97 )
by Dan
01:56
created

InvocationFactory::prepareInvocation()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 5
nop 1
dl 0
loc 19
rs 9.6111
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Nopolabs\Test;
5
6
7
use PHPUnit\Framework\TestCase;
8
use PHPUnit_Framework_MockObject_Matcher_Invocation;
9
10
class InvocationFactory
11
{
12
    public function prepareInvocation($invoked) : PHPUnit_Framework_MockObject_Matcher_Invocation
13
    {
14
        if ($invoked === null) {
15
            return TestCase::any();
16
        }
17
18
        if (\is_object($invoked)) {
19
            return $invoked;
20
        }
21
22
        if (\is_numeric($invoked)) {
23
            return $this->prepareInvocationNumeric((int)$invoked);
24
        }
25
26
        if (\is_string($invoked)) {
27
            return $this->prepareInvocationString($invoked);
28
        }
29
30
        throw new TestException("prepareInvocation cannot prepare '$invoked'");
31
    }
32
33
    private function prepareInvocationNumeric(int $times): PHPUnit_Framework_MockObject_Matcher_Invocation
34
    {
35
        switch ($times) {
36
            case 0:
37
                return TestCase::never();
38
            case 1:
39
                return TestCase::once();
40
            default:
41
                return TestCase::exactly($times);
42
        }
43
    }
44
45
    private function prepareInvocationString(string $invoked): PHPUnit_Framework_MockObject_Matcher_Invocation
46
    {
47
        if (preg_match("/(?'method'\w+)(?:\s+(?'count'\d+))?/", $invoked, $matches)) {
48
            $method = $matches['method'];
49
            if (!isset($matches['count'])) {
50
                switch ($method) {
51
                    case 'once':
52
                        return TestCase::once();
53
                    case 'any':
54
                        return TestCase::any();
55
                    case 'never':
56
                        return TestCase::never();
57
                    case 'atLeastOnce':
58
                        return TestCase::atLeastOnce();
59
                }
60
            } else {
61
                $count = (int)$matches['count'];
62
                switch ($method) {
63
                    case 'atLeast':
64
                        return TestCase::atLeast($count);
65
                    case 'exactly':
66
                        return TestCase::exactly($count);
67
                    case 'atMost':
68
                        return TestCase::atMost($count);
69
                }
70
            }
71
        }
72
73
        throw new TestException("prepareInvocationString cannot handle '$invoked'");
74
    }
75
}
76