1: <?php
2:
3: namespace PHPixie\ORM\Models\Model\Implementation;
4:
5: abstract class Entity implements \PHPixie\ORM\Models\Model\Entity
6: {
7: protected $entityPropertyMap;
8: protected $data;
9: protected $config;
10: protected $relationshipProperties;
11:
12: public function __construct($entityPropertyMap, $config, $data)
13: {
14: $this->entityPropertyMap = $entityPropertyMap;
15: $this->config = $config;
16: $this->data = $data;
17: }
18:
19: public function modelName()
20: {
21: return $this->config->model;
22: }
23:
24: public function data()
25: {
26: return $this->data;
27: }
28:
29: public function getField($name, $default = null)
30: {
31: return $this->data->get($name, $default);
32: }
33:
34: public function getRequiredField($name)
35: {
36: return $this->data->getRequired($name);
37: }
38:
39: public function setField($name, $value)
40: {
41: $this->data->set($name, $value);
42: return $this;
43: }
44:
45: public function getRelationshipProperty($name, $createMissing = true)
46: {
47: $this->requirePropertyNames();
48:
49: if (!array_key_exists($name, $this->relationshipProperties)) {
50: throw new \PHPixie\ORM\Exception\Relationship("Relationship property '$name' is not defined for '{$this->modelName()}'");
51: }
52:
53: return $this->relationshipProperty($name, $createMissing);
54: }
55:
56: protected function relationshipProperty($name, $createMissing = true)
57: {
58: $property = $this->relationshipProperties[$name];
59:
60: if($property === null && $createMissing) {
61: $property = $this->entityPropertyMap->property($this, $name);
62: $this->relationshipProperties[$name] = $property;
63: }
64:
65: return $this->relationshipProperties[$name];
66: }
67:
68: public function asObject($recursive = false)
69: {
70: $this->requirePropertyNames();
71:
72: $data = $this->data->data();
73:
74: if($recursive) {
75: foreach($this->relationshipProperties as $name => $property) {
76: if($property instanceof \PHPixie\ORM\Relationships\Relationship\Property\Entity\Data && $property->isLoaded()) {
77: $data->$name = $property->asData(true);
78:
79: }
80: }
81: }
82: return $data;
83: }
84:
85: public function __get($name)
86: {
87: $this->requirePropertyNames();
88:
89: if (array_key_exists($name, $this->relationshipProperties)) {
90: return $this->relationshipProperty($name);
91: }
92:
93: return $this->getRequiredField($name);
94: }
95:
96: public function __call($name, $params)
97: {
98: $property = $this->getRelationshipProperty($name);
99: return call_user_func_array($property, $params);
100: }
101:
102: public function __set($name, $value)
103: {
104: $this->setField($name, $value);
105: }
106:
107: protected function requirePropertyNames()
108: {
109: if ($this->relationshipProperties === null) {
110: $propertyNames = $this->entityPropertyMap->getPropertyNames($this->modelName());
111: $this->relationshipProperties = array_fill_keys($propertyNames, null);
112: }
113: }
114:
115: }