-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathHasRelations.php
More file actions
637 lines (522 loc) · 20.7 KB
/
HasRelations.php
File metadata and controls
637 lines (522 loc) · 20.7 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
<?php
declare(strict_types=1);
namespace Michalsn\CodeIgniterNestedModel\Traits;
use Closure;
use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Database\Exceptions\DataException;
use CodeIgniter\Entity\Entity;
use CodeIgniter\Model;
use LogicException;
use Michalsn\CodeIgniterNestedModel\Enums\RelationTypes;
use Michalsn\CodeIgniterNestedModel\Exceptions\NestedModelException;
use Michalsn\CodeIgniterNestedModel\Relation;
use Michalsn\CodeIgniterNestedModel\With;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use ReflectionNamedType;
trait HasRelations
{
private array $relations = [];
private array $relationErrors = [];
private bool $useTransactions = false;
/**
* Set up model events and initialize
* relation model stuff.
*/
protected function initRelations(): void
{
$this->beforeInsert[] = 'relationsBeforeInsert';
$this->afterInsert[] = 'relationsAfterInsert';
$this->beforeUpdate[] = 'relationsBeforeUpdate';
$this->afterUpdate[] = 'relationsAfterUpdate';
$this->afterFind[] = 'relationsAfterFind';
helper('inflector');
}
/**
* Set the relation to use.
*/
public function with(string $relation, ?Closure $closure = null): static
{
if (str_contains($relation, '.')) {
[$relation, $name] = explode('.', $relation, 2);
if (! isset($this->relations[$relation])) {
throw NestedModelException::forParentRelationNotDeclared($relation);
}
$this->relations[$relation]->setWith(new With($name, $closure));
return $this;
}
$this->checkReturnType($relation);
$this->{$relation}();
if ($closure !== null) {
$this->relations[$relation]->setConditions($closure);
}
return $this;
}
/**
* Transform relation IDs before using them in whereIn queries
* This method checks for relation-specific transform methods
*/
private function transformRelationIds(array $ids, string $relationName): array
{
// Check if there's a specific transform method for this relation
// e.g., transformProfileRelationIds() for 'profile' relation
$transformMethod = 'transform' . ucfirst($relationName) . 'RelationIds';
if (method_exists($this, $transformMethod)) {
return $this->{$transformMethod}($ids);
}
// Check for a general relation transform method
if (method_exists($this, 'transformAllRelationIds')) {
return $this->transformAllRelationIds($ids);
}
return $ids;
}
/**
* Validate relation definition.
*/
private function checkReturnType(string $methodName): bool
{
if (! method_exists($this, $methodName)) {
throw NestedModelException::forRelationNotDefined($methodName);
}
$reflectionMethod = new ReflectionMethod($this, $methodName);
$returnType = $reflectionMethod->getReturnType();
if (! $returnType instanceof ReflectionNamedType) {
throw NestedModelException::forMissingReturnType($methodName);
}
if ($returnType->getName() !== Relation::class) {
throw NestedModelException::forIncorrectReturnType($methodName);
}
return true;
}
/**
* @throws ReflectionException
*/
private function addRelation(Model|string $model, RelationTypes $relationType, ?string $foreignKey = null, ?string $primaryKey = null): Relation
{
$relation = $this->getInitialMethodName();
$this->allowedFields[] = $relation;
$model = $this->getModelInstance($model);
$this->relations[$relation] = new Relation(
$relationType,
$model,
$foreignKey ?? ($relationType === RelationTypes::belongsTo ? get_primary_key($model) : get_foreign_key($this)),
$primaryKey ?? ($relationType === RelationTypes::belongsTo ? get_foreign_key($model) : get_primary_key($this)),
);
// dd($this->relations[$relation]->foreignKey, $this->relations[$relation]->primaryKey);
return $this->relations[$relation];
}
/**
* @throws ReflectionException
*/
protected function hasOne(Model|string $model, ?string $foreignKey = null, ?string $primaryKey = null): Relation
{
return $this->addRelation($model, RelationTypes::hasOne, $foreignKey, $primaryKey);
}
/**
* @throws ReflectionException
*/
protected function hasMany(Model|string $model, ?string $foreignKey = null, ?string $primaryKey = null): Relation
{
return $this->addRelation($model, RelationTypes::hasMany, $foreignKey, $primaryKey);
}
/**
* @throws ReflectionException
*/
protected function belongsTo(Model|string $model, ?string $primaryKey = null, ?string $foreignKey = null): Relation
{
return $this->addRelation($model, RelationTypes::belongsTo, $foreignKey, $primaryKey);
}
/**
* @throws ReflectionException
*/
protected function hasOneThrough(
Model|string $model,
Model|string $through,
?string $throughForeignKey = null,
?string $foreignKey = null,
?string $throughPrimaryKey = null,
?string $primaryKey = null,
): Relation {
$model = $this->getModelInstance($model);
$through = $this->getModelInstance($through);
$foreignKey ??= get_foreign_key($through);
$throughForeignKey ??= get_foreign_key($model);
return $this->addRelation($model, RelationTypes::hasOne, $foreignKey, $primaryKey)
->setThrough($through, $throughForeignKey, $throughPrimaryKey);
}
/**
* @throws ReflectionException
*/
protected function hasManyThrough(
Model|string $model,
Model|string $through,
?string $throughForeignKey = null,
?string $foreignKey = null,
?string $throughPrimaryKey = null,
?string $primaryKey = null,
): Relation {
$model = $this->getModelInstance($model);
$through = $this->getModelInstance($through);
$foreignKey ??= get_foreign_key($through);
$throughForeignKey ??= get_foreign_key($model);
return $this->addRelation($model, RelationTypes::hasMany, $foreignKey, $primaryKey)
->setThrough($through, $throughForeignKey, $throughPrimaryKey);
}
public function belongsToMany(Model|string $model, ?string $pivotTable = null, ?string $pivotForeignKey = null, ?string $pivotRelatedKey = null)
{
$model = $this->getModelInstance($model);
$pivotTable ??= $this->createPivotTableName($this->table, $model->getTable());
$pivotForeignKey ??= get_foreign_key($this);
$pivotRelatedKey ??= get_foreign_key($model);
return $this->addRelation($model, RelationTypes::belongsToMany)
->setMany($pivotTable, $pivotForeignKey, $pivotRelatedKey);
}
/**
* Return model instance.
*/
private function getModelInstance(Model|string $model): Model
{
return $model instanceof Model ? $model : model($model);
}
/**
* Create pivot table name.
*/
private function createPivotTableName(mixed $table1, mixed $table2): string
{
$tables = [$table1, $table2];
sort($tables);
$tables = array_map(singular(...), $tables);
return implode('_', $tables);
}
/**
* Get the caller method name.
*
* @throws ReflectionException
*/
private function getInitialMethodName(): string
{
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
$reflectionClass = new ReflectionClass(self::class);
$classFile = $reflectionClass->getFileName();
foreach ($backtrace as $trace) {
if (isset($trace['class']) && $trace['class'] === self::class) {
$method = new ReflectionMethod($trace['class'], $trace['function']);
// Check if the method is declared in the current class, not a trait
if ($method->getFileName() !== $classFile) {
continue;
}
// Check if the return type is a Relation class
$returnType = $method->getReturnType();
if ($returnType instanceof ReflectionNamedType && $returnType->getName() === Relation::class) {
return $trace['function'];
}
}
}
throw new LogicException('No initial method with Relation return type found in the current class.');
}
/**
* Reset all relations for model
*/
private function resetRelations(): void
{
$keys = array_keys($this->relations);
$this->allowedFields = array_diff($this->allowedFields, $keys);
$this->relations = [];
}
/**
* Before insert event.
*/
protected function relationsBeforeInsert(array $eventData): array
{
foreach ($this->relations as $relationName => $relationObject) {
if (array_key_exists($relationName, $eventData['data'])) {
$relationObject->setData($eventData['data'][$relationName]);
unset($eventData['data'][$relationName]);
}
}
return $eventData;
}
/**
* After insert event.
*
* @throws ReflectionException
*/
protected function relationsAfterInsert(array $eventData): array
{
if (! $eventData['result'] || $this->relations === []) {
return $eventData;
}
foreach ($this->relations as $relationObject) {
$data = $relationObject->getData();
// Skip if data is null or empty - nothing to insert
if ($data === [null] || $data === []) {
continue;
}
foreach ($data as $row) {
$row = $this->transformDataToArray($row, 'insert');
$result = $relationObject->applyWith()->model->insert(array_merge($row, [
$relationObject->foreignKey => $eventData[$this->primaryKey],
]));
if ($result === false) {
$this->relationErrors = array_merge($this->relationErrors, $relationObject->model->errors());
$eventData['result'] = false;
return $eventData;
}
}
}
$this->resetRelations();
return $eventData;
}
/**
* Before update event.
*/
protected function relationsBeforeUpdate(array $eventData): array
{
foreach ($this->relations as $relationName => $relationObject) {
if (array_key_exists($relationName, $eventData['data'])) {
$relationObject->setData($eventData['data'][$relationName]);
unset($eventData['data'][$relationName]);
}
}
return $eventData;
}
/**
* After update event.
*
* @throws ReflectionException
*/
protected function relationsAfterUpdate(array $eventData): array
{
if (! $eventData['result'] || $this->relations === []) {
return $eventData;
}
foreach ($this->relations as $relationObject) {
$data = $relationObject->getData();
// Skip if data is null or empty - nothing to update
if ($data === [null] || $data === []) {
continue;
}
foreach ($data as $row) {
$row = $this->transformDataToArray($row, 'insert');
foreach ($eventData[$this->primaryKey] as $id) {
$query = $relationObject->applyWith()->model->where($relationObject->foreignKey, $id);
$relationObject->applyConditions();
$result = $query->save(array_merge($row, [
$relationObject->foreignKey => $id,
]));
if ($result === false) {
$this->relationErrors = array_merge($this->relationErrors, $relationObject->model->errors());
$eventData['result'] = false;
return $eventData;
}
}
}
}
$this->resetRelations();
return $eventData;
}
/**
* After find event.
*/
protected function relationsAfterFind(array $eventData): array
{
if (($eventData['data'] || $this->relations === []) === false) {
return $eventData;
}
if ($eventData['singleton']) {
if ($this->tempReturnType === 'array') {
foreach ($this->relations as $relationName => $relationObject) {
$eventData['data'][$relationName] = $this->getDataForRelationById($eventData['data'][$relationObject->primaryKey], $relationObject, $relationName);
}
} else {
foreach ($this->relations as $relationName => $relationObject) {
$relationValue = $this->getDataForRelationById($eventData['data']->{$relationObject->primaryKey}, $relationObject, $relationName);
if ($eventData['data'] instanceof Entity) {
$this->setEntityRelation($eventData['data'], $relationName, $relationValue);
} else {
$eventData['data']->{$relationName} = $relationValue;
}
}
}
} else {
foreach ($this->relations as $relationName => $relationObject) {
$ids = array_unique(array_column(
array_map(
static fn ($item) => $item instanceof Entity
? $item->toRawArray()
: $item,
$eventData['data'],
),
$relationObject->primaryKey,
));
$relationData = $this->getDataForRelationByIds($ids, $relationObject, $relationName);
foreach ($eventData['data'] as &$data) {
if ($this->tempReturnType === 'array') {
$data[$relationName] = $relationData[$data[$relationObject->primaryKey]] ?? [];
} else {
$relationValue = $relationData[$data->{$relationObject->primaryKey}] ?? [];
if ($data instanceof Entity) {
$this->setEntityRelation($data, $relationName, $relationValue);
} else {
$data->{$relationName} = $relationValue;
}
}
}
}
}
$this->resetRelations();
return $eventData;
}
/**
* Store relation data on an entity without triggering strict __set() implementations.
*/
private function setEntityRelation(Entity $entity, string $relationName, mixed $value): void
{
$setter = function (string $name, mixed $relationValue): void {
// @phpstan-ignore-next-line bound to Entity scope below
$this->attributes[$name] = $relationValue;
};
Closure::bind($setter, $entity, Entity::class)($relationName, $value);
}
/**
* Get relation data for a single item.
*/
protected function getDataForRelationById(int|string $id, Relation $relation, string $relationName)
{
$id = $this->transformRelationIds([$id], $relationName);
$relation->applyWith()->applyRelation($id, $this->primaryKey)->applyConditions();
return in_array($relation->type, [RelationTypes::hasOne, RelationTypes::belongsTo], true) ?
$relation->filterResult($relation->model->first(), $this->tempReturnType) :
$relation->filterResults($relation->model->findAll(), $this->tempReturnType);
}
/**
* Get relation data for many items.
*/
protected function getDataForRelationByIds(array $id, Relation $relation, string $relationName): array
{
// Transform the ID before applying relation
$id = $this->transformRelationIds($id, $relationName);
$relation->applyWith()->applyRelation($id, $this->primaryKey)->applyConditions();
if ($relation->type === RelationTypes::hasOne && ($ofMany = $relation->getOfMany()) !== null) {
$results = $relation->model
->select(sprintf('%s.*', $relation->model->getTable()))
->join(
sprintf(
'%s relation1',
$relation->model->getTable(),
),
sprintf(
'%s.%s = %s.%s AND %s.%s %s %s.%s',
$relation->model->getTable(),
$relation->foreignKey,
'relation1',
$relation->foreignKey,
$relation->model->getTable(),
$ofMany->getField(),
$ofMany->getOrder(),
'relation1',
$ofMany->getField(),
),
'LEFT',
)
->where('relation1.' . $relation->primaryKey)
->findAll();
} else {
$results = $relation->model->findAll();
}
$relationData = [];
$key = $relation->foreignKey;
if (in_array($relation->type, [RelationTypes::hasOne, RelationTypes::belongsTo], true)) {
foreach ($results as $row) {
$relationData[$this->tempReturnType === 'array' ? $row[$key] : $row->{$key}] = $row;
}
} else {
foreach ($results as $row) {
$arrayKey = $this->tempReturnType === 'array' ? $row[$key] : $row->{$key};
$row = $relation->filterResult($row, $this->tempReturnType);
$relationData[$arrayKey][] = $row;
}
}
return $relationData;
}
/**
* Validate if given relation can be handled during write operation.
*/
protected function validateWriteRelations(): void
{
if ($this->relations === []) {
return;
}
foreach ($this->relations as $relation) {
if (
! in_array($relation->type, [RelationTypes::hasOne, RelationTypes::hasMany], true)
|| (
in_array($relation->type, [RelationTypes::hasOne, RelationTypes::hasMany], true)
&& ($relation->hasMany() || $relation->hasThrough())
)
) {
throw NestedModelException::forRelationDoesNotSupportWrite();
}
}
}
/**
* Whether to use transaction during insert/update.
*/
public function useTransactions(bool $value = true): static
{
$this->useTransactions = $value;
return $this;
}
public function insert($row = null, bool $returnID = true): bool|int|string
{
$this->validateWriteRelations();
if ($this->useTransactions) {
try {
$this->db->transException(true)->transStart();
$result = parent::insert($row, $returnID);
if ($this->errors() !== []) {
$this->db->transRollback();
return $result;
}
$this->db->transComplete();
} catch (DatabaseException|DataException $e) {
$this->relationErrors['database_error'] = $e->getMessage();
return false;
} finally {
$this->useTransactions(false);
}
return $result;
}
return parent::insert($row, $returnID);
}
public function update($id = null, $row = null): bool
{
$this->validateWriteRelations();
if ($this->useTransactions) {
try {
$this->db->transException(true)->transStart();
$result = parent::update($id, $row);
if ($this->errors() !== []) {
$this->db->transRollback();
return $result;
}
$this->db->transComplete();
} catch (DatabaseException|DataException $e) {
$this->relationErrors['database_error'] = $e->getMessage();
return false;
} finally {
$this->useTransactions(false);
}
return $result;
}
return parent::update($id, $row);
}
public function errors(bool $forceDB = false)
{
if ($this->relationErrors !== []) {
return $this->relationErrors;
}
return parent::errors($forceDB);
}
}