Repository navigation
Expand file tree
/
Copy pathEntityAwareFactory.php
More file actions
67 lines (51 loc) · 1.85 KB
/
Copy pathEntityAwareFactory.php
File metadata and controls
67 lines (51 loc) · 1.85 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
<?php
declare(strict_types=1);
namespace MsgPhp\Domain\Factory;
use MsgPhp\Domain\{DomainIdentityMappingInterface, DomainIdInterface};
use MsgPhp\Domain\Exception\InvalidClassException;
/**
* @author Roland Franssen <franssen.roland@gmail.com>
*/
final class EntityAwareFactory implements EntityAwareFactoryInterface
{
private $factory;
private $identityMapping;
private $identifierMapping;
public function __construct(DomainObjectFactoryInterface $factory, DomainIdentityMappingInterface $identityMapping, array $identifierMapping = [])
{
$this->factory = $factory;
$this->identityMapping = $identityMapping;
$this->identifierMapping = $identifierMapping;
}
public function create(string $class, array $context = [])
{
return $this->factory->create($class, $context);
}
public function reference(string $class, $id)
{
$idFields = $this->identityMapping->getIdentifierFieldNames($class);
if (!\is_array($id)) {
$id = [array_shift($idFields) => $id];
}
return $this->factory->create($class, $id + array_fill_keys($idFields, null));
}
public function identify(string $class, $value): DomainIdInterface
{
if ($value instanceof DomainIdInterface) {
return $value;
}
$object = $this->factory->create($this->identifierMapping[$class] ?? $class, [$value]);
if (!$object instanceof DomainIdInterface) {
throw InvalidClassException::create($class);
}
return $object;
}
public function nextIdentifier(string $class): DomainIdInterface
{
$object = $this->factory->create($this->identifierMapping[$class] ?? $class);
if (!$object instanceof DomainIdInterface) {
throw InvalidClassException::create($class);
}
return $object;
}
}