Implement Propable trait in Brand, Category, Product, and Tenant models to manage properties; remove unused code in Tenant model.
This commit is contained in:
94
app/Domains/Prop/Concerns/Propable.php
Normal file
94
app/Domains/Prop/Concerns/Propable.php
Normal file
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Prop\Concerns;
|
||||
|
||||
use App\Domains\Prop\Models\ModelPropValue;
|
||||
use App\Domains\Prop\Models\Prop;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use LogicException;
|
||||
|
||||
trait Propable
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
public static function createProp(array $attributes): Prop
|
||||
{
|
||||
return Prop::query()->create([
|
||||
...$attributes,
|
||||
'propable_type' => static::class,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Builder<Prop>
|
||||
*/
|
||||
public function props(): Builder
|
||||
{
|
||||
return Prop::query()->forModel(static::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<ModelPropValue, $this>
|
||||
*/
|
||||
public function propValues(): HasMany
|
||||
{
|
||||
return $this->hasMany(ModelPropValue::class, 'valuable_id')
|
||||
->whereHas('prop', fn (Builder $query) => $query->forModel(static::class));
|
||||
}
|
||||
|
||||
public function getPropValue(Prop|string $prop): ?ModelPropValue
|
||||
{
|
||||
$resolvedProp = $this->resolveProp($prop);
|
||||
|
||||
return $this->propValues()
|
||||
->where('prop_id', $resolvedProp->getKey())
|
||||
->first();
|
||||
}
|
||||
|
||||
public function setPropValue(Prop|string $prop, mixed $value): ModelPropValue
|
||||
{
|
||||
$this->ensurePropValuesCanBeManaged();
|
||||
|
||||
$resolvedProp = $this->resolveProp($prop);
|
||||
|
||||
return $this->propValues()->updateOrCreate(
|
||||
['prop_id' => $resolvedProp->getKey()],
|
||||
['value' => $value],
|
||||
);
|
||||
}
|
||||
|
||||
public function deletePropValue(Prop|string $prop): bool
|
||||
{
|
||||
$resolvedProp = $this->resolveProp($prop);
|
||||
|
||||
return $this->propValues()
|
||||
->where('prop_id', $resolvedProp->getKey())
|
||||
->delete() > 0;
|
||||
}
|
||||
|
||||
protected function ensurePropValuesCanBeManaged(): void
|
||||
{
|
||||
if (! $this->exists) {
|
||||
throw new LogicException('Cannot manage prop values for an unsaved model.');
|
||||
}
|
||||
}
|
||||
|
||||
protected function resolveProp(Prop|string $prop): Prop
|
||||
{
|
||||
if ($prop instanceof Prop) {
|
||||
if ($prop->propable_type !== static::class) {
|
||||
throw new LogicException('The given prop does not belong to this model type.');
|
||||
}
|
||||
|
||||
return $prop;
|
||||
}
|
||||
|
||||
return Prop::query()
|
||||
->forModel(static::class)
|
||||
->where('codigo', $prop)
|
||||
->firstOrFail();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user