From ed527ed51c6b972095b2cc254562a70dcba0620d Mon Sep 17 00:00:00 2001 From: Firman Taruna Nugraha Date: Mon, 10 Feb 2020 01:06:17 +0700 Subject: [PATCH] Add ModelTrait for more reusability --- src/Database/Eloquent/Model.php | 49 ++----------------------- src/Database/Eloquent/ModelTrait.php | 54 ++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 47 deletions(-) create mode 100644 src/Database/Eloquent/ModelTrait.php diff --git a/src/Database/Eloquent/Model.php b/src/Database/Eloquent/Model.php index aeb1c1b..6b21ef5 100644 --- a/src/Database/Eloquent/Model.php +++ b/src/Database/Eloquent/Model.php @@ -4,12 +4,12 @@ namespace GoldSpecDigital\LaravelEloquentUUID\Database\Eloquent; -use Exception; use Illuminate\Database\Eloquent\Model as BaseModel; -use Ramsey\Uuid\Uuid; abstract class Model extends BaseModel { + use ModelTrait; + /** * The "type" of the auto-incrementing ID. * @@ -17,20 +17,6 @@ abstract class Model extends BaseModel */ protected $keyType = 'string'; - /** - * Indicates if the IDs are UUIDs. - * - * @var bool - */ - protected $keyIsUuid = true; - - /** - * The UUID version to use. - * - * @var int - */ - protected $uuidVersion = 4; - /** * Indicates if the IDs are auto-incrementing. * @@ -55,35 +41,4 @@ abstract class Model extends BaseModel 'updated_at' => 'datetime', 'deleted_at' => 'datetime', ]; - - /** - * The "booting" method of the model. - */ - protected static function boot(): void - { - parent::boot(); - - static::creating(function (self $model): void { - // Automatically generate a UUID if using them, and not provided. - if ($model->keyIsUuid && empty($model->{$model->getKeyName()})) { - $model->{$model->getKeyName()} = $model->generateUuid(); - } - }); - } - - /** - * @throws \Exception - * @return string - */ - protected function generateUuid(): string - { - switch ($this->uuidVersion) { - case 1: - return Uuid::uuid1()->toString(); - case 4: - return Uuid::uuid4()->toString(); - } - - throw new Exception("UUID version [{$this->uuidVersion}] not supported."); - } } diff --git a/src/Database/Eloquent/ModelTrait.php b/src/Database/Eloquent/ModelTrait.php new file mode 100644 index 0000000..52bed3f --- /dev/null +++ b/src/Database/Eloquent/ModelTrait.php @@ -0,0 +1,54 @@ +keyIsUuid && empty($model->{$model->getKeyName()})) { + $model->{$model->getKeyName()} = $model->generateUuid(); + } + }); + } + + /** + * @throws \Exception + * @return string + */ + protected function generateUuid(): string + { + switch ($this->uuidVersion) { + case 1: + return Uuid::uuid1()->toString(); + case 4: + return Uuid::uuid4()->toString(); + } + + throw new Exception("UUID version [{$this->uuidVersion}] not supported."); + } +}