Skip to content

Commit

Permalink
Merge pull request #102 from vinlim/feature/configurable-status-attri…
Browse files Browse the repository at this point in the history
…bute

Feature/configurable status attribute
  • Loading branch information
freekmurze authored May 17, 2023
2 parents e81d1a3 + 17fa416 commit b1a7def
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 5 deletions.
7 changes: 7 additions & 0 deletions config/model-status.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@
*/
'status_model' => Spatie\ModelStatus\Status::class,

/*
* The name of the attribute to access the latest status.
*
* You can change this value if you have need a custom status attribute.
*/
'status_attribute' => 'status',

/*
* The name of the column which holds the ID of the model related to the statuses.
*
Expand Down
24 changes: 19 additions & 5 deletions src/HasStatuses.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,6 @@ function (QueryBuilder $query) use ($names) {
->orWhereDoesntHave('statuses');
}

public function getStatusAttribute(): string
{
return (string) $this->latestStatus();
}

public function forceSetStatus(string $name, ?string $reason = null): self
{
$oldStatus = $this->latestStatus();
Expand Down Expand Up @@ -160,8 +155,27 @@ protected function getStatusModelClassName(): string
return config('model-status.status_model');
}

protected function getStatusAttributeName(): string
{
return config('model-status.status_attribute') ?? 'status';
}

protected function getStatusModelType(): string
{
return array_search(static::class, Relation::morphMap()) ?: static::class;
}

/**
* @param string $key
*
* @return mixed
*/
public function __get($key): mixed
{
if ($key === $this->getStatusAttributeName()) {
return (string) $this->latestStatus();
}

return parent::__get($key);
}
}
11 changes: 11 additions & 0 deletions tests/HasStatusesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,17 @@
->and($this->testModel->status()->reason)->toEqual('waiting for a change');
});

it('can handle a different status attribute', function () {
$this->testModel
->setStatus('free')
->setStatus('pending', 'waiting for a change');

config()->set('model-status.status_attribute', 'alternative_status');

expect($this->testModel->alternative_status)
->toEqual('pending');
});

it('can find all models that do not have a status with a given name', function () {
$model1 = TestModel::create(['name' => 'model1']);
$model2 = TestModel::create(['name' => 'model2']);
Expand Down

0 comments on commit b1a7def

Please sign in to comment.