laravel-shift/blueprint

Add `HasUuids` trait when Model has `id uuid primary`

brocard opened this issue · 3 comments

Synopsis:

Model:
id: uuid primary
name: string
code: smallInteger nullable
softDeletes: true

Proposed Syntax:

class FacilityGroup extends Model { use HasFactory, SoftDeletes, HasUuids; }

This can help?

protected function addTraits(Model $model, $stub): string
    {
        if (!$model->usesSoftDeletes()) {
            return $stub;
        }

        if (
            $model->usesPrimaryKey()
            && $model->column($model->primaryKey())->dataType() === 'uuid'
        ) {
            $this->addImport($model, 'Illuminate\\Database\\Eloquent\\Concerns\\HasUuids');
            $this->addImport($model, 'Illuminate\\Database\\Eloquent\\SoftDeletes');
            return Str::replaceFirst('use HasFactory', 'use HasFactory, HasUuids, SoftDeletes', $stub);
        }

        $this->addImport($model, 'Illuminate\\Database\\Eloquent\\SoftDeletes');
        return Str::replaceFirst('use HasFactory', 'use HasFactory, SoftDeletes', $stub);
    }

or

protected function addTraits(Model $model, $stub): string
{
        $hasUuidsAsPrimaryKey = $model->usesPrimaryKey() && $model->column($model->primaryKey())->dataType() === 'uuid';

        // Add the appropriate traits based on conditions
        $traits = ['HasFactory'];
        if ($hasUuidsAsPrimaryKey) {
            $traits[] = 'HasUuids';
            $this->addImport($model, 'Illuminate\\Database\\Eloquent\\Concerns\\HasUuids');
        }
        if ($model->usesSoftDeletes()) {
            $traits[] = 'SoftDeletes';
            $this->addImport($model, 'Illuminate\\Database\\Eloquent\\SoftDeletes');
        }

        // Replace the 'use HasFactory' statement with the appropriate traits
        return Str::replaceFirst('use HasFactory', 'use ' . implode(', ', $traits), $stub);
}

Feel free to open a PR.