diff --git a/src/Console/Commands/Export.php b/src/Console/Commands/Export.php new file mode 100644 index 0000000..54caac3 --- /dev/null +++ b/src/Console/Commands/Export.php @@ -0,0 +1,24 @@ +argument('model'); + + $this->info('Exporting ' . $model . ' model to sync data file'); + + (new Exporter($model, $this->option('criteria'), $this->option('except'), $this->option('only')))->run(); + + $this->comment('Export for data sync completed'); + } +} diff --git a/src/DataSyncBaseServiceProvider.php b/src/DataSyncBaseServiceProvider.php index f0bc600..8932a41 100644 --- a/src/DataSyncBaseServiceProvider.php +++ b/src/DataSyncBaseServiceProvider.php @@ -17,6 +17,7 @@ class DataSyncBaseServiceProvider extends ServiceProvider { $this->commands([ Console\Commands\Sync::class, + Console\Commands\Export::class, ]); } diff --git a/src/Exporter.php b/src/Exporter.php new file mode 100644 index 0000000..f7317f0 --- /dev/null +++ b/src/Exporter.php @@ -0,0 +1,96 @@ +modelName = $modelName; + $this->criteria = $criteria; + $this->except = $except; + $this->only = $only; + } + + /** + * Export Model data to sync file. + * + * @return mixed + */ + public function run() + { + $class = config('data-sync.namespace', '\\App\\Models\\') . $this->modelName; + $filename = $this->getDirectory() . '/' . $this->modelName . '.json'; + $data = $this->prepareData($class); + + file_put_contents($filename, $data); + } + + /** + * Get directory path for sync files. + * + * @throws \nullthoughts\LaravelDataSync\Exceptions\FileDirectoryNotFoundException + * + * @return string + */ + protected function getDirectory() + { + $directory = config('data-sync.path', base_path('sync')); + + if (! file_exists($directory)) { + throw new FileDirectoryNotFoundException(); + } + + return $directory; + } + + protected function prepareData($class) + { + $class = new $class; + $keys = $this->prepareKeys($class); + + return $class->select($keys)->get()->toJson(); + } + + protected function prepareKeys($class) + { + $keys = Schema::getColumnListing($class->getTable()); + + if ($this->only) { + $keys = array_intersect($keys, $this->only); + } + + if ($this->except) { + $keys = array_diff($keys, $this->except); + } + + + return collect($keys)->map(function ($key) { + if (in_array($key, $this->criteria)) { + return $key . ' as _' . $key; + } + + return $key; + })->toArray(); + } +}