1
|
|
|
<?php |
2
|
|
|
namespace Vsmoraes\DynamoMapper; |
3
|
|
|
|
4
|
|
|
use ICanBoogie\Inflector; |
5
|
|
|
use Vsmoraes\DynamoMapper\Exception\AttributeUnreachable; |
6
|
|
|
use Vsmoraes\DynamoMapper\Exception\InvalidAttributeType; |
7
|
|
|
use Vsmoraes\DynamoMapper\Mappings\Factory; |
8
|
|
|
|
9
|
|
|
class EntityMap implements Map |
10
|
|
|
{ |
11
|
|
|
/** |
12
|
|
|
* @var mixed |
13
|
|
|
*/ |
14
|
|
|
private $entity; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @var array |
18
|
|
|
*/ |
19
|
|
|
private $data; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var \ReflectionClass |
23
|
|
|
*/ |
24
|
|
|
protected $reflectionClass; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var Factory |
28
|
|
|
*/ |
29
|
|
|
protected $mappingFactory; |
30
|
|
|
|
31
|
|
|
public function __construct($entity, array $data, $mappingFactory) |
32
|
|
|
{ |
33
|
|
|
$this->entity = $entity; |
34
|
|
|
$this->data = $data; |
35
|
|
|
$this->mappingFactory = $mappingFactory; |
36
|
|
|
$this->reflectionClass = new \ReflectionClass($this->entity); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
public function getMap() |
40
|
|
|
{ |
41
|
|
|
$entity = clone $this->entity; |
42
|
|
|
|
43
|
|
|
$annotations = new Annotations($this->reflectionClass); |
44
|
|
|
|
45
|
|
|
foreach ($this->data as $attribute => $value) { |
46
|
|
|
$type = $annotations->getAttributeType($attribute); |
47
|
|
|
$value = $this->getFieldValue($value, $type); |
48
|
|
|
|
49
|
|
|
$this->setEntityValue($entity, $attribute, $value); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return $entity; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param array $data |
57
|
|
|
* @param string $type |
58
|
|
|
* @return mixed |
59
|
|
|
* @throws InvalidAttributeType |
60
|
|
|
*/ |
61
|
|
|
protected function getFieldValue(array $data, string $type) |
62
|
|
|
{ |
63
|
|
|
return $this->mappingFactory->make($type) |
64
|
|
|
->toAttribute($data); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @param mixed $entity |
69
|
|
|
* @param string $field |
70
|
|
|
* @param mixed $value |
71
|
|
|
* @throws AttributeUnreachable |
72
|
|
|
*/ |
73
|
|
|
protected function setEntityValue($entity, string $field, $value) |
74
|
|
|
{ |
75
|
|
|
$method = Inflector::get()->camelize('set_' . $field); |
76
|
|
|
|
77
|
|
|
if (method_exists($entity, $method)) { |
78
|
|
|
$entity->{$method}($value); |
79
|
|
|
return; |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
$property = new \ReflectionProperty($entity, $field); |
83
|
|
|
if ($property->isPublic()) { |
84
|
|
|
$entity->{$field} = $value; |
85
|
|
|
return; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
throw new AttributeUnreachable("Cannot access the attribute: '{$field}'"); |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|