1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Daikon\Entity\Entity; |
4
|
|
|
|
5
|
|
|
use Countable; |
6
|
|
|
use Daikon\DataStructure\TypedMapTrait; |
7
|
|
|
use Daikon\Entity\ValueObject\Nil; |
8
|
|
|
use Daikon\Entity\ValueObject\ValueObjectInterface; |
9
|
|
|
use Daikon\Interop\ToNativeInterface; |
10
|
|
|
use IteratorAggregate; |
11
|
|
|
|
12
|
|
|
final class ValueObjectMap implements ToNativeInterface, IteratorAggregate, Countable |
13
|
|
|
{ |
14
|
|
|
use TypedMapTrait; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var EntityInterface $entity |
18
|
|
|
*/ |
19
|
|
|
private $entity; |
20
|
|
|
|
21
|
31 |
|
public static function forEntity(EntityInterface $entity, array $entityState = []): self |
22
|
|
|
{ |
23
|
31 |
|
return new static($entity, $entityState); |
24
|
|
|
} |
25
|
|
|
|
26
|
13 |
|
public function withValue(string $attrName, $value): self |
27
|
|
|
{ |
28
|
13 |
|
$clonedMap = clone $this; |
29
|
13 |
|
$attribute = $this->entity->getEntityType()->getAttribute($attrName); |
30
|
13 |
|
$clonedMap->compositeMap[$attrName] = $attribute->makeValue($value, $clonedMap->entity); |
31
|
13 |
|
return $clonedMap; |
32
|
|
|
} |
33
|
|
|
|
34
|
1 |
|
public function withValues(array $values): self |
35
|
|
|
{ |
36
|
1 |
|
$clonedMap = clone $this; |
37
|
1 |
|
foreach ($values as $attrName => $value) { |
38
|
1 |
|
$attribute = $clonedMap->entity->getEntityType()->getAttribute($attrName); |
39
|
1 |
|
$clonedMap->compositeMap[$attrName] = $attribute->makeValue($value, $clonedMap->entity); |
40
|
|
|
} |
41
|
1 |
|
return $clonedMap; |
42
|
|
|
} |
43
|
|
|
|
44
|
7 |
|
public function toNative(): array |
45
|
|
|
{ |
46
|
7 |
|
$array = []; |
47
|
7 |
|
foreach ($this as $attributeName => $valueObject) { |
48
|
7 |
|
$array[$attributeName] = $valueObject->toNative(); |
49
|
|
|
} |
50
|
7 |
|
return $array; |
51
|
|
|
} |
52
|
|
|
|
53
|
31 |
|
private function __construct(EntityInterface $entity, array $values = []) |
54
|
|
|
{ |
55
|
31 |
|
$this->entity = $entity; |
56
|
31 |
|
$valueObjects = []; |
57
|
31 |
|
foreach ($entity->getEntityType()->getAttributes() as $attrName => $attribute) { |
58
|
31 |
|
if (array_key_exists($attrName, $values)) { |
59
|
31 |
|
$valueObjects[$attrName] = $attribute->makeValue($values[$attrName], $this->entity); |
60
|
|
|
} |
61
|
|
|
} |
62
|
31 |
|
$this->init($valueObjects, ValueObjectInterface::class); |
63
|
31 |
|
} |
64
|
|
|
} |
65
|
|
|
|