Test Failed
Push — master ( 9507e6...8ad776 )
by Artem
01:32
created

AbstractFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 42.11%

Importance

Changes 0
Metric Value
eloc 16
c 0
b 0
f 0
dl 0
loc 69
ccs 8
cts 19
cp 0.4211
rs 10
wmc 8

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A loadConfig() 0 9 3
A entityExists() 0 3 1
A make() 0 15 3
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 8
    public function __construct(array $config)
21
    {
22 8
        $this->loadConfig($config);
23 8
    }
24
25
    /**
26
     * loadConfig.
27
     *
28
     * @access	protected
29
     * @param	array	$config	
30
     * @return	void
31
     */
32 8
    protected function loadConfig(array $config): void
33
    {
34 8
        foreach ($config as $code => $class) {
35 8
            if (!class_exists($class)) {
36
                throw new FactoryException('Фабрика не сможет создать такой объект: '.$class);
37
            }
38
        }
39
40 8
        $this->config = $config;
41 8
    }
42
43
    /**
44
     * make.
45
     *
46
     * @access	public
47
     * @param	string	$code	
48
     * @return	mixed
49
     */
50
    public function make(string $code)
51
    {
52
        if (empty($this->config)) {
53
            throw new ConfigurationException('Фабрика не инициализирована');
54
        }
55
56
        if (! $this->entityExists($code)) {
57
            throw new FactoryException('Фабрика не может сделать такую сущность');
58
        }
59
60
        $resolved = new $this->config[$code];
61
62
        Assert::isInstanceOf($resolved, $this->allowedType);
63
64
        return $resolved;
65
    }
66
67
    /**
68
     * entityExists.
69
     *
70
     * @access	public
71
     * @param	string	$code	
72
     * @return	bool
73
     */
74
    public function entityExists(string $code): bool
75
    {
76
        return array_key_exists($code, $this->config);
77
    }
78
}
79