Repository navigation
Expand file tree
/
Copy pathDomainObjectFactory.php
More file actions
68 lines (54 loc) · 2.27 KB
/
Copy pathDomainObjectFactory.php
File metadata and controls
68 lines (54 loc) · 2.27 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
<?php
declare(strict_types=1);
namespace MsgPhp\Domain\Factory;
use MsgPhp\Domain\{DomainIdInterface, DomainCollectionInterface};
use MsgPhp\Domain\Exception\InvalidClassException;
/**
* @author Roland Franssen <franssen.roland@gmail.com>
*/
final class DomainObjectFactory implements DomainObjectFactoryInterface
{
private $factory;
public function setNestedFactory(?DomainObjectFactoryInterface $factory): void
{
$this->factory = $factory;
}
public function create(string $class, array $context = [])
{
if (is_subclass_of($class, DomainIdInterface::class) || is_subclass_of($class, DomainCollectionInterface::class)) {
return $class::fromValue(...$this->resolveArguments($class, 'fromValue', $context));
}
if (!class_exists($class)) {
throw InvalidClassException::create($class);
}
return new $class(...$this->resolveArguments($class, '__construct', $context));
}
private function resolveArguments(string $class, string $method, array $context): array
{
$arguments = [];
foreach (ClassMethodResolver::resolve($class, $method) as $i => $argument) {
$given = true;
if (array_key_exists($name = $argument['name'], $context)) {
$value = $context[$name];
} elseif (array_key_exists($key = $argument['key'], $context)) {
$value = $context[$key];
} elseif (array_key_exists($i, $context)) {
$value = $context[$i];
} elseif (!$argument['required']) {
$value = $argument['default'];
$given = false;
} else {
throw new \LogicException(sprintf('No value available for argument $%s in class method "%s::%s()".', $name, $class, $method));
}
if ($given && isset($argument['type']) && (interface_exists($argument['type']) || class_exists($argument['type'])) && !\is_object($value)) {
try {
$arguments[] = ($this->factory ?? $this)->create($argument['type'], (array) $value);
continue;
} catch (InvalidClassException $e) {
}
}
$arguments[] = $value;
}
return $arguments;
}
}