Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support non backed enum & php 8.1 #1110

Merged
merged 11 commits into from
Nov 10, 2022
4 changes: 4 additions & 0 deletions src/ActivityLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,10 @@ public function withProperties(mixed $properties): static

public function withProperty(string $key, mixed $value): static
{
if (is_object($value) && function_exists('enum_exists') && enum_exists(get_class($value))) {
$value = $value->value ?? $value->name;
}

$this->getActivity()->properties = $this->getActivity()->properties->put($key, $value);

return $this;
Expand Down
4 changes: 4 additions & 0 deletions src/Traits/LogsActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,10 @@ public static function logChanges(Model $model): array
if ($model->hasCast($attribute)) {
$cast = $model->getCasts()[$attribute];

if (function_exists('enum_exists') && enum_exists($cast)) {
$changes[$attribute] = $model->getStorableEnumValue($changes[$attribute]);
}

if ($model->isCustomDateTimeCast($cast) || $model->isImmutableCustomDateTimeCast($cast)) {
$changes[$attribute] = $model->asDateTime($changes[$attribute])->format(explode(':', $cast, 2)[1]);
}
Expand Down
17 changes: 17 additions & 0 deletions tests/AbleStoreNonBackedEnumTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Spatie\Activitylog\Test;

use Spatie\Activitylog\Test\Enum\NonBackedEnum;
use Spatie\Activitylog\Test\Models\Activity;
use Spatie\Activitylog\Test\Models\User;

it('can store non backed enum', function () {
$description = 'ROLE LOG';

activity()
->performedOn(User::first())
->withProperty('role', NonBackedEnum::User)->log($description);
Gummibeer marked this conversation as resolved.
Show resolved Hide resolved

expect(Activity::query()->latest()->first()->description)->toEqual($description);
});
10 changes: 10 additions & 0 deletions tests/Enum/NonBackedEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Spatie\Activitylog\Test\Enum;

enum NonBackedEnum
{
case Admin;

case User;
}