<?php namespace App\Commands ;
use CodeIgniter\CLI\BaseCommand ;
use CodeIgniter\CLI\CLI ;
class CreateModel extends BaseCommand {
protected $group = 'Create' ;
protected $name = 'create:model' ;
protected $description = 'Création d’un fichier app/Models/XxxxModel.php, arguments : model_name , table_name[=model_name]' ;
protected $usage = 'php spark create:model [model_name] ?[table_name]' ;
protected $arguments = [
'model_name' => 'le nom du model' ,
'table_name' => 'le nom de la table sans le préfixe, optionnel si le nom de la table est différent du nom du model'
] ;
protected $options = [] ;
public function run(array $params){
if( ! is_array($params) OR ! isset($params[0])){
CLI::error('argument model_name manquant') ;
CLI::newLine() ;
return false ;
}
helper('inflector');
$model_name = pascalize($params[0].'_model') ;
$model_filename = $model_name ;
$table_name = (isset($params[1])) ? $params[1] : $params[0] ;
# on verifie si la table existe
$db = \Config\Database::connect() ;
$table_exists = $db->tableExists($table_name) ;
if( ! $table_exists){
CLI::error('la table '.$table_name.' n’existe pas encore dans la base de données') ;
CLI::newLine() ;
return false ;
}
$fields = $db->getFieldData($table_name) ;
$fields_names = array_column($fields,'name') ;
$primary_key = CLI::prompt('Primary Key ?', $fields_names) ;
$return_type = CLI::prompt('Return Type ? (array | object | __EntityClassName__)',null, 'required') ;
$file_content = "<?php namespace App\Models ;".PHP_EOL
."use CodeIgniter\Model ;".PHP_EOL
."class ".$model_name." extends Model {".PHP_EOL ;
$file_content .= "}".PHP_EOL ;
CLI::write($file_content) ;
}
}