1 | <?php |
||
38 | 29 | $entity = new Entity($this, $definition, $data); |
|
39 | 29 | if ($empty) { |
|
40 | 3 | return $entity; |
|
41 | } |
||
42 | 27 | $this->lazy($entity, $data); |
|
43 | 27 | return $this->objects[$definition->getName()][base64_encode(serialize($primary))] = $entity; |
|
44 | } |
||
45 | /** |
||
46 | * Get a collection of entities |
||
47 | * |
||
48 | * @param TableQueryIterator $iterator |
||
49 | * @param Table $definition |
||
50 | * @return Collection |
||
51 | */ |
||
52 | 54 | public function collection(TableQueryIterator $iterator, Table $definition) : Collection |
|
59 | /** |
||
60 | * Persist all changes to an entity in the DB. Does not include modified relation collections. |
||
61 | * |
||
62 | * @param Entity $entity |
||
63 | * @return object |
||
64 | */ |
||
65 | 9 | public function save(Entity $entity) |
|
89 | /** |
||
90 | * Delete an entity from the database |
||
91 | * |
||
92 | * @param Entity $entity |
||
93 | * @return void |
||
94 | */ |
||
95 | 3 | public function delete(Entity $entity) |
|
107 | /** |
||
108 | * Refresh an entity from the DB (includes own columns and relations). |
||
109 | * |
||
110 | * @param Entity $entity |
||
111 | * @return object |
||
112 | */ |
||
113 | public function refresh(Entity $entity) |
||
124 | 33 | protected function lazy(Entity $entity, $data) |
|
125 | { |
||
126 | 33 | $primary = $entity->id(); |
|
127 | 33 | $definition = $entity->definition(); |
|
128 | 33 | foreach ($definition->getColumns() as $column) { |
|
129 | 33 | if (!array_key_exists($column, $data)) { |
|
130 | $entity->__lazyProperty($column, function () use ($definition, $primary, $column) { |
||
131 | $query = $this->db->table($definition->getName()); |
||
132 | foreach ($primary as $k => $v) { |
||
133 | $query->filter($k, $v); |
||
134 | } |
||
135 | return $query->select([$column])[0][$column] ?? null; |
||
136 | }); |
||
137 | } |
||
138 | } |
||
139 | 33 | foreach ($definition->getRelations() as $name => $relation) { |
|
140 | 33 | $entity->__lazyProperty( |
|
141 | 33 | $name, |
|
142 | 33 | array_key_exists($name, $data) && isset($data[$name]) ? |
|
143 | ($relation->many ? |
||
144 | array_map(function ($v) use ($relation) { |
||
145 | return $this->entity($relation->table, $v); |
||
146 | }, $data[$name]) : |
||
147 | $this->entity($relation->table, $data[$name]) |
||
148 | ) : |
||
149 | 33 | function (array $columns = null) use ($entity, $definition, $relation, $data) { |
|
150 | 9 | $query = $this->db->table($relation->table->getName(), true); |
|
151 | 9 | if ($columns !== null) { |
|
152 | $query->columns($columns); |
||
191 |