update 模版生成

This commit is contained in:
JaguarJack 2021-06-10 19:38:44 +08:00
parent 72bf97579b
commit 15c271eafb
16 changed files with 245 additions and 1521 deletions

View File

@ -15,7 +15,7 @@ use catcher\Utils;
class Generator
{
const NEED_PACKAGE = 'nikic/php-parser';
const NEED_PACKAGE = 'jaguarjack/file-generate';
/**
* generate
@ -32,7 +32,7 @@ class Generator
// 判断是否安装了扩展包
if (!(new Composer)->hasPackage(self::NEED_PACKAGE)) {
throw new FailedException(
sprintf('you must use [ composer require --dev %s]', self::NEED_PACKAGE)
sprintf('you must use [ composer require --dev %s:dev-master]', self::NEED_PACKAGE)
);
}
@ -40,9 +40,8 @@ class Generator
[$controller, $model] = $this->parseParams($params);
$message = [];
$message = $files = [];
$files = [];
$migration = '';
try {
@ -89,16 +88,15 @@ class Generator
* @time 2020年04月29日
* @param $params
* @return bool|string|string[]
* @throws \JaguarJack\Generate\Exceptions\TypeNotFoundException
*/
public function preview($params)
{
$type = $params['type'];
$params = \json_decode($params['data'], true);
[$controller, $model] = $this->parseParams($params);
switch ($type) {
switch ($params['type']) {
case 'controller':
return (new Controller)->getContent($controller);
case 'model':

View File

@ -1,141 +0,0 @@
<?php
namespace catcher\generate\build;
use catcher\CatchAdmin;
use catcher\facade\FileSystem;
use catcher\generate\build\classes\Classes;
use PhpParser\BuilderFactory;
use PhpParser\PrettyPrinter\Standard;
class CatchBuild
{
protected $astBuilder;
protected $outPath;
protected $filename;
public function __construct()
{
$this->astBuilder = app(BuilderFactory::class);
}
/**
* 命名空间
*
* @time 2020年11月19日
* @param string $namespace
* @return $this
*/
public function namespace(string $namespace)
{
$this->astBuilder = $this->astBuilder->namespace($namespace);
return $this;
}
/**
* use 方法体
*
* @time 2020年11月19日
* @param $use
* @return $this
*/
public function use($use)
{
$this->astBuilder->addStmt($use);
return $this;
}
/**
* class 模版
*
* @time 2020年11月19日
* @param Classes $class
* @param \Closure $function
* @return $this
*/
public function class(Classes $class, \Closure $function)
{
$function($class);
$this->astBuilder->addStmt($class->build());
return $this;
}
/**
* 条件
*
* @time 2020年11月19日
* @param $condition
* @param \Closure $closure
* @return $this
*/
public function when($condition, \Closure $closure)
{
if ($condition && $closure instanceof \Closure) {
$closure($this);
}
return $this;
}
/**
* 获取内容
*
* @time 2020年11月19日
* @return string
*/
public function getContent()
{
$stmts = array($this->astBuilder->getNode());
$prettyPrinter = new Standard();
return $prettyPrinter->prettyPrintFile($stmts);
}
/**
* 输出
*
* @time 2020年11月19日
* @return string
*/
public function output()
{
return FileSystem::put($this->outPath . $this->filename, $this->getContent());
}
/**
* 输出 Path
*
* @time 2020年11月19日
* @param $path
* @return $this
*/
public function path($path)
{
CatchAdmin::makeDirectory($path);
$this->outPath = $path;
return $this;
}
/**
* 设置文件名
*
* @time 2020年11月19日
* @param $name
* @return mixed
*/
public function filename($name)
{
$this->filename = $name;
return $this;
}
}

View File

@ -1,117 +0,0 @@
<?php
namespace catcher\generate\build\classes;
use PhpParser\BuilderFactory;
class Classes
{
protected $classBuild;
public function __construct(string $name)
{
$this->classBuild = (new BuilderFactory())->class($name);
}
/**
* 设置 comment
*
* @time 2020年11月19日
* @param string $comment
* @return $this
*/
public function docComment($comment="\r\n")
{
$this->classBuild->setDocComment($comment);
return $this;
}
/**
* @time 2020年11月17日
* @param $extend
* @return $this
*/
public function extend($extend)
{
$this->classBuild->extend($extend);
return $this;
}
/**
* @time 2020年11月17日
* @param $interfaces
* @return $this
*/
public function implement($interfaces)
{
$this->classBuild->implement($interfaces);
return $this;
}
/**
* @time 2020年11月17日
* @return $this
*/
public function abstract()
{
$this->classBuild->makeAbstract();
return $this;
}
/**
* @time 2020年11月17日
* @return $this
*/
public function final()
{
$this->classBuild->makeFinal();
return $this;
}
public function build()
{
return $this->classBuild;
}
public function addMethod(Methods $method)
{
$this->classBuild->addStmt($method->build());
return $this;
}
public function addProperty(Property $property)
{
$this->classBuild->addStmt($property->build());
return $this;
}
public function addTrait(Traits $trait)
{
$this->classBuild->addStmt($trait->build());
return $this;
}
/**
* when
*
* @time 2020年11月19日
* @param $condition
* @param \Closure $closure
* @return $this
*/
public function when($condition, \Closure $closure)
{
if ($condition) {
$closure($this);
}
return $this;
}
}

View File

@ -1,158 +0,0 @@
<?php
namespace catcher\generate\build\classes;
use catcher\generate\build\traits\CatchMethodReturn;
use PhpParser\BuilderFactory;
use PhpParser\Node\Expr\Assign;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt\Expression;
class Methods
{
use CatchMethodReturn;
protected $methodBuild;
public function __construct(string $name)
{
$this->methodBuild = (new BuilderFactory())->method($name);
}
public function public()
{
$this->methodBuild->makePublic();
return $this;
}
public function protected()
{
$this->methodBuild->makeProtected();
return $this;
}
public function private()
{
$this->methodBuild->makePrivate();
return $this;
}
/**
* set params
*
* @time 2020年11月16日
* @param $type
* @param $param
* @param $default
* @return $this
*/
public function param($param, $type = null, $default = null)
{
$param = (new BuilderFactory())->param($param);
if ($type) {
$param = $param->setType($type);
}
if ($default) {
$param = $param->setDefault($default);
}
$this->methodBuild->addParam(
$param
);
return $this;
}
/**
* 定义
*
* @time 2020年11月18日
* @param $variable
* @param $value
* @return $this
*/
public function declare($variable, $value)
{
$smt = new Expression(
new Assign(
new PropertyFetch(
new Variable('this'),
new Identifier($variable)
),
new Variable($value)
)
);
$this->methodBuild->addStmt($smt);
return $this;
}
/**
* 返回值
*
* @time 2020年11月16日
* @param $returnType
* @return $this
*/
public function returnType($returnType)
{
$this->methodBuild->setReturnType($returnType);
return $this;
}
/**
* 注释
*
* @time 2020年11月16日
* @param $comment
* @return $this
*/
public function docComment(string $comment)
{
$this->methodBuild->setDocComment($comment);
return $this;
}
/**
* 抽象
*
* @time 2020年11月17日
* @return $this
*/
public function toAbstract()
{
$this->methodBuild->makeAbstract();
return $this;
}
/**
* final
*
* @time 2020年11月17日
* @return $this
*/
public function toFinal()
{
$this->methodBuild->makeFinal();
return $this;
}
public function build()
{
return $this->methodBuild;
}
}

View File

@ -1,97 +0,0 @@
<?php
namespace catcher\generate\build\classes;
use PhpParser\BuilderFactory;
class Property
{
protected $propertyBuild;
public function __construct(string $name)
{
$this->propertyBuild = (new BuilderFactory())->property($name);
}
/**
* @time 2020年11月17日
* @return $this
*/
public function public()
{
$this->propertyBuild->makePublic();
return $this;
}
/**
* @time 2020年11月17日
* @return $this
*/
public function protected()
{
$this->propertyBuild->makeProtected();
return $this;
}
/**
* @time 2020年11月17日
* @return $this
*/
public function private()
{
$this->propertyBuild->makePrivate();
return $this;
}
/**
* 注释
*
* @time 2020年11月16日
* @param $comment
* @return $this
*/
public function static($comment)
{
$this->propertyBuild->makeStatic();
return $this;
}
/**
* set default
*
* @time 2020年11月16日
* @param $value
* @return $this
*/
public function default($value)
{
$this->propertyBuild->setDefault($value);
return $this;
}
public function type($type)
{
$this->propertyBuild->setType($type);
return $this;
}
public function docComment($comment)
{
$this->propertyBuild->setDocComment($comment);
return $this;
}
public function build()
{
return $this->propertyBuild;
}
}

View File

@ -1,88 +0,0 @@
<?php
namespace catcher\generate\build\classes;
use PhpParser\BuilderFactory;
class Traits
{
protected $traitBuild;
protected $build;
public function use(...$names)
{
$this->build = new BuilderFactory;
$this->traitBuild = call_user_func_array([$this->build, 'useTrait'], $names);
return $this;
}
public function and($name)
{
$this->traitBuild->and($name);
return $this;
}
/**
* with
*
* @time 2020年11月19日
* @param \Closure|null $closure
* @return $this
*/
public function with(\Closure $closure = null)
{
if ($closure instanceof \Closure) {
$this->traitBuild->withe($closure($this));
return $this;
}
return $this;
}
/**
* @time 2020年11月19日
* @param $name
* @param null $method
* @return $this
*/
public function adaptation($name, $method = null)
{
$this->build = $this->build->traitUseAdaptation($name. $method);
return $this;
}
/**
* @time 2020年11月19日
* @param $name
* @return $this
*/
public function as($name)
{
$this->build->as($name);
return $this;
}
/**
* @time 2020年11月19日
* @param $name
* @return $this
*/
public function insteadof($name)
{
$this->build->insteadof($name);
return $this;
}
public function build()
{
return $this->traitBuild;
}
}

View File

@ -1,29 +0,0 @@
<?php
namespace catcher\generate\build\classes;
use PhpParser\BuilderFactory;
class Uses
{
public function name(string $name, string $as = '')
{
$build = (new BuilderFactory())->use($name);
if ($as) {
$build->as($as);
}
return $build;
}
public function function(string $function)
{
return (new BuilderFactory())->useFunction($function);
}
public function const(string $const)
{
return (new BuilderFactory())->useConst($const);
}
}

View File

@ -1,130 +0,0 @@
<?php
namespace catcher\generate\build\traits;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\PropertyFetch;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Return_;
trait CatchMethodReturn
{
/**
* 列表
*
* @time 2020年11月18日
* @param $model
* @return $this
*/
public function index($model)
{
$class = new Name('CatchResponse');
$arg = new Arg(new MethodCall(
new PropertyFetch(
new Variable('this'), new Identifier($model)
),
new Identifier('getList')
));
$this->methodBuild->addStmt(new Return_(new StaticCall($class, 'paginate', [$arg])));
return $this;
}
/**
* 保存
*
* @time 2020年11月18日
* @param $model
* @return $this
*/
public function save($model)
{
$arg = new Arg(new MethodCall(
new PropertyFetch(
new Variable('this'), new Identifier($model)
),
new Identifier('storeBy'), [new Arg(new MethodCall(new Variable('request'), new Identifier('post')))]
));
$class = new Name('CatchResponse');
$this->methodBuild->addStmt(new Return_(new StaticCall($class, 'success', [$arg])));
return $this;
}
/**
* 更新
*
* @time 2020年11月18日
* @param $model
* @return $this
*/
public function update($model)
{
$arg = new Arg(new MethodCall(
new PropertyFetch(
new Variable('this'), new Identifier($model)
),
new Identifier('updateBy'), [
new Arg(new Variable('id')),
new Arg(new MethodCall(new Variable('request'), new Identifier('post')))
]
));
$class = new Name('CatchResponse');
$this->methodBuild->addStmt(new Return_(new StaticCall($class, 'success', [$arg])));
return $this;
}
public function read($model)
{
$arg = new Arg(new MethodCall(
new PropertyFetch(
new Variable('this'), new Identifier($model)
),
new Identifier('findBy'), [
new Arg(new Variable('id'))
]
));
$class = new Name('CatchResponse');
$this->methodBuild->addStmt(new Return_(new StaticCall($class, 'success', [$arg])));
return $this;
}
/**
* 删除
*
* @time 2020年11月18日
* @param $model
* @return $this
*/
public function delete($model)
{
$arg = new Arg(new MethodCall(
new PropertyFetch(
new Variable('this'), new Identifier($model)
),
new Identifier('deleteBy'), [
new Arg(new Variable('id'))
]
));
$class = new Name('CatchResponse');
$this->methodBuild->addStmt(new Return_(new StaticCall($class, 'success', [$arg])));
return $this;
}
}

View File

@ -1,28 +0,0 @@
<?php
namespace catcher\generate\build\types;
use PhpParser\Comment\Doc;
use PhpParser\Node\Expr\ArrayItem;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Expr\Array_;
class Arr
{
public function build($fields)
{
$items = [];
foreach ($fields as $field) {
$arrItem = new ArrayItem(new String_($field['name']));
if ($field['comment']) {
$arrItem->setDocComment(
new Doc('// ' . $field['comment'])
);
}
$items[] = $arrItem;
}
return new Array_($items);
}
}

View File

@ -1,24 +1,17 @@
<?php
namespace catcher\generate\factory;
use catcher\CatchAdmin;
use catcher\base\CatchController;
use catcher\CatchResponse;
use catcher\exceptions\FailedException;
use catcher\facade\FileSystem;
use catcher\generate\build\classes\Methods;
use catcher\generate\build\CatchBuild;
use catcher\generate\build\classes\Classes;
use catcher\generate\build\classes\Property;
use catcher\generate\build\classes\Uses;
use PhpParser\BuilderFactory;
use PhpParser\Node\Expr\Closure;
use PhpParser\Node\Expr\ClosureUse;
use PhpParser\PrettyPrinter\Standard;
use JaguarJack\Generate\Build\Class_;
use JaguarJack\Generate\Build\ClassMethod;
use JaguarJack\Generate\Build\Params;
use JaguarJack\Generate\Define;
use JaguarJack\Generate\Generator;
use think\helper\Str;
use PhpParser\Error;
use PhpParser\NodeDumper;
use PhpParser\ParserFactory;
use PhpParser\PrettyPrinter;
use PhpParser\Node;
use think\Response;
class Controller extends Factory
{
@ -26,14 +19,14 @@ class Controller extends Factory
protected $uses = [
'catcher\base\CatchRequest as Request',
'catcher\CatchResponse',
'catcher\base\CatchController'
CatchResponse::class,
CatchController::class,
];
/**
*
* @time 2020年04月27日
* @param $params
* @param array $params
* @return bool|string|string[]
*/
public function done(array $params)
@ -66,130 +59,111 @@ class Controller extends Factory
[$model, $modelNamespace] = $this->parseFilename($params['model']);
$asModel = ucfirst(Str::contains($model, 'Model') ? : $model . 'Model');
$asModel = lcfirst(Str::contains($model, 'Model') ? : $model . 'Model');
if (!$className) {
if (! $className) {
throw new FailedException('未填写控制器名称');
}
$use = new Uses();
$class = new Classes($className);
$this->uses[] = sprintf('%s as %s', $modelNamespace . '\\' . ucfirst($model), ucfirst($asModel));
$this->uses[] = Response::class;
return (new CatchBuild())->namespace($namespace)
->use($use->name('catcher\base\CatchRequest', 'Request'))
->use($use->name('catcher\CatchResponse'))
->use($use->name('catcher\base\CatchController'))
->use($use->name($modelNamespace . '\\' . ucfirst($model), $asModel))
->class($class->extend('CatchController')->docComment(), function (Classes $class) use ($asModel) {
foreach ($this->getMethods($asModel) as $method) {
$class->addMethod($method);
}
try {
$content = Generator::namespace($namespace)
->class($className, function (Class_ $class, Generator $generator) use ($model, $asModel) {
$class->extend('CatchController');
$class->addProperty(
(new Property($asModel))->protected()
);
})
->getContent();
}
$generator->property($asModel, function ($property) {
return $property->makeProtected();
});
// construct 方法
$generator->method('__construct', function (ClassMethod $method) use ($model, $asModel) {
return $method->addParam(
Params::name($asModel, ucfirst($asModel))
)->body([
Define::variable(Define::propertyDefineIdentifier($asModel), Define::variable($asModel))
])->makePublic();
});
// index 方法
$generator->method('index', function (ClassMethod $method, Generator $generator) use ($asModel) {
return $method->body([
$generator->call('paginate', [
$generator->methodCall([Define::propertyDefineIdentifier($asModel), 'getList'], [])
], 'CatchResponse')->call()
])->makePublic()->return()->setReturnType('Response');
});
/**
* 方法集合
*
* @time 2020年11月19日
* @param $model
* @return array
*/
protected function getMethods($model)
{
$date = date('Y年m月d日 H:i');
// save 方法
$generator->method('save', function (ClassMethod $method, Generator $generator) use ($asModel) {
return $method
->addParam([
Params::name('request')->setType('Request')
])
->body([
$generator->call('success', [
$generator->methodCall([Define::propertyDefineIdentifier($asModel), 'storeBy'], [
$generator->methodCall(['request', 'post'], [])
])
], 'CatchResponse')->call()
])->makePublic()->return('Response');
});
// read 方法
$generator->method('read', function (ClassMethod $method, Generator $generator) use ($asModel) {
return $method
->addParam([
Params::name('id'),
])
->body([
$generator->call('success', [
$generator->methodCall([Define::propertyDefineIdentifier($asModel), 'findBy'], [
Define::variable('id'),
])
], 'CatchResponse')->call()
])->makePublic()->return('Response');
});
return [
(new Methods('__construct'))
->public()
->param($model, ucfirst($model))
->docComment("\r\n")
->declare($model, $model),
// update 方法
$generator->method('update', function (ClassMethod $method, Generator $generator) use ($asModel) {
return $method
->addParam([
Params::name('id'),
Params::name('request')->setType('Request')
])
->body([
$generator->call('success', [
$generator->methodCall([Define::propertyDefineIdentifier($asModel), 'updateBy'], [
Define::variable('id'),
$generator->methodCall(['request', 'post'], [])
])
], 'CatchResponse')->call()
])->makePublic()->return('Response');
});
(new Methods('index'))->public()
->param('request', 'Request')
->docComment(
<<<TEXT
// read 方法
$generator->method('delete', function (ClassMethod $method, Generator $generator) use ($asModel) {
return $method
->addParam([
Params::name('id'),
])
->body([
$generator->call('success', [
$generator->methodCall([Define::propertyDefineIdentifier($asModel), 'deleteBy'], [
Define::variable('id'),
])
], 'CatchResponse')->call()
])->makePublic()->return('Response');
});
/**
* 列表
* @time $date
* @param Request \$request
*/
TEXT
)
->returnType('\think\Response')->index($model),
})->uses($this->uses)->print();
} catch (\Exception $e) {
throw new FailedException($e->getMessage());
}
(new Methods('save'))
->public()
->param('request', 'Request')
->docComment(
<<<TEXT
/**
* 保存信息
* @time $date
* @param Request \$request
*/
TEXT
)
->returnType('\think\Response')
->save($model),
(new Methods('read'))->public()
->param('id')
->docComment(
<<<TEXT
/**
* 读取
* @time $date
* @param \$id
*/
TEXT
)
->returnType('\think\Response')->read($model),
(new Methods('update'))->public()
->param('request', 'Request')
->param('id')
->docComment(
<<<TEXT
/**
* 更新
* @time $date
* @param Request \$request
* @param \$id
*/
TEXT
)
->returnType('\think\Response')->update($model),
(new Methods('delete'))->public()
->param('id')
->docComment(
<<<TEXT
/**
* 删除
* @time $date
* @param \$id
*/
TEXT
)
->returnType('\think\Response')->delete($model),
];
return $content;
}
}

View File

@ -1,14 +1,13 @@
<?php
namespace catcher\generate\template;
namespace catcher\generate\factory;
trait Content
trait HeaderDoc
{
public function header()
public function header(): string
{
$year = date('Y', time());
return <<<TMP
<?php
// +----------------------------------------------------------------------
// | CatchAdmin [Just Like ]
// +----------------------------------------------------------------------
@ -19,24 +18,6 @@ trait Content
// | Author: JaguarJack [ njphper@gmail.com ]
// +----------------------------------------------------------------------
TMP;
}
/**
* set namespace
*
* @time 2020年04月27日
* @param $namespace
* @return string
*/
public function nameSpace($namespace)
{
return <<<TMP
namespace {$namespace};
TMP;
}
}
}

View File

@ -3,15 +3,12 @@ namespace catcher\generate\factory;
use catcher\exceptions\FailedException;
use catcher\facade\FileSystem;
use catcher\generate\build\CatchBuild;
use catcher\generate\build\classes\Classes;
use catcher\generate\build\classes\Property;
use catcher\generate\build\classes\Traits;
use catcher\generate\build\classes\Uses;
use catcher\generate\build\types\Arr;
use catcher\traits\db\BaseOptionsTrait;
use catcher\traits\db\ScopeTrait;
use catcher\Utils;
use JaguarJack\Generate\Build\Class_;
use JaguarJack\Generate\Build\Property;
use JaguarJack\Generate\Generator;
use think\facade\Db;
use think\helper\Str;
@ -45,6 +42,7 @@ class Model extends Factory
* @time 2020年04月29日
* @param $params
* @return string|string[]
* @throws \JaguarJack\Generate\Exceptions\TypeNotFoundException
*/
public function getContent($params)
{
@ -66,6 +64,33 @@ class Model extends Factory
$softDelete = $extra['soft_delete'];
return Generator::namespace($namespace)
->class($modelName, function (Class_ $class, Generator $generator) use ($table){
$class->extend('Model');
$class->setDocComment($this->buildClassComment($table));
$generator->property('name', function (Property $property) use ($table){
return $property->setDefault(Utils::tableWithoutPrefix($table));
});
if ($this->hasTableExists($table)) {
$generator->property('field', function (Property $property) use ($table){
return $property->setDefault(array_column(Db::getFields($table), 'name'));
});
}
})
->uses([
$softDelete ? 'catcher\base\CatchModel as Model' : 'think\Model'
])
->when(! $softDelete, function (Generator $generator){
$generator->traits([
BaseOptionsTrait::class,
ScopeTrait::class,
]);
})
->print();
/**
return (new CatchBuild)->namespace($namespace)
->use((new Uses())->name('catcher\base\CatchModel', 'Model'))
->when(!$softDelete, function (CatchBuild $build){
@ -94,7 +119,7 @@ class Model extends Factory
(new Arr)->build(Db::getFields($table))
)->docComment('// 数据库字段映射'));
});
})->getContent();
})->getContent();*/
}
/**

View File

@ -2,11 +2,14 @@
namespace catcher\generate\factory;
use catcher\facade\FileSystem;
use catcher\generate\template\Content;
use JaguarJack\Generate\Build\Value;
use JaguarJack\Generate\Define;
use PhpParser\ParserFactory;
use JaguarJack\Generate\Generator;
class Route extends Factory
{
use Content;
use HeaderDoc;
protected $controllerName;
@ -14,68 +17,111 @@ class Route extends Factory
protected $restful;
protected $module;
protected $methods = [];
const VARIABLE_ST = 'scapegoat';
/**
* 实现
*
* @time 2021年06月09日
* @param array $params
* @throws \Exception
* @return mixed
*/
public function done(array $params = [])
{
$route = [];
$router = $this->getModulePath($this->controller) . DIRECTORY_SEPARATOR . 'route.php';
$content = $this->generateRoute($router);
$content = '<?php' . PHP_EOL .
trim(str_replace(['$scapegoat', '='], ['', ''], $content), ';') . ';';
if (! file_exists($router)) {
return FileSystem::put($router, $content);
}
return FileSystem::put($router, $content);
}
/**
* parse router methods
*
* @time 2021年06月09日
* @return array
* @throws \JaguarJack\Generate\Exceptions\TypeNotFoundException
*/
protected function parseRouteMethods(): array
{
$generate = new Generator();
$stmts = [];
if ($this->restful) {
$route[] = sprintf("\$router->resource('%s', '\%s');", $this->controllerName, $this->controller);
$stmts[] = Define::variable(self::VARIABLE_ST, $generate->methodCall(['router', 'resource'], [
Value::fetch($this->controllerName),
Value::fetch(Define::classConstFetch($this->controller))
]), sprintf('// %s 路由', $this->controllerName));
}
if (!empty($this->methods)) {
foreach ($this->methods as $method) {
$route[] = sprintf("\$router->%s('%s/%s', '\%s@%s');", $method[1], $this->controllerName, $method[0], $this->controller, $method[0] );
$stmts[] = Define::variable(self::VARIABLE_ST,
$generate->methodCall(['router', $method[1]], [
Value::fetch(sprintf('%s/%s', $this->controllerName, $method[0])),
Value::fetch(sprintf('%s@%s', $this->controller, $method[0]))
]));
}
}
$router = $this->getModulePath($this->controller) . DIRECTORY_SEPARATOR . 'route.php';
$comment = '// ' . $this->controllerName . '路由';
array_unshift($route, $comment);
if (file_exists($router)) {
return FileSystem::put($router, $this->parseRoute($router, $route));
}
return FileSystem::put($router, $this->header() . $comment. implode(';'. PHP_EOL , $route) . ';');
return $stmts;
}
protected function parseRoute($path, $route)
/**
* generate route
*
* @time 2021年06月09日
* @param string $router
* @return string
* @throws \Exception
*/
protected function generateRoute(string $router): string
{
$file = new \SplFileObject($path);
// 保留所有行
$lines = [];
// 结尾之后的数据
$down = [];
// 结尾数据
$end = '';
while (!$file->eof()) {
$lines[] = rtrim($file->current(), PHP_EOL);
$file->next();
$generate = new Generator();
if (! FileSystem::exists($router)) {
$stmts = $this->parseRouteMethods();
$expr = Define::variable(self::VARIABLE_ST, $generate->call(
$generate->methodCall(['router', 'group'], [
Value::fetch($this->module),
$generate->closure()->uses('router')->body($stmts)
]))
->call('middleware', [Value::fetch('auth')])
->call(), $this->header() . PHP_EOL . '/* @var \think\Route $router */');
return $generate->getContent([$expr]);
} else {
$factory = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $factory->parse(file_get_contents($router));
$expression = $ast[0];
$stmts = $expression->expr->var->args[1]->value->stmts;
$stmts = array_merge($stmts, $this->parseRouteMethods());
$expression->expr->var->args[1]->value->stmts = $stmts;
$ast[0] = $expression;
return $generate->getContent($ast);
}
while (count($lines)) {
$line = array_pop($lines);
if (strpos($line, '})') !== false) {
$end = $line;
break;
}
array_unshift($down, $line);
}
$router = implode(PHP_EOL, $lines) . PHP_EOL;
$routes = array_merge($down, $route);
foreach ($routes as $r) {
if ($r) {
$router .= "\t" . $r . PHP_EOL;
}
}
return $router .= $end;
}
/**
@ -85,7 +131,7 @@ class Route extends Factory
* @param $class
* @return $this
*/
public function controller($class)
public function controller($class): Route
{
$this->controller = $class;
@ -93,6 +139,10 @@ class Route extends Factory
$this->controllerName = lcfirst(array_pop($class));
array_pop($class);
$this->module = array_pop($class);
return $this;
}
@ -103,7 +153,7 @@ class Route extends Factory
* @param $restful
* @return $this
*/
public function restful($restful)
public function restful($restful): Route
{
$this->restful = $restful;
@ -117,7 +167,7 @@ class Route extends Factory
* @param $methods
* @return $this
*/
public function methods($methods)
public function methods($methods): Route
{
$this->methods = $methods;

View File

@ -1,249 +0,0 @@
<?php
namespace catcher\generate\template;
use catcher\base\CatchController;
class Controller
{
use Content;
/**
* use
*
* @time 2020年04月27日
* @return string
*/
public function uses()
{
return <<<TMP
use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
{USE}
TMP;
}
/**
* construct
*
* @time 2020年04月27日
* @param $model
* @return string
*/
public function construct($model)
{
return <<<TMP
protected \$model;
public function __construct({$model} \$model)
{
\$this->model = \$model;
}
TMP;
}
public function createClass($class)
{
return <<<TMP
class {$class} extends CatchController
{
{CONTENT}
}
TMP;
}
/**
* list template
*
* @time 2020年04月24日
* @return string
*/
public function index()
{
return <<<TMP
{$this->controllerFunctionComment('列表', '')}
public function index()
{
return CatchResponse::paginate(\$this->model->getList());
}
TMP;
}
/**
* create template
*
* @time 2020年04月24日
* @return string
*/
public function create()
{
return <<<TMP
{$this->controllerFunctionComment('单页')}
public function create()
{
//
}
TMP;
}
/**
* save template
*
* @time 2020年04月24日
* @param $createRequest
* @return string
*/
public function save($createRequest = '')
{
$request = $createRequest ? 'CreateRequest' : 'Request';
return <<<TMP
{$this->controllerFunctionComment('保存', 'Request ' . $request)}
public function save({$request} \$request)
{
return CatchResponse::success(\$this->model->storeBy(\$request->post()));
}
TMP;
}
/**
* read template
*
* @time 2020年04月24日
* @return string
*/
public function read()
{
return <<<TMP
{$this->controllerFunctionComment('读取', '$id')}
public function read(\$id)
{
return CatchResponse::success(\$this->model->findBy(\$id));
}
TMP;
}
/**
* edit template
*
* @time 2020年04月24日
* @return string
*/
public function edit()
{
return <<<TMP
{$this->controllerFunctionComment('编辑', '\$id')}
public function edit(\$id)
{
//
}
TMP;
}
/**
* update template
*
* @time 2020年04月24日
* @param $updateRequest
* @return string
*/
public function update($updateRequest = '')
{
$updateRequest = ($updateRequest ? 'UpdateRequest' : 'Request') . ' $request';
return <<<TMP
{$this->controllerFunctionComment('更新', $updateRequest)}
public function update({$updateRequest}, \$id)
{
return CatchResponse::success(\$this->model->updateBy(\$id, \$request->post()));
}
TMP;
}
/**
* delete template
*
* @time 2020年04月24日
* @return string
*/
public function delete()
{
return <<<TMP
{$this->controllerFunctionComment('删除', '$id')}
public function delete(\$id)
{
return CatchResponse::success(\$this->model->deleteBy(\$id));
}
TMP;
}
/**
* 其他方法
*
* @time 2020年04月27日
* @param $function
* @param string $method
* @return string
*/
public function otherFunction($function, $method = 'get')
{
$params = $method === 'delete' ? '$id' : 'Request $request';
return <<<TMP
{$this->controllerFunctionComment('', $params)}
public function {$function}({$params})
{
// todo
}
TMP;
}
/**
* 控制器方法注释
*
* @time 2020年04月24日
* @param $des
* @param $params
* @return string
*/
protected function controllerFunctionComment($des, $params = '')
{
$now = date('Y/m/d H:i', time());
$params = $params ? '@param ' . $params : '';
return <<<TMP
/**
* {$des}
*
* @time {$now}
* {$params}
* @return \\think\\Response
*/
TMP;
}
}

View File

@ -1,225 +0,0 @@
<?php
namespace catcher\generate\template;
class Model
{
use Content;
public function createModel($model, $table)
{
return <<<TMP
class {$model} extends Model
{
{CONTENT}
}
TMP;
}
public function useTrait($hasDeletedAt = true)
{
if (!$hasDeletedAt) {
return <<<TMP
use BaseOptionsTrait,ScopeTrait;
TMP;
}
}
public function uses($hasDeletedAt = true)
{
if ($hasDeletedAt) {
return <<<TMP
use catcher\base\CatchModel as Model;
TMP;
} else {
return <<<TMP
use think\Model;
use catcher\\traits\db\BaseOptionsTrait;
use catcher\\traits\db\ScopeTrait;
TMP;
}
}
/**
* name
*
* @time 2020年04月28日
* @param $name
* @return string
*/
public function name($name)
{
if ($name) {
return <<<TMP
protected \$name = '{$name}';
TMP;
}
}
/**
* field
*
* @time 2020年04月28日
* @param $field
* @return string
*/
public function field($field)
{
if ($field) {
return <<<TMP
protected \$field = [
{$field}
];
TMP;
}
}
/**
* 一对一关联
*
* @time 2020年04月24日
* @param $model
* @param string $foreignKey
* @param string $pk
* @return string
*/
public function hasOne($model, $foreignKey = '', $pk = '')
{
$func = lcfirst($model);
return <<<TMP
public function {$func}()
{
return \$this->hasOne({$model}::class{$this->keyRelate($foreignKey, $pk)});
}
TMP;
}
/**
*
*
* @time 2020年04月24日
* @param $model
* @param string $foreignKey
* @param string $pk
* @return string
*/
public function hasMany($model, $foreignKey = '', $pk = '')
{
$func = lcfirst($model);
return <<<TMP
public function {$func}()
{
return \$this->hasMany({$model}::class{$this->keyRelate($foreignKey, $pk)});
}
TMP;
}
/**
* 远程一对多
*
* @time 2020年04月24日
* @param $model
* @param $middleModel
* @param string $foreignKey
* @param string $pk
* @param string $middleRelateId
* @param string $middleId
* @return string
*/
public function hasManyThrough($model, $middleModel, $foreignKey = '', $pk = '', $middleRelateId = '', $middleId = '')
{
$func = lcfirst($model);
return <<<TMP
public function {$func}()
{
return \$this->hasManyThrough({$model}::class, {$middleModel}::class{$this->keyRelate($foreignKey, $pk, $middleRelateId, $middleId)});
}
TMP;
}
/**
* 远程一对一
*
* @time 2020年04月24日
* @param $model
* @param $middleModel
* @param string $foreignKey
* @param string $pk
* @param string $middleRelateId
* @param string $middleId
* @return string
*/
public function hasOneThrough($model, $middleModel, $foreignKey = '', $pk = '', $middleRelateId = '', $middleId = '')
{
$func = lcfirst($model);
return <<<TMP
public function {$func}()
{
return \$this->hasOneThrough({$model}::class, {$middleModel}::class{$this->keyRelate($foreignKey, $pk, $middleRelateId, $middleId)});
}
TMP;
}
/**
* 多对多关联
*
* @time 2020年04月24日
* @param $model
* @param string $table
* @param string $foreignKey
* @param string $relateKey
* @return string
*/
public function belongsToMany($model, $table = '', $foreignKey = '', $relateKey = '')
{
$func = lcfirst($model);
$table = !$table ? : ','.$table;
$relateKey = !$relateKey ? : ','.$relateKey;
return <<<TMP
public function {$func}()
{
return \$this->hasOneThrough({$model}::class{$table}{$this->keyRelate($foreignKey)}{$relateKey});
}
TMP;
}
/**
* 模型关联key
*
* @time 2020年04月24日
* @param string $foreignKey
* @param string $pk
* @param string $middleRelateId
* @param string $middleId
* @return string
*/
public function keyRelate($foreignKey = '', $pk = '', $middleRelateId = '', $middleId = '')
{
return !$foreignKey ? : ',' . $foreignKey .
!$middleRelateId ? : ','. $middleRelateId .
!$pk ? : ',' . $pk .
!$middleId ? : ',' . $middleId;
}
}

View File

@ -1,42 +0,0 @@
<?php
namespace catcher\generate\template;
trait Request
{
/**
* 规则
*
* @time 2020年04月24日
* @return string
*/
public function rules()
{
return <<<EOT
public function rules(): array
{
return [
{rules}
];
}
EOT;
}
/**
* 消息
*
* @time 2020年04月24日
* @return string
*/
public function message()
{
return <<<EOT
public function message(): array
{
return [
{messages}
];
}
EOT;
}
}