Completed
Pull Request — master (#6)
by Alberto
04:09
created

PHPUnitMockingStrategy::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Moka\Strategy;
5
6
use Moka\Exception\InvalidArgumentException;
7
use Moka\Exception\MockNotCreatedException;
8
use Moka\Stub\Stub;
9
use Moka\Stub\StubSet;
10
use PHPUnit_Framework_MockObject_Generator as MockGenerator;
11
use PHPUnit_Framework_MockObject_MockObject as MockObject;
12
13
/**
14
 * Class PHPUnitMockingStrategy
15
 * @package Moka\Strategy
16
 */
17
class PHPUnitMockingStrategy extends AbstractMockingStrategy
18
{
19
    /**
20
     * @var MockGenerator
21
     */
22
    private $generator;
23
24
    /**
25
     * PHPUnitMockingStrategy constructor.
26
     */
27 13
    public function __construct()
28
    {
29 13
        $this->generator = new MockGenerator();
30 13
        $this->setMockType(MockObject::class);
31
    }
32
33
    /**
34
     * @param string $fqcn
35
     * @return MockObject
36
     *
37
     * @throws MockNotCreatedException
38
     */
39 15
    public function build(string $fqcn)
40
    {
41
        try {
42 15
            return $this->generator->getMock(
43 15
                $fqcn,
44 15
                $methods = [],
45 15
                $arguments = [],
46 15
                $mockClassName = '',
47 15
                $callOriginalConstructor = false
48
            );
49 2
        } catch (\Throwable $exception) {
50
            // Use \Throwable to catch \ParseError too.
51 2
            throw new MockNotCreatedException(
52 2
                sprintf(
53 2
                    'Unable to create mock object for FQCN %s',
54 2
                    $fqcn
55
                )
56
            );
57
        }
58
    }
59
60
    /**
61
     * @param MockObject $mock
62
     * @param StubSet $stubs
63
     * @return void
64
     *
65
     * @throws InvalidArgumentException
66
     */
67 12
    public function decorate($mock, StubSet $stubs)
68
    {
69 12
        $this->checkMockType($mock);
70
71
        /** @var Stub $stub */
72 11
        foreach ($stubs as $stub) {
73 5
            $methodValue = $stub->getMethodValue();
74
75 5
            $partial = $mock->method($stub->getMethodName());
76 5
            $methodValue instanceof \Exception
77 2
                ? $partial->willThrowException($methodValue)
78 5
                : $partial->willReturn($methodValue);
79
        }
80
    }
81
82
    /**
83
     * @param MockObject $mock
84
     * @return MockObject
85
     *
86
     * @throws InvalidArgumentException
87
     */
88 13
    public function get($mock)
89
    {
90 13
        $this->checkMockType($mock);
91
92 12
        return $mock;
93
    }
94
}
95