Skip to content

Commit

Permalink
feat:controller 自动生成 trait ,剥离部分代码到 trait 中
Browse files Browse the repository at this point in the history
  • Loading branch information
Charsen committed May 26, 2024
1 parent 9e87e82 commit 1d19de7
Show file tree
Hide file tree
Showing 12 changed files with 217 additions and 179 deletions.
2 changes: 1 addition & 1 deletion config/config.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
'admin' => [
'name' => ['zh-CN' => '后台管理', 'en' => 'Admin'],
'path' => 'app/Admin/Controllers/',
'requests' => ['index', 'trashed', 'store', 'update', 'destroyBatch', 'restore', 'create', 'edit'], // 默认的 action 对应的 request 定义
'requests' => ['index', 'store', 'update', 'destroyBatch', 'restore', 'create', 'edit'], // 默认的 action 对应的 request 定义
'stub' => 'controller-admin',
'trait_stub' => 'controller-base-action-trait',
'route' => 'routes/admin.php',
Expand Down
21 changes: 3 additions & 18 deletions src/Command/CreateControllerCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,6 @@ protected function getArguments()
protected function getOptions()
{
return [
[
'trait',
'-t',
InputOption::VALUE_OPTIONAL,
'Build Trait File.',
false,
],
[
'force',
'-f',
Expand Down Expand Up @@ -92,18 +85,10 @@ public function handle()
(new FreshStorageGenerator($this, $this->filesystem, $this->utility))->start();
$this->tipCallCommand('moo:controller');

$trait = $this->option('trait') === null;
$force = $this->option('force') === null;

if ($trait) {
$controllers = $this->utility->getControllers();
$controller_name = $this->choice('Which controller ?', array_keys($controllers));
(new CreateControllerGenerator($this, $this->filesystem, $this->utility))
->buildTrait($controller_name, $controllers[$controller_name], $force);
} else {
$result = (new CreateControllerGenerator($this, $this->filesystem, $this->utility))
->start($schema_name, $force);
$this->tipDone($result);
}
$result = (new CreateControllerGenerator($this, $this->filesystem, $this->utility))
->start($schema_name, $force);
$this->tipDone($result);
}
}
29 changes: 15 additions & 14 deletions src/Command/FreeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@

namespace Mooeen\Scaffold\Command;

use Symfony\Component\Yaml\Yaml;
use Symfony\Component\Console\Input\InputOption;
use Mooeen\Scaffold\Generator\CreateApiGenerator;
use Symfony\Component\Console\Input\InputArgument;
use Mooeen\Scaffold\Generator\CreateControllerGenerator;
use Mooeen\Scaffold\Generator\CreateMigrationGenerator;
use Mooeen\Scaffold\Generator\CreateModelGenerator;
use Mooeen\Scaffold\Generator\FreshStorageGenerator;
use Mooeen\Scaffold\Generator\CreateMigrationGenerator;
use Mooeen\Scaffold\Generator\CreateControllerGenerator;
use Mooeen\Scaffold\Generator\UpdateMultilingualGenerator;
use Mooeen\Scaffold\Generator\UpdateAuthorizationGenerator;
use Mooeen\Scaffold\Generator\UpdateMultilingualGenerator;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Yaml\Yaml;

/**
* Free : Release your hands
*
Expand Down Expand Up @@ -81,6 +82,7 @@ protected function getOptions()
* Execute the console command.
*
* @return void
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function handle()
Expand All @@ -93,12 +95,12 @@ public function handle()
$schema_name = $this->choice('What is schema name?', $file_names);
}

$clean = $this->option('clean') === null;
$force = $this->option('force') === null;
$clean = $this->option('clean') === null;
$force = $this->option('force') === null;

$schema_path = $this->utility->getDatabasePath('schema');
$yaml = new Yaml;
$data = $yaml::parseFile($schema_path . $schema_name . '.yaml');
$schema_path = $this->utility->getDatabasePath('schema');
$yaml = new Yaml;
$data = $yaml::parseFile($schema_path . $schema_name . '.yaml');

$this->tipCallCommand('moo:fresh');
(new FreshStorageGenerator($this, $this->filesystem, $this->utility))->start($clean);
Expand All @@ -111,7 +113,7 @@ public function handle()

$this->tipCallCommand('moo:api');
//$namespace = "{$data['package']['folder']}/{$data['module']['folder']}";
$namespace = "{$data['module']['folder']}";
$namespace = "{$data['module']['folder']}";
(new CreateApiGenerator($this, $this->filesystem, $this->utility))->start($namespace, false, $force);

$this->tipCallCommand('moo:i18n');
Expand All @@ -123,8 +125,7 @@ public function handle()
$this->tipCallCommand('moo:migration');
(new CreateMigrationGenerator($this, $this->filesystem, $this->utility))->start($schema_name);

if ($this->confirm("Do you want to Execute 'artisan migrate' ?", 'yes'))
{
if ($this->confirm("Do you want to Execute 'artisan migrate' ?", 'yes')) {
$this->tipCallCommand('migrate');
$this->call('migrate');
}
Expand Down
79 changes: 36 additions & 43 deletions src/Generator/CreateControllerGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ public function start(string $schema_name, bool $force = false)
}

// 检查目录是否存在,不存在则创建
$path = $this->base_path . $uc_app_folder . '/Controllers/' . $attr['module']['folder'];
$path = $this->utility->getConfig("controller.{$app_folder}.path");
$path = base_path($path) . $attr['module']['folder'];
if (! $this->filesystem->isDirectory($path)) {
$this->filesystem->makeDirectory($path, 0777, true, true);
}
Expand All @@ -62,9 +63,10 @@ public function start(string $schema_name, bool $force = false)
$model_class = ucfirst(str_replace(['./', '/'], ['', '\\'], $model_class));

// 表格数据
$table_attrs = $this->utility->getOneTable($attr['table_name']);
$fields = $table_attrs['fields'];
$enums = $table_attrs['enums'];
$table_attrs = $this->utility->getOneTable($attr['table_name']);
$fields = $table_attrs['fields'];
$enums = $table_attrs['enums'];
$controller_name = Str::replaceLast('Controller', '', $class);

$meta = [
'author' => $this->utility->getConfig('author'),
Expand All @@ -78,18 +80,17 @@ public function start(string $schema_name, bool $force = false)
'entity_en_name' => $attr['model_class'],
'namespace' => "{$namespace_pre}{$attr['module']['folder']}",
'use_base_action' => "{$namespace_pre}Traits\\BaseActionTrait",
'use_controller_trait' => "{$namespace_pre}{$attr['module']['folder']}\\Traits\\{$controller_name}Trait",
'use_base_controller' => $this->utility->getConfig('class.controller'),
'use_base_resources' => $this->utility->getConfig('class.resources.base'),
'use_base_resources_collection' => $this->utility->getConfig('class.resources.collection'),
'use_form_widgets' => $this->utility->getConfig('class.resources.form'),
'use_columns' => $this->utility->getConfig('class.resources.columns'),
'use_table_columns' => $this->utility->getConfig('class.resources.table_columns'),
'controller_name' => Str::replaceLast('Controller', '', $class),
'index_fields' => $this->getListFields($fields),
'index_columns' => $this->getListFields($fields, $app_folder === 'admin'),
'controller_name' => $controller_name,
'list_fields' => $this->getListFields($fields),
'list_columns' => $this->getListFields($fields, $app_folder === 'admin'),
'show_fields' => $this->getShowFields($fields),
'trashed_fields' => $this->getListFields($fields, false, true),
'trashed_columns' => $this->getListFields($fields, $app_folder === 'admin', true),
'route_key' => strtolower(Str::snake($attr['model_class'], '-')),
'model_class' => $model_class,
'model_key_name' => (new $model_class())->getKeyName(),
Expand All @@ -104,6 +105,9 @@ public function start(string $schema_name, bool $force = false)
$meta['use_requests'] = $this->buildRequest($uc_app_folder, $rules, $enums, $table_attrs['index'], $meta, $controller_file, $force);
$meta['use_requests'] = implode(PHP_EOL, $meta['use_requests']);

// build controller trait
$this->buildTrait($app_folder, $meta, $force);

// 生成 controller 文件
$controller_relative_file = str_replace(base_path(), '.', $controller_file);
if ($this->filesystem->isFile($controller_file) && ! $force) {
Expand All @@ -113,6 +117,7 @@ public function start(string $schema_name, bool $force = false)
continue;
}

// build controller
$stub = $this->utility->getConfig('controller.' . $app_folder . '.stub');
$content = $this->buildStub($meta, $this->getStub($stub));
$this->filesystem->put($controller_file, $content);
Expand Down Expand Up @@ -182,7 +187,7 @@ public function buildRequest(string $app_folder, array $rules, array $enums, arr
$this->command->info('+ ' . str_replace(base_path(), '.', $trait_file));

// 如果之前已经有 trait 文件了,并且存在 controller 文件,则不再生成 request 文件,避免删除了又重新生成
if ($dont_build_request && $this->filesystem->isFile($controller_file)) {
if ($dont_build_request && $this->filesystem->isFile($controller_file) && ! $force) {
return [];
}

Expand Down Expand Up @@ -254,27 +259,22 @@ public function buildRequest(string $app_folder, array $rules, array $enums, arr
/**
* 生成 controller 的 trait 代码文件
*/
public function buildTrait(string $controller, array $data, bool $force): void
public function buildTrait(string $app, array $data, bool $force = false): void
{
$model_class = $this->utility->getConfig('model.path') . $data['module']['folder'] . '/' . $data['model_class'];

if (count($data['app']) > 1) {
$app = $this->command->choice('Which app?', $data['app']);
} else {
$app = $data['app'][0];
}

$path = $this->utility->getConfig("controller.{$app}.path");
$trait_path = base_path($path) . $data['module']['folder'] . '/Traits/';
$trait_path = base_path($path) . $data['module_en_name'] . '/Traits/';
$trait_relative_path = str_replace(base_path(), '.', $trait_path);

$meta = [
'namespace' => ucfirst(str_replace('/', '\\', $path)) . $data['module']['folder'] . '\\Traits',
'controller' => $controller . '\'s',
'trait_class' => str_replace('Controller', '', $controller) . 'Trait',
'model_class' => ucfirst(str_replace('/', '\\', $model_class)),
'author' => $this->utility->getConfig('author'),
'date' => date('Y-m-d H:i:s'),
'namespace' => $data['namespace'] . '\\Traits',
'controller_name' => $data['controller_name'],
'trait_class' => $data['controller_name'] . 'Trait',
'model_class' => $data['model_class'],
'model_name' => $data['model_name'],
'list_fields' => $data['list_fields'],
'list_columns' => $data['list_columns'],
'author' => $data['author'],
'date' => $data['date'],
];

// 检查目录是否存在,不存在则创建
Expand All @@ -291,9 +291,9 @@ public function buildTrait(string $controller, array $data, bool $force): void
return;
}

$content = $this->buildStub($meta, $this->getStub('controller-trait'));
$content = $this->buildStub($meta, $this->getStub("controller-{$app}-trait"));
$this->filesystem->put($trait_file, $content);
$this->command->info('+ ' . $trait_relative_file . ' (' . ($force ? 'Updated' : 'Added') . ')');
$this->command->info('+ ' . $trait_relative_file);
}

/**
Expand Down Expand Up @@ -414,7 +414,7 @@ private function rebuildFieldsRules(array $controller, array $fields, array $enu
/**
* 获取列表查询字段
*/
private function getListFields(array $fields, bool $option = false, bool $trashed = false): string
private function getListFields(array $fields, bool $is_columns = false): string
{
$fields = array_keys($fields);

Expand All @@ -426,21 +426,14 @@ private function getListFields(array $fields, bool $option = false, bool $trashe
continue;
}

if (! $trashed) {
if (in_array($value, ['deleted_at'])) {
unset($fields[$k]);

continue;
}
} else {
if (in_array($value, ['updated_at'])) {
unset($fields[$k]);
// 在 controller 中处理
if (in_array($value, ['updated_at', 'deleted_at'])) {
unset($fields[$k]);

continue;
}
continue;
}

if ($option && in_array($value, ['id', 'created_at'])) { // 列表头,不要 id, created_at 列
if ($is_columns && in_array($value, ['id', 'created_at'])) { // 列表头,不要 id, created_at 列
unset($fields[$k]);

continue;
Expand All @@ -450,8 +443,8 @@ private function getListFields(array $fields, bool $option = false, bool $trashe
}
unset($value);

if ($option) { // 列表加入操作列
$fields[] = "'options'";
if ($is_columns) { // 一行一个属性
return implode(',' . PHP_EOL, $fields);
}

return implode(', ', $fields);
Expand Down
13 changes: 4 additions & 9 deletions src/Http/Controllers/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,23 @@

namespace Mooeen\Scaffold\Http\Controllers;

use Mooeen\Scaffold\Utility;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Routing\Controller as BaseController;
use Mooeen\Scaffold\Utility;

/**
* Class Controller
*
* @package Mooeen\Scaffold\Http\Controllers
* @author Charsen https://github.com/charsen
*/
class Controller extends BaseController
{
protected $utility;

protected $filesystem;

/**
* Controller constructor.
*
* @param \Mooeen\Scaffold\Utility $utility
* @param \Illuminate\Filesystem\Filesystem $filesystem
*/
public function __construct(Utility $utility, Filesystem $filesystem)
{
Expand All @@ -33,7 +30,6 @@ public function __construct(Utility $utility, Filesystem $filesystem)
* Helper to get the config values.
*
* @param string $key
*
* @return mixed
*/
protected function config($key)
Expand All @@ -45,9 +41,8 @@ protected function config($key)
* Get the evaluated view contents for the given view.
*
* @param string $view
* @param array $data
* @param array $mergeData
*
* @param array $data
* @param array $mergeData
* @return \Illuminate\View\View
*/
protected function view($view, $data = [], $mergeData = [])
Expand Down
12 changes: 3 additions & 9 deletions src/Http/Controllers/DatabaseController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,12 @@
/**
* Class DatabaseController
*
* @package Mooeen\Scaffold\Http\Controllers
* @author Charsen https://github.com/charsen
*/
class DatabaseController extends Controller
{
/**
* tables list
*
*/
public function index(Request $req)
{
Expand All @@ -25,13 +23,11 @@ public function index(Request $req)
$data['first_menu_active'] = $data['current_file'] != null;
$data['first_table_active'] = $data['current_file'] != null;


return $this->view('db.index', $data);
}

/**
* dictionaries
*
*/
public function dictionaries(Request $req)
{
Expand All @@ -47,9 +43,9 @@ public function dictionaries(Request $req)
/**
* table view
*
* @param \Illuminate\Http\Request $req
*
* @return \Illuminate\View\View
*
* @throws \Illuminate\Contracts\Filesystem\FileNotFoundException
*/
public function show(Request $req)
Expand All @@ -59,10 +55,8 @@ public function show(Request $req)

// 从 i18n 里读取字段名称
$lang_fields = $this->utility->getLangFields();
foreach ($data['data']['fields'] as $key => &$attr)
{
if (isset($lang_fields[$key]))
{
foreach ($data['data']['fields'] as $key => &$attr) {
if (isset($lang_fields[$key])) {
$attr['name'] = $lang_fields[$key]['zh-CN'];
}
}
Expand Down
Loading

0 comments on commit 1d19de7

Please sign in to comment.