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