Skip to content

Commit 7844c20

Browse files
committed
Add StateHistory model
1 parent 5254b81 commit 7844c20

File tree

1 file changed

+97
-0
lines changed

1 file changed

+97
-0
lines changed

src/Models/StateHistory.php

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?php
2+
3+
namespace NathanDunn\StateHistory\Models;
4+
5+
use Illuminate\Database\Eloquent\Model;
6+
use Illuminate\Database\Eloquent\Relations\MorphTo;
7+
use NathanDunn\StateHistory\Support\StateMachineConfig;
8+
9+
class StateHistory extends Model
10+
{
11+
protected $table = 'state_histories';
12+
13+
protected $fillable = [
14+
'model_type',
15+
'model_id',
16+
'field',
17+
'from',
18+
'to',
19+
'meta',
20+
];
21+
22+
protected $casts = [
23+
'meta' => 'array',
24+
];
25+
26+
/**
27+
* Get the casts for this model, including dynamic ones from the related model
28+
*/
29+
public function getCasts(): array
30+
{
31+
$casts = parent::getCasts();
32+
33+
if (! data_get($this->attributes, 'field') || ! data_get($this->attributes, 'model_type') || ! data_get($this->attributes, 'model_id')) {
34+
return $casts;
35+
}
36+
37+
if (! $this->relationLoaded('model')) {
38+
return $casts;
39+
}
40+
41+
try {
42+
$relatedModel = $this->getRelation('model');
43+
44+
if (! $relatedModel || ! method_exists($relatedModel, 'stateMachine')) {
45+
return $casts;
46+
}
47+
48+
$config = $relatedModel->stateMachine();
49+
$fieldName = data_get($this->attributes, 'field');
50+
51+
if (! data_get($config, $fieldName)) {
52+
return $casts;
53+
}
54+
55+
$fieldConfig = StateMachineConfig::parse($config, $fieldName, $relatedModel);
56+
57+
if (! $fieldConfig->hasCasts()) {
58+
return $casts;
59+
}
60+
61+
$casts['from'] = $fieldConfig->getCastType('from') ?: 'string';
62+
$casts['to'] = $fieldConfig->getCastType('to') ?: 'string';
63+
64+
} catch (\Exception $e) {
65+
}
66+
67+
return $casts;
68+
}
69+
70+
/**
71+
* Get the related model instance
72+
*/
73+
public function getModelAttribute(): ?Model
74+
{
75+
if (! $this->relationLoaded('model')) {
76+
$this->load('model');
77+
}
78+
79+
return $this->getRelation('model');
80+
}
81+
82+
/**
83+
* Get the model that owns this state.
84+
*/
85+
public function model(): MorphTo
86+
{
87+
return $this->morphTo();
88+
}
89+
90+
/**
91+
* Scope to filter by field.
92+
*/
93+
public function scopeForField($query, string $field)
94+
{
95+
return $query->where('field', $field);
96+
}
97+
}

0 commit comments

Comments
 (0)