75 lines
2.3 KiB
PHP
75 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Models\Concerns;
|
|
|
|
use App\Models\Project;
|
|
use App\Models\ProjectTemplate;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
|
|
trait SyncsProjectTemplateOwnership
|
|
{
|
|
/** @param array<string, mixed> $options */
|
|
public function save(array $options = []): bool
|
|
{
|
|
return DB::transaction(function () use ($options): bool {
|
|
$this->syncProjectTemplateOwnership();
|
|
if ($this->getAttribute('project_id') !== null) {
|
|
$project = Project::query()->whereKey($this->getAttribute('project_id'))->lockForUpdate()->first();
|
|
if ($project?->project_template_id !== null) {
|
|
$this->setAttribute('project_template_id', $project->project_template_id);
|
|
}
|
|
}
|
|
|
|
return parent::save($options);
|
|
}, 3);
|
|
}
|
|
|
|
public function delete(): ?bool
|
|
{
|
|
return DB::transaction(function (): ?bool {
|
|
if ($this->getAttribute('project_id') !== null) {
|
|
Project::query()->whereKey($this->getAttribute('project_id'))->lockForUpdate()->first();
|
|
}
|
|
|
|
return parent::delete();
|
|
}, 3);
|
|
}
|
|
|
|
protected function syncProjectTemplateOwnership(): void
|
|
{
|
|
if ($this->getAttribute('configuration_key') === null) {
|
|
$this->setAttribute('configuration_key', (string) Str::uuid());
|
|
}
|
|
|
|
$projectTemplateId = $this->getAttribute('project_template_id');
|
|
$projectId = $this->getAttribute('project_id');
|
|
|
|
if ($projectTemplateId === null && $projectId !== null) {
|
|
$projectTemplateId = Project::query()
|
|
->whereKey($projectId)
|
|
->value('project_template_id');
|
|
|
|
if ($projectTemplateId !== null) {
|
|
$this->setAttribute('project_template_id', $projectTemplateId);
|
|
}
|
|
}
|
|
|
|
if ($projectId === null && $projectTemplateId !== null) {
|
|
$projectId = ProjectTemplate::query()
|
|
->whereKey($projectTemplateId)
|
|
->value('project_id');
|
|
|
|
if ($projectId !== null) {
|
|
$this->setAttribute('project_id', $projectId);
|
|
}
|
|
}
|
|
}
|
|
|
|
public function projectTemplate(): BelongsTo
|
|
{
|
|
return $this->belongsTo(ProjectTemplate::class);
|
|
}
|
|
}
|