BuildEasyMockTrait::buildEasyMock()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 9.1928
c 0
b 0
f 0
cc 5
nc 6
nop 2
1
<?php
2
3
namespace Fwolf\Wrapper\PHPUnit\Helper;
4
5
use PHPUnit\Framework\MockObject\Matcher\AnyInvokedCount;
6
use PHPUnit\Framework\MockObject\MockBuilder;
7
use PHPUnit\Framework\MockObject\MockObject;
8
9
/**
10
 * Trait for build simple mock which change method return value
11
 *
12
 * @method  MockBuilder getMockBuilder($className)
13
 * @method  static AnyInvokedCount  any()
14
 *
15
 * @copyright   Copyright 2015-2019 Fwolf
16
 * @license     http://opensource.org/licenses/MIT MIT
17
 */
18
trait BuildEasyMockTrait
19
{
20
    /**
21
     * @param string   $className
22
     * @param string[] $methods {methodName: returnValue}
23
     * @return  MockObject | object
24
     */
25
    public function buildEasyMock($className, array $methods = [])
26
    {
27
        $builder = $this->getMockBuilder($className)
28
            ->setMethods(empty($methods) ? null : array_keys($methods))
29
            ->disableOriginalConstructor()
30
        ;
31
32
        // Use class name without namespace path to detect abstract or trait
33
        $shortName = join('', array_slice(explode('\\', $className), -1));
34
        if ('Trait' == substr($shortName, -5)) {
35
            $mock = $builder->getMockForTrait();
36
        } elseif ('Abstract' == substr($shortName, 0, 8)) {
37
            $mock = $builder->getMockForAbstractClass();
38
        } else {
39
            $mock = $builder->getMock();
40
        }
41
42
        foreach ($methods as $method => $returnValue) {
43
            $mock->expects($this->any())
44
                ->method($method)
45
                ->willReturn($returnValue)
46
            ;
47
        }
48
49
        return $mock;
50
    }
51
}
52