Passed
Push — master ( fae04d...859641 )
by Artem
01:45
created

AbstractFactory::entityExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace Prozorov\DataVerification\Factories;
4
5
use Prozorov\DataVerification\Exceptions\{ConfigurationException, FactoryException};
6
use Webmozart\Assert\Assert;
7
8
abstract class AbstractFactory
9
{
10
    /**
11
     * @var string $allowedType
12
     */
13
    protected $allowedType;
14
15
    /**
16
     * @var array $config
17
     */
18
    protected $config = [];
19
20
    /**
21
     * @var array $resolved
22
     */
23
    protected $resolved = [];
24
25 13
    public function __construct(array $config)
26
    {
27 13
        $this->config = $config;
28 13
    }
29
30
    /**
31
     * make.
32
     *
33
     * @access	public
34
     * @param	string	$code	
35
     * @return	mixed
36
     */
37 5
    public function make(string $code)
38
    {
39 5
        if (! empty($this->resolved[$code])) {
40 1
            return $this->resolved[$code];
41
        }
42
43 5
        if (empty($this->config)) {
44
            throw new ConfigurationException('Фабрика не инициализирована');
45
        }
46
47 5
        if (empty($this->config[$code])) {
48 1
            throw new FactoryException('Отсутствуют инструкции по созданию объекта ' . $code);
49
        }
50
51 4
        if (is_callable($this->config[$code])) {
52
            $resolved = $this->config[$code]();
53 4
        } elseif (is_string($code)) {
0 ignored issues
show
introduced by
The condition is_string($code) is always true.
Loading history...
54 4
            $resolved = $this->getResolvedFromString($code);
55
        }
56
57 4
        Assert::isInstanceOf($resolved, $this->allowedType);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $resolved does not seem to be defined for all execution paths leading up to this point.
Loading history...
58
59 4
        $this->resolved[$code] = $resolved;
60
61 4
        return $this->resolved[$code];
62
    }
63
64
    /**
65
     * getResolvedFromString.
66
     *
67
     * @access	protected
68
     * @return	mixed
69
     */
70 4
    protected function getResolvedFromString(string $code)
71
    {
72 4
        if (! $this->entityExists($code)) {
73
            throw new FactoryException('Фабрика не может сделать такую сущность');
74
        }
75
76 4
        return new $this->config[$code];
77
    }
78
79
    /**
80
     * entityExists.
81
     *
82
     * @access	public
83
     * @param	string	$code	
84
     * @return	bool
85
     */
86 4
    public function entityExists(string $code): bool
87
    {
88 4
        return array_key_exists($code, $this->config);
89
    }
90
}
91