1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Tarantool\Mapper; |
4
|
|
|
|
5
|
|
|
use BadMethodCallException; |
6
|
|
|
use Tarantool\Mapper\Plugin\Annotation; |
7
|
|
|
|
8
|
|
|
class Entity |
9
|
|
|
{ |
10
|
|
|
private $_repository; |
11
|
|
|
|
12
|
|
|
public function __construct(Repository $repository) |
13
|
|
|
{ |
14
|
|
|
$this->_repository = $repository; |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function getRepository() |
18
|
|
|
{ |
19
|
|
|
return $this->_repository; |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function save() |
23
|
|
|
{ |
24
|
|
|
return $this->getRepository()->save($this); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function __call($name, $arguments) |
28
|
|
|
{ |
29
|
|
|
if (strpos($name, 'get') === 0) { |
30
|
|
|
$property = lcfirst(substr($name, 3)); |
31
|
|
|
$mapper = $this->getRepository()->getMapper(); |
32
|
|
|
if (property_exists($this, $property)) { |
33
|
|
|
$reference = $this->getRepository()->getSpace()->getReference($property); |
34
|
|
|
if ($reference) { |
35
|
|
|
return $mapper->findOrFail($reference, [ |
36
|
|
|
'id' => $this->$property, |
37
|
|
|
]); |
38
|
|
|
} |
39
|
|
|
} else if(strpos($property, 'Collection') !== false) { |
40
|
|
|
$property = substr($property, 0, -10); |
41
|
|
|
$targetSpace = $mapper->getSchema()->toUnderscore($property); |
42
|
|
|
if ($mapper->getSchema()->hasSpace($targetSpace)) { |
43
|
|
|
$localSpace = $this->getRepository()->getSpace()->getName(); |
44
|
|
|
$candidates = []; |
45
|
|
|
foreach ($mapper->getSchema()->getSpace($targetSpace)->getFormat() as $row) { |
46
|
|
|
if (array_key_exists('reference', $row) && $row['reference'] == $localSpace) { |
47
|
|
|
$candidates[] = $row['name']; |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
if (count($candidates) == 1) { |
51
|
|
|
return $mapper->find($targetSpace, [ |
52
|
|
|
$candidates[0] => $this->id |
|
|
|
|
53
|
|
|
]); |
54
|
|
|
} |
55
|
|
|
if (count($candidates) > 1) { |
56
|
|
|
throw new Exception("Multiple references from $targetSpace to $localSpace"); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
throw new BadMethodCallException("Call to undefined method ". get_class($this).'::'.$name); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
public function __debugInfo() |
65
|
|
|
{ |
66
|
|
|
$info = get_object_vars($this); |
67
|
|
|
|
68
|
|
|
unset($info['_repository']); |
69
|
|
|
|
70
|
|
|
if (array_key_exists('app', $info) && is_object($info['app'])) { |
71
|
|
|
unset($info['app']); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $info; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: