Files
core/app/Console/Commands/Modules/CreateMigration.php
T

107 lines
3.0 KiB
PHP

<?php
namespace App\Console\Commands\Modules;
use App\Models\Module;
use Illuminate\Console\Command;
class CreateMigration extends Command
{
/**
* The name and signature of the console command.
* @var string
*/
protected $signature = 'module:make-migration {module?} {name?} {--t|table= : Table name} {--c|create : Use template for creating new table}';
/**
* The console command description.
* @var string
*/
protected $description = 'Make new migration for given module';
protected $migrationName;
protected $tableName;
protected $moduleName;
/**
* Execute the console command.
*/
public function handle()
{
$this->moduleName = $module = $this->argument('module');
$this->migrationName = $name = $this->argument('name');
$this->tableName = trim($this->option('table'), ' =');
$modules = Module::where('enabled', true)
->get()
->pluck('static_name', 'id')
->toArray();
while (is_null($module) || !in_array($module, $modules)) {
$module = $this->anticipate('Input valid module name', $modules);
}
$selectedModule = Module::where('static_name', $module)
->first();
$basePath = $selectedModule->is_template ? config('modules.path.template') : config('modules.paths.modules');
$path = $basePath . '/' . $module . '/Database/Migrations/';
if (!is_dir($path)) {
mkdir($path, 0777, true);
}
while (is_null($name)) {
$this->migrationName = $name = $this->ask('Input migration name');
}
$stubName = $this->option('create') ? 'create' : 'new';
$content = file_get_contents(config('modules.paths.stubs') . '/Migrations/' . $stubName . '.stub');
$content = $this->replacePlaceholders($content);
$migrationName = $path . $this->getMigrationName($name);
file_put_contents($migrationName, $content);
$this->line('Migration successfully created.', 'info');
}
/**
* Find and replace all placeholders in given content
*
* @param $content
*
* @return mixed
*/
private function replacePlaceholders($content)
{
$replace = [
'$MigrationName$' => studly_case($this->migrationName),
'$ModuleName$' => $this->moduleName,
'$TableName$' => $this->tableName
];
foreach ($replace as $what => $for) {
$content = str_replace($what, $for, $content);
}
return $content;
}
/**
* Get prefix for created migration
* @return false|string
*/
protected function getDatePrefix()
{
return date('Y_m_d_His');
}
/**
* @param $name
*
* @return string
*/
private function getMigrationName($name)
{
return $this->getDatePrefix() . '_' . snake_case($name) . '.php';
}
}