Skip to content

Commit

Permalink
add type column
Browse files Browse the repository at this point in the history
  • Loading branch information
QuentinGab committed Sep 21, 2024
1 parent fc0b774 commit 2ea2bb1
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 11 deletions.
3 changes: 3 additions & 0 deletions database/migrations/create_workflows_table.php.stub
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down
17 changes: 17 additions & 0 deletions src/Concerns/HasWorkflows.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Elegantly\Workflow\Concerns;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;

trait HasWorkflows
{
/**
* @return MorphMany<Workflow, Model>
*/
public function workflows(): MorphMany
{
return $this->morphMany(Workflow::class, 'model');
}
}
19 changes: 8 additions & 11 deletions src/Models/Workflow.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

/**
* @property int $id
* @property string $type Definition class
* @property ?string $step
* @property WorkflowDefinition $definition Serialized Workflow definition
* @property Collection<int, WorkflowItem> $items
Expand Down Expand Up @@ -69,12 +70,12 @@ public function model(): MorphTo
}

/**
* @return Attribute<WorkflowDefinition, WorkflowDefinition|string>
* @return Attribute<WorkflowDefinition, WorkflowDefinition>
*/
protected function definition(): Attribute
{
return Attribute::make(
get: function ($value) {
get: function (mixed $value) {
if (is_string($value)) {
return unserialize($value);
}
Expand All @@ -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,
];
},
);
}
Expand Down
2 changes: 2 additions & 0 deletions tests/Feature/WorkflowDefinitionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down

0 comments on commit 2ea2bb1

Please sign in to comment.