Repository navigation
Expand file tree
/
Copy pathEntityModel.php
More file actions
365 lines (308 loc) · 8.78 KB
/
Copy pathEntityModel.php
File metadata and controls
365 lines (308 loc) · 8.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<?php
namespace SyncEngine\Model\Abstract;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use SyncEngine\Controller\DefaultController;
use SyncEngine\Exception\InvalidConfigException;
use SyncEngine\Exception\InvalidParameterException;
use SyncEngine\Exception\NotFoundException;
use SyncEngine\Model\Interface\Configurable;
use SyncEngine\Model\Interface\Persistable;
use SyncEngine\Model\Interface\Supervisable;
use SyncEngine\Repository\Interface\Searchable;
use SyncEngine\Service\ModelNormalizer;
/**
* @template T of object
*
* @method int|null getId()
*/
abstract class EntityModel extends AbstractModel implements Persistable
{
/**
* @var T
*/
protected object $entity;
/**
* @throws \Exception
*
* @param T|null $entity
*/
public function __construct( ?object $entity = null )
{
$class = static::getEntityClass();
if ( $entity ) {
if ( ! $entity instanceof $class ) {
throw new InvalidParameterException( 'Wrong entity type.' );
}
$this->entity = $entity;
}
parent::__construct();
}
public function hasEntity( bool $isPersisted = false ): bool
{
if ( $isPersisted ) {
return ! empty( $this->entity ) && $this->entity->getId();
}
return ! empty( $this->entity );
}
/**
* @return T|null
*/
public function getEntity(): ?object
{
return $this->entity ?? null;
}
public function validate(): bool
{
// Create ref if not set yet.
if ( method_exists( $this, 'createRef' ) ) {
$this->createRef( false );
}
if ( method_exists( $this, 'getRef' ) ) {
if ( str_contains( $this->getRef(), '.' ) ) {
throw new InvalidConfigException( 'Ref cannot contain dots(.)' );
}
}
if ( $this instanceof Configurable ) {
// Refresh config.
$this->setConfig( $this->entity->getConfig() );
// Any custom config parser methods.
if ( method_exists( $this, 'parseConfig' ) ) {
$this->parseConfig();
}
// Create dependency array from config.
if ( method_exists( $this, 'fetchConfigDependencies' ) ) {
$this->fetchConfigDependencies();
}
}
if ( $this instanceof Supervisable ) {
$this->runSupervisorValidate();
}
return true;
}
/**
* Update existing entity.
*
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws NotFoundException
*
* @param bool $flush
* @param EntityManagerInterface|null $entityManager
*
* @return void
*/
public function update( $flush = false, ?EntityManagerInterface $entityManager = null ): void
{
if ( ! $this->entity->getId() ) {
throw new NotFoundException( 'Cannot update entity that does not yet exist.' );
}
$this->save( $flush, $entityManager );
}
/**
* Save and validate entity.
*
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*
* @param bool $flush
* @param EntityManagerInterface|null $entityManager
*
* @return void
*/
public function save( $flush = false, ?EntityManagerInterface $entityManager = null ): void
{
$success = $this->validate();
if ( $success ) {
$this->persist( $flush, $entityManager );
}
}
/**
* Update entity without validating and parsing its data.
* This should NEVER be used when there is new user input involved!
*
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*
* @param bool $flush
* @param EntityManagerInterface|null $entityManager
*
* @return void
*/
public function persist( $flush = false, ?EntityManagerInterface $entityManager = null ): void
{
if ( ! $entityManager ) {
$entityManager = $this->getContainer()->get( 'entitymanager' );
}
$entityManager->persist( $this->entity );
if ( $flush ) {
$entityManager->flush();
}
}
/**
* Remove entity.
*
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*
* @param bool $flush
* @param EntityManagerInterface|null $entityManager
*
* @return bool
*/
public function delete( $flush = false, ?EntityManagerInterface $entityManager = null ): bool
{
if ( ! $this->hasEntity() ) {
return false; // @todo Or return true?
}
if ( ! $entityManager ) {
$entityManager = $this->getContainer()->get( 'entitymanager' );
}
$entityManager->remove( $this->entity );
if ( $flush ) {
$entityManager->flush();
}
return true;
}
public function normalize( $dependencies = false, $dependents = false ): array
{
return $this->getContainer()->get( ModelNormalizer::class )->normalize( $this, $dependencies, $dependents );
}
public function __call( string $name, array $arguments )
{
if ( ! isset( $this->entity ) || ! is_callable( [ $this->entity, $name ] ) ) {
throw new \ErrorException( 'Method not found: ' . __CLASS__ . '::' . $name );
}
return call_user_func_array( [ $this->entity, $name ], $arguments );
}
/**
* @param T|null $entity
*/
public static function create( ?object $entity = null ): static
{
if ( ! $entity ) {
$class = static::getEntityClass();
$entity = new $class();
}
return new static( $entity );
}
public static function get( $entity, $type = null ): ?static
{
if ( $entity instanceof static ) {
return $entity;
}
if ( ! $entity ) {
return null;
}
if ( $type ) {
$model = static::getEntityModelClass( ucfirst( $type ) );
if ( class_exists( $model ) ) {
// @todo is the iterable check even needed?
return $model::get( is_iterable( $entity ) ? $entity['id'] ?? $entity['ref'] ?? $entity : $entity );
}
}
if ( is_object( $entity ) && self::getEntityRealClass( $entity ) === static::getEntityClass() ) {
return static::create( $entity );
}
$repository = static::getRepository();
if ( is_numeric( $entity ) ) {
$entity = $repository->findOneBy( [ 'id' => $entity ] );
} elseif ( is_string( $entity ) ) {
$entity = $repository->findOneBy( [ 'ref' => $entity ] );
} else {
// Only keep valid columns for get query.
$props = array_map( fn($i) => $i->name, ( new \ReflectionClass( static::getEntityClass() ) )->getProperties() );
$entity = array_intersect_key( $entity, array_flip( $props ) );
if ( ! empty( $entity ) ) {
$entity = $repository->findOneBy( $entity );
}
}
return ( $entity ) ? static::create( $entity ) : null;
}
/**
* @throws \Exception
*
* @param array $query
* @todo Move getAll() to a dedicated query object/value type.
*
* @return static[]
*/
public static function getAll( array $query = [] ): array
{
if ( empty( static::getEntityClass() ) ) {
return [];
}
$repository = static::getRepository();
if ( $query ) {
$order = $query['orderBy'] ?? $query['order'] ?? $query['sort'] ?? null;
$limit = $query['limit'] ?? $query['max'] ?? null;
$offset = $query['offset'] ?? null;
$where = $query['where'] ?? [];
if ( ! empty( $query['search'] ) && $repository instanceof Searchable ) {
$search = $query['search'];
if ( ! is_array( $search ) ) {
$search = array( 'name' => $search );
}
$entities = $repository->searchBy( $search, $where, $order, $limit, $offset );
} else {
$entities = $repository->findBy( $where, $order, $limit, $offset );
}
} else {
$entities = $repository->findAll();
}
$models = [];
foreach ( $entities as $entity ) {
$models[] = static::create( $entity );
}
return $models;
}
public static function getTotalCount( array $query = [] ): int
{
if ( empty( static::getEntityClass() ) ) {
return 0;
}
$repository = static::getRepository();
return $repository->count( $query['where'] ?? [] );
}
/**
* @return EntityRepository<T>
*/
public static function getRepository( ?EntityManagerInterface $entityManager = null ): EntityRepository
{
if ( ! $entityManager ) {
$entityManager = DefaultController::getEntityManager();
}
return $entityManager->getRepository( static::getEntityClass() );
}
public static function getEntityModelClass( $entity ): ?string
{
if ( is_object( $entity ) ) {
$entity = self::getEntityReflection( $entity )->getShortName();
}
return static::getModelClass( $entity );
}
/**
* @param class-string|object $entity
*/
public static function getEntityReflection( string|object $entity ): \ReflectionClass
{
if ( is_object( $entity ) ) {
$entity = get_class( $entity );
}
return DefaultController::getEntityManager()->getClassMetadata( $entity )->getReflectionClass();
}
/**
* @param class-string|object $entity
*/
public static function getEntityRealClass( string|object $entity ): string
{
if ( is_object( $entity ) ) {
$entity = get_class( $entity );
}
return DefaultController::getEntityManager()->getClassMetadata( $entity )->getName();
}
/**
* @return class-string<T>
*/
abstract public static function getEntityClass(): string;
}