|
<?php |
|
|
|
namespace App\Console\Commands; |
|
|
|
use Illuminate\Console\Command; |
|
use Illuminate\Support\Facades\DB; |
|
use Illuminate\Support\Str; |
|
|
|
class SetModelAttributes extends Command |
|
{ |
|
/** |
|
* The name and signature of the console command. |
|
* |
|
* @var string |
|
*/ |
|
protected $signature = 'set:model {model}'; |
|
|
|
/** |
|
* The console command description. |
|
* |
|
* @var string |
|
*/ |
|
protected $description = 'Generate model object attribute fill'; |
|
|
|
/** |
|
* Execute the console command. |
|
* |
|
* @return int |
|
*/ |
|
public function handle() |
|
{ |
|
$name = $this->argument('model'); |
|
$model = '\App\Models\\' . Str::camel($name); |
|
|
|
$nsModel = new $model(); |
|
$table = $nsModel->getTable(); |
|
|
|
$results = DB::select('SHOW COLUMNS FROM ' . $table); |
|
|
|
$var = '$' . Str::camel($name); |
|
|
|
$output = $var . ' = new ' . Str::ucfirst($name) . '();' . PHP_EOL; |
|
foreach ($results as $result) { |
|
$defaultValueForType = $this->getDefaultValueForType($result->Field, $result->Type); |
|
if (is_null($defaultValueForType)) { |
|
continue; |
|
} |
|
|
|
$output .= $var . '->' . $result->Field |
|
. ' = ' |
|
. $defaultValueForType . PHP_EOL; |
|
} |
|
|
|
echo $output, PHP_EOL; |
|
|
|
return 0; |
|
} |
|
|
|
protected function getDefaultValueForType(string $field, string $type) |
|
{ |
|
if (in_array($field, ['created_at', 'updated_at'])) { |
|
return null; |
|
} |
|
|
|
if (in_array($field, ['id'])) { |
|
return null; |
|
} |
|
|
|
if ($type === 'timestamp') { |
|
return 'now();'; |
|
} |
|
|
|
if (Str::contains($type, ['char', 'var', 'text'])) { |
|
return '"";'; |
|
} |
|
|
|
if (Str::contains($type, ['int', 'double', 'float'])) { |
|
return '0;'; |
|
} |
|
|
|
return null; |
|
} |
|
} |
using Schema::getColumnListing($table) instead of DB::select('SHOW COLUMNS FROM ' . $table) allow to access to columns in other databases like postgresql
thanks anyway, super handy