['services' => ['model' => App\Models\Service::class, 'view' => 'services.view', 'restore' => 'services.manage']] */ final class Revisions { /** How many states are kept per record unless config `manager.revisions.keep` says otherwise. */ private const KEEP = 50; /** * What has a history: key => model, the permissions to see and to put back, the attributes that are not part of it (for a * post that is whether it is on the site: going back in time must not publish or hide anything). * * @return array, view: string, restore: string, except: list}> */ public static function types(): array { $types = [ 'posts' => ['model' => Post::class, 'view' => 'posts.view', 'restore' => 'posts.write', 'except' => ['published_at']], 'pages' => ['model' => Page::class, 'view' => 'pages.edit', 'restore' => 'pages.edit', 'except' => ['is_published']], ]; foreach ((array) config('manager.revisions.types', []) as $key => $type) { if (is_string($key) && preg_match('/^[a-z][a-z0-9_]{0,39}$/', $key) && is_array($type) && is_subclass_of($type['model'] ?? '', Eloquent::class)) { $types[$key] = ['model' => $type['model'], 'view' => (string) ($type['view'] ?? $key.'.view'), 'restore' => (string) ($type['restore'] ?? $key.'.manage'), 'except' => array_values((array) ($type['except'] ?? []))]; } } return array_filter($types, fn (array $type) => ! in_array($type['model'], (array) config('manager.revisions.skip', []), true)); } /** Starts keeping the history of every type: a save of a record writes its state, a delete removes its history. */ public static function listen(): void { foreach (self::types() as $key => $type) { $type['model']::saved(fn (Eloquent $model) => self::record($key, $model)); $type['model']::deleted(fn (Eloquent $model) => Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->delete()); } } public static function record(string $key, Eloquent $model): ?Revision { $type = self::types()[$key] ?? null; if ($type === null || ! $model->getKey()) { return null; } $data = self::snapshot($model, $type['except']); $latest = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->first(); if ($latest !== null && $latest->data == $data) { return null; } $user = auth()->user(); $revision = Revision::query()->create([ 'type' => $key, 'subject_id' => $model->getKey(), 'user_id' => $user?->getAuthIdentifier(), 'user_name' => $user === null ? null : mb_substr((string) ($user->name ?? ''), 0, 255), 'data' => $data, 'changed' => $latest === null ? array_keys($data) : self::changed((array) $latest->data, $data), 'created_at' => now(), ]); // Keep the newest ones only. $old = Revision::query()->where('type', $key)->where('subject_id', $model->getKey())->orderByDesc('id')->skip(max(5, (int) config('manager.revisions.keep', self::KEEP)))->take(1000)->pluck('id'); $old->isNotEmpty() && Revision::query()->whereKey($old)->delete(); return $revision; } /** * Puts a state back. It is a save like any other, so the history shows it and the state before it is not lost. * * @param array{except: list} $type */ public static function restore(Eloquent $model, Revision $revision, array $type): Eloquent { $keep = array_flip([...$type['except'], $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]); $model->forceFill(array_diff_key((array) $revision->data, $keep))->save(); return $model; } /** * @param list $except * @return array */ private static function snapshot(Eloquent $model, array $except): array { $skip = array_flip([...$except, $model->getKeyName(), $model->getCreatedAtColumn(), $model->getUpdatedAtColumn()]); return array_diff_key($model->attributesToArray(), $skip); } /** * @param array $before * @param array $after * @return list */ private static function changed(array $before, array $after): array { return array_values(array_filter(array_keys($after + $before), fn ($key) => ($before[$key] ?? null) != ($after[$key] ?? null))); } }