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
|
9 |
|
public function __construct(array $config) |
26
|
|
|
{ |
27
|
9 |
|
$this->loadConfig($config); |
28
|
9 |
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* loadConfig. |
32
|
|
|
* |
33
|
|
|
* @access protected |
34
|
|
|
* @param array $config |
35
|
|
|
* @return void |
36
|
|
|
*/ |
37
|
9 |
|
protected function loadConfig(array $config): void |
38
|
|
|
{ |
39
|
9 |
|
foreach ($config as $code => $class) { |
40
|
9 |
|
if (!class_exists($class)) { |
41
|
|
|
throw new FactoryException('Фабрика не сможет создать такой объект: '.$class); |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
9 |
|
$this->config = $config; |
46
|
9 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* make. |
50
|
|
|
* |
51
|
|
|
* @access public |
52
|
|
|
* @param string $code |
53
|
|
|
* @return mixed |
54
|
|
|
*/ |
55
|
1 |
|
public function make(string $code) |
56
|
|
|
{ |
57
|
1 |
|
if (! empty($this->resolved[$code])) { |
58
|
|
|
return $this->resolved[$code]; |
59
|
|
|
} |
60
|
|
|
|
61
|
1 |
|
if (empty($this->config)) { |
62
|
|
|
throw new ConfigurationException('Фабрика не инициализирована'); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
if (is_callable($this->config[$code])) { |
66
|
|
|
$resolved = $this->config[$code](); |
67
|
1 |
|
} elseif (is_string($code)) { |
|
|
|
|
68
|
1 |
|
$resolved = $this->getResolvedFromString($code); |
69
|
|
|
} |
70
|
|
|
|
71
|
1 |
|
Assert::isInstanceOf($resolved, $this->allowedType); |
|
|
|
|
72
|
|
|
|
73
|
1 |
|
$this->resolved[$code] = $resolved; |
74
|
|
|
|
75
|
1 |
|
return $this->resolved[$code]; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
/** |
79
|
|
|
* getResolvedFromString. |
80
|
|
|
* |
81
|
|
|
* @access protected |
82
|
|
|
* @return mixed |
83
|
|
|
*/ |
84
|
1 |
|
protected function getResolvedFromString(string $code) |
85
|
|
|
{ |
86
|
1 |
|
if (! $this->entityExists($code)) { |
87
|
|
|
throw new FactoryException('Фабрика не может сделать такую сущность'); |
88
|
|
|
} |
89
|
|
|
|
90
|
1 |
|
return new $this->config[$code]; |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
/** |
94
|
|
|
* entityExists. |
95
|
|
|
* |
96
|
|
|
* @access public |
97
|
|
|
* @param string $code |
98
|
|
|
* @return bool |
99
|
|
|
*/ |
100
|
1 |
|
public function entityExists(string $code): bool |
101
|
|
|
{ |
102
|
1 |
|
return array_key_exists($code, $this->config); |
103
|
|
|
} |
104
|
|
|
} |
105
|
|
|
|