91 lines
2.3 KiB
PHP
Raw Normal View History

2020-04-28 16:34:17 +08:00
<?php
2020-04-28 22:02:03 +08:00
namespace catcher\generate\factory;
use catcher\exceptions\FailedException;
use catcher\generate\template\Model as Template;
use think\facade\Db;
2020-04-30 18:15:48 +08:00
use think\helper\Str;
2020-04-28 22:02:03 +08:00
class Model extends Factory
{
public function done($params)
2020-04-29 09:02:20 +08:00
{
$file = $this->getGeneratePath($params['model']);
file_put_contents($file, $this->getContent($params));
if (!file_exists($file)) {
throw new FailedException('create model failed');
}
return true;
}
/**
* get contents
*
* @time 2020年04月29日
* @param $params
* @return string|string[]
*/
public function getContent($params)
2020-04-28 22:02:03 +08:00
{
// TODO: Implement done() method.
$template = new Template();
$extra = $params['extra'];
$table = $params['table'];
[$modelName, $namespace] = $this->parseFilename($params['model']);
2020-04-30 18:15:48 +08:00
// 如果填写了表名并且没有填写模型名称 使用表名作为模型名称
if (!$modelName && $table) {
$modelName = Str::camel($table);
}
2020-04-28 22:02:03 +08:00
if (!$modelName) {
2020-04-29 11:41:54 +08:00
throw new FailedException('model name not set');
2020-04-28 22:02:03 +08:00
}
$content = $template->useTrait($extra['soft_delete']) .
2020-04-29 09:02:20 +08:00
$template->name($table) .
$template->field($this->parseField($table));
2020-04-28 22:02:03 +08:00
$class = $template->header() .
2020-04-29 09:02:20 +08:00
$template->nameSpace($namespace) .
$template->uses($extra['soft_delete']) .
$template->createModel($modelName, $table);
2020-04-28 22:02:03 +08:00
2020-04-29 09:02:20 +08:00
return str_replace('{CONTENT}', $content, $class);
2020-04-28 22:02:03 +08:00
}
/**
* parse field
*
* @time 2020年04月28日
* @param $table
* @return string
*/
protected function parseField($table)
{
2020-04-29 09:02:20 +08:00
if (!$this->hasTableExists($table)) {
return false;
}
2020-04-28 22:02:03 +08:00
$columns = Db::query('show full columns from ' .
config('database.connections.mysql.prefix') . $table);
$new = [];
foreach ($columns as $field) {
$new[$field['Field']] = $field['Comment'];
}
$fields = [];
foreach ($new as $field => $comment) {
$fields[] = sprintf("'%s', // %s", $field, $comment);
}
return implode("\r\n\t\t", $fields);
}
}