diff --git a/src/Commands/Model/ModelBackupCommand.php b/src/Commands/Model/ModelBackupCommand.php new file mode 100644 index 0000000..ad446dc --- /dev/null +++ b/src/Commands/Model/ModelBackupCommand.php @@ -0,0 +1,87 @@ +title(); + + $modelName = (string) $this->argument('model'); + + $model = ModelBackupCommand::getModel($modelName); + $path = ModelBackupCommand::getPath($model['filename']); + + if (file_exists($path)) { + $contents = json_decode(file_get_contents($path), true); + if (count($contents) === 0) { + $this->info("{$model['name']} file is empty, deleting..."); + unlink($path); + } + } + + $items = DB::table($model['instance']->getTable())->get(); + $json = $items->toJson(JSON_PRETTY_PRINT); + + file_put_contents($path, $json); + + $this->info("Saved {$model['name']} to {$path}"); + } + + /** + * @return array{name: string, filename: string, model: string, instance: \Illuminate\Database\Eloquent\Model} + */ + public static function getModel(string $modelName): array + { + if (str_contains($modelName, '\\')) { + $model = $modelName; + } else { + $model = 'App\\Models\\'.$modelName; + } + + $instance = new $model; + $reflection = new \ReflectionClass($instance); + $className = $reflection->name; + $className = str_replace('\\', '_', $className); + $fileName = Str::slug($className).'.json'; + + return [ + 'name' => $reflection->name, + 'model' => $model, + 'filename' => $fileName, + 'instance' => $instance, + ]; + } + + public static function getPath(string $filename): string + { + $basePath = storage_path('app'.DIRECTORY_SEPARATOR.'model-backup'); + if (! is_dir($basePath)) { + mkdir($basePath, 0775, true); + } + + return $basePath.DIRECTORY_SEPARATOR.$filename; + } +} diff --git a/src/Commands/Model/ModelRestoreCommand.php b/src/Commands/Model/ModelRestoreCommand.php new file mode 100644 index 0000000..6c9d75e --- /dev/null +++ b/src/Commands/Model/ModelRestoreCommand.php @@ -0,0 +1,50 @@ +title(); + + $modelName = (string) $this->argument('model'); + + $model = ModelBackupCommand::getModel($modelName); + $path = ModelBackupCommand::getPath($model['filename']); + + if (! file_exists($path)) { + $this->error("{$model['name']} file does not exist"); + + return; + } + + $json = file_get_contents($path); + $items = json_decode($json, true); + + $model['instance']::query()->truncate(); + $model['instance']::query()->insert($items); + + $this->info("Restored {$model['name']} from {$path}"); + } +} diff --git a/src/StewardServiceProvider.php b/src/StewardServiceProvider.php index d6653ce..0eba714 100644 --- a/src/StewardServiceProvider.php +++ b/src/StewardServiceProvider.php @@ -42,6 +42,8 @@ public function configurePackage(Package $package): void \Kiwilan\Steward\Commands\ClearFreshCommand::class, \Kiwilan\Steward\Commands\Jobs\JobsListCommand::class, \Kiwilan\Steward\Commands\Jobs\JobsClearCommand::class, + \Kiwilan\Steward\Commands\Model\ModelBackupCommand::class, + \Kiwilan\Steward\Commands\Model\ModelRestoreCommand::class, ]); }