-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFactory.php
More file actions
97 lines (81 loc) · 2.54 KB
/
Factory.php
File metadata and controls
97 lines (81 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
/*
* This file is part of the enhavo package.
*
* (c) WE ARE INDEED GmbH
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Enhavo\Component\Type;
use Enhavo\Component\Type\Exception\TypeCreateException;
class Factory implements FactoryInterface
{
public function __construct(
private readonly string $class,
private readonly RegistryInterface $registry,
) {
}
/**
* @param string|null $key
*
* @throws TypeCreateException
*
* @return object
*/
public function create(array $options, $key = null)
{
if (!isset($options['type'])) {
throw TypeCreateException::missingOption($this->class, $options);
}
$type = $this->registry->getType($options['type']);
$parents = $this->getParents($type);
unset($options['type']);
$class = $this->instantiate($this->class, [
'type' => $type,
'parents' => $parents,
'options' => $options,
'key' => $key,
'extensions' => $this->getExtensions($type, $parents),
]);
return $class;
}
protected function instantiate($class, $arguments)
{
return new $class($arguments['type'], $arguments['parents'], $arguments['options'], $arguments['key'], $arguments['extensions']);
}
private function getParents(TypeInterface $type)
{
$parents = [];
$parent = $type::getParentType();
while (null !== $parent) {
$parentType = $this->registry->getType($parent);
$parents[] = $parentType;
$parent = $parentType::getParentType($parentType);
}
return array_reverse($parents);
}
private function getExtensions(TypeInterface $type, array $parents): array
{
$extensions = [];
$checkTypes = [$type];
foreach ($parents as $parent) {
$checkTypes[] = $parent;
}
foreach ($checkTypes as $checkType) {
foreach ($this->registry->getExtensions($checkType) as $foundExtension) {
$exists = false;
foreach ($extensions as $extension) {
if ($extension === $foundExtension) {
$exists = true;
break;
}
}
if (!$exists) {
$extensions[] = $foundExtension;
}
}
}
return $extensions;
}
}