Completed
Pull Request — master (#37)
by Alberto
01:52
created

ProxyBuilder::buildProxy()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Moka\Builder;
5
6
use Moka\Exception\InvalidIdentifierException;
7
use Moka\Exception\MockNotCreatedException;
8
use Moka\Factory\ProxyGeneratorFactory;
9
use Moka\Proxy\ProxyContainer;
10
use Moka\Proxy\ProxyInterface;
11
use Moka\Strategy\MockingStrategyInterface;
12
13
/**
14
 * Class ProxyBuilder
15
 * @package Moka\Builder
16
 */
17
class ProxyBuilder
18
{
19
    /**
20
     * @var ProxyContainer
21
     */
22
    protected $container;
23
24
    /**
25
     * @var MockingStrategyInterface
26
     */
27
    protected $mockingStrategy;
28
29
    /**
30
     * ProxyBuilder constructor.
31
     * @param MockingStrategyInterface $mockingStrategy
32
     */
33 6
    public function __construct(MockingStrategyInterface $mockingStrategy)
34
    {
35 6
        $this->mockingStrategy = $mockingStrategy;
36 6
        $this->reset();
37
    }
38
39
    /**
40
     * @return void
41
     */
42 7
    public function reset()
43
    {
44 7
        $this->container = new ProxyContainer();
45
    }
46
47
    /**
48
     * @param string $fqcnOrAlias
49
     * @param string|null $alias
50
     * @return ProxyInterface
51
     *
52
     * @throws MockNotCreatedException
53
     * @throws InvalidIdentifierException
54
     */
55 6
    public function getProxy(string $fqcnOrAlias, string $alias = null): ProxyInterface
56
    {
57 6
        if ($this->container->has($fqcnOrAlias)) {
58 1
            return $this->container->get($fqcnOrAlias);
59
        }
60
61 6
        if (null === $alias) {
62 3
            return $this->buildProxy($fqcnOrAlias);
63
        }
64
65 3
        if (!$this->container->has($alias)) {
66 3
            $this->container->set($alias, $this->buildProxy($fqcnOrAlias));
67
        }
68
69 3
        return $this->container->get($alias);
70
    }
71
72
    /**
73
     * @param string $fqcn
74
     * @return ProxyInterface
75
     */
76 6
    protected function buildProxy(string $fqcn): ProxyInterface
77
    {
78 6
        return ProxyGeneratorFactory::get($this->mockingStrategy)->get($fqcn);
79
    }
80
}
81