|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Kiwilan\Steward\Commands\Model; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\DB; |
| 6 | +use Illuminate\Support\Str; |
| 7 | +use Kiwilan\Steward\Commands\Commandable; |
| 8 | + |
| 9 | +class ModelBackupCommand extends Commandable |
| 10 | +{ |
| 11 | + /** |
| 12 | + * The name and signature of the console command. |
| 13 | + * |
| 14 | + * @var string |
| 15 | + */ |
| 16 | + protected $signature = 'model:backup {model : The model to backup, can be `User` or `App\Models\User`}'; |
| 17 | + |
| 18 | + /** |
| 19 | + * The console command description. |
| 20 | + * |
| 21 | + * @var string |
| 22 | + */ |
| 23 | + protected $description = 'Backup model from the database'; |
| 24 | + |
| 25 | + /** |
| 26 | + * Execute the console command. |
| 27 | + */ |
| 28 | + public function handle() |
| 29 | + { |
| 30 | + $this->title(); |
| 31 | + |
| 32 | + $modelName = (string) $this->argument('model'); |
| 33 | + |
| 34 | + $model = ModelBackupCommand::getModel($modelName); |
| 35 | + $path = ModelBackupCommand::getPath($model['filename']); |
| 36 | + |
| 37 | + if (file_exists($path)) { |
| 38 | + $contents = json_decode(file_get_contents($path), true); |
| 39 | + if (count($contents) === 0) { |
| 40 | + $this->info("{$model['name']} file is empty, deleting..."); |
| 41 | + unlink($path); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + $items = DB::table($model['instance']->getTable())->get(); |
| 46 | + $json = $items->toJson(JSON_PRETTY_PRINT); |
| 47 | + |
| 48 | + file_put_contents($path, $json); |
| 49 | + |
| 50 | + $this->info("Saved {$model['name']} to {$path}"); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @return array{name: string, filename: string, model: string, instance: \Illuminate\Database\Eloquent\Model} |
| 55 | + */ |
| 56 | + public static function getModel(string $modelName): array |
| 57 | + { |
| 58 | + if (str_contains($modelName, '\\')) { |
| 59 | + $model = $modelName; |
| 60 | + } else { |
| 61 | + $model = 'App\\Models\\'.$modelName; |
| 62 | + } |
| 63 | + |
| 64 | + $instance = new $model; |
| 65 | + $reflection = new \ReflectionClass($instance); |
| 66 | + $className = $reflection->name; |
| 67 | + $className = str_replace('\\', '_', $className); |
| 68 | + $fileName = Str::slug($className).'.json'; |
| 69 | + |
| 70 | + return [ |
| 71 | + 'name' => $reflection->name, |
| 72 | + 'model' => $model, |
| 73 | + 'filename' => $fileName, |
| 74 | + 'instance' => $instance, |
| 75 | + ]; |
| 76 | + } |
| 77 | + |
| 78 | + public static function getPath(string $filename): string |
| 79 | + { |
| 80 | + $basePath = storage_path('app'.DIRECTORY_SEPARATOR.'model-backup'); |
| 81 | + if (! is_dir($basePath)) { |
| 82 | + mkdir($basePath, 0775, true); |
| 83 | + } |
| 84 | + |
| 85 | + return $basePath.DIRECTORY_SEPARATOR.$filename; |
| 86 | + } |
| 87 | +} |
0 commit comments