From 2ea2bb17334b5a030113be5bd04c0888f6a68cac Mon Sep 17 00:00:00 2001 From: Quentin Gabriele Date: Sat, 21 Sep 2024 15:30:03 +0200 Subject: [PATCH] add type column --- .../create_workflows_table.php.stub | 3 +++ src/Concerns/HasWorkflows.php | 17 +++++++++++++++++ src/Models/Workflow.php | 19 ++++++++----------- tests/Feature/WorkflowDefinitionTest.php | 2 ++ 4 files changed, 30 insertions(+), 11 deletions(-) create mode 100644 src/Concerns/HasWorkflows.php diff --git a/database/migrations/create_workflows_table.php.stub b/database/migrations/create_workflows_table.php.stub index 86a66c2..73b71ef 100644 --- a/database/migrations/create_workflows_table.php.stub +++ b/database/migrations/create_workflows_table.php.stub @@ -11,6 +11,9 @@ return new class extends Migration Schema::create('workflows', function (Blueprint $table) { $table->id(); + // definition class + $table->string('type')->index(); + // serialized class $table->longText('definition'); diff --git a/src/Concerns/HasWorkflows.php b/src/Concerns/HasWorkflows.php new file mode 100644 index 0000000..4cb86bb --- /dev/null +++ b/src/Concerns/HasWorkflows.php @@ -0,0 +1,17 @@ + + */ + public function workflows(): MorphMany + { + return $this->morphMany(Workflow::class, 'model'); + } +} diff --git a/src/Models/Workflow.php b/src/Models/Workflow.php index 0b82855..a68e182 100644 --- a/src/Models/Workflow.php +++ b/src/Models/Workflow.php @@ -15,6 +15,7 @@ /** * @property int $id + * @property string $type Definition class * @property ?string $step * @property WorkflowDefinition $definition Serialized Workflow definition * @property Collection $items @@ -69,12 +70,12 @@ public function model(): MorphTo } /** - * @return Attribute + * @return Attribute */ protected function definition(): Attribute { return Attribute::make( - get: function ($value) { + get: function (mixed $value) { if (is_string($value)) { return unserialize($value); } @@ -84,15 +85,11 @@ protected function definition(): Attribute return null; }, - set: function ($value) { - if (is_string($value)) { - return $value; - } - if ($value instanceof WorkflowDefinition) { - return serialize($value); - } - - return null; + set: function (WorkflowDefinition $value) { + return [ + 'definition' => serialize($value), + 'type' => $value::class, + ]; }, ); } diff --git a/tests/Feature/WorkflowDefinitionTest.php b/tests/Feature/WorkflowDefinitionTest.php index 218425c..8334c1c 100644 --- a/tests/Feature/WorkflowDefinitionTest.php +++ b/tests/Feature/WorkflowDefinitionTest.php @@ -9,6 +9,8 @@ $workflow = $definition->start(); + expect($workflow->type)->toBe(TestWorkflowDefinition::class); + expect($workflow->definition)->toBeInstanceOf(TestWorkflowDefinition::class); expect($workflow->exists)->toBe(true); expect($workflow->items)->toHaveLength(2);