Skip to content

Commit 780b53e

Browse files
author
Admin
committed
Improve Active Record Segregation Properties
1 parent 2f6a55b commit 780b53e

File tree

1 file changed

+26
-10
lines changed

1 file changed

+26
-10
lines changed

src/Models/BaseModel.php

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@ abstract class BaseModel extends Model
3232
public static $snakeAttributes = false;
3333
public BaseModelAttributes $a;
3434
public BaseModelRelations $r;
35+
protected const A = 'a';
36+
protected const R = 'r';
37+
/**
38+
* @var array<string, <string, string>>
39+
*/
40+
protected static array $activeRecordFqnSegregationPropertiesFqnsMap = [];
3541
protected bool $returnNullOnInvalidColumnAttributeAccess = true;
3642
protected array $ignoreUpdateFor = [];
3743
protected array $ignoreExternalCreateFor = [];
@@ -51,7 +57,7 @@ public function __construct(array $attributes = [])
5157

5258
$this->initializeActiveRecordSegregationProperties();
5359

54-
$this->append('primary_key_identifier');
60+
$this->appends[] = 'primary_key_identifier';
5561
}
5662

5763
public static function resourceName(): string
@@ -435,20 +441,30 @@ protected function incrementOrDecrement($column, $amount, $extra, $method): int
435441
*/
436442
protected function initializeActiveRecordSegregationProperties(): void
437443
{
438-
$prefix = \substr($class = static::class, 0, $l = (-1 * (\strlen($class) - \strrpos($class, '\\') - 1))) .
444+
$class = static::class;
445+
446+
if (isset(self::$activeRecordFqnSegregationPropertiesFqnsMap[$class])) {
447+
$this->a = new (self::$activeRecordFqnSegregationPropertiesFqnsMap[$class][self::A])($this);
448+
$this->r = new (self::$activeRecordFqnSegregationPropertiesFqnsMap[$class][self::R])($this);
449+
450+
return;
451+
}
452+
453+
$prefix = \substr($class, 0, $l = (-1 * (\strlen($class) - \strrpos($class, '\\') - 1))) .
439454
'Attributes\\' . \substr($class, $l);
440455

441-
foreach (
442-
[
443-
'a' => ['p' => 'Attributes', 'c' => BaseModelAttributes::class],
444-
'r' => ['p' => 'Relations', 'c' => BaseModelRelations::class]
445-
] as $p => $propertyMap
446-
) {
456+
foreach ([self::A => 'Attributes', self::R => 'Relations'] as $property => $postfix) {
447457
try {
448-
$this->$p = new ($prefix . $this->$propertyMap['p'])($this);
458+
$this->$property = new ($classFqn = $prefix . $this->$postfix)($this);
449459
} catch (\Throwable) {
450-
$this->$p = new ($this->$propertyMap['c'])($this);
460+
$this->$property =
461+
new ($classFqn = 'MacropaySolutions\LaravelCrudWizard\Models\Attributes\BaseModel' .
462+
$this->$postfix)(
463+
$this
464+
);
451465
}
466+
467+
self::$activeRecordFqnSegregationPropertiesFqnsMap[$class][$property] = $classFqn;
452468
}
453469
}
454470
}

0 commit comments

Comments
 (0)