Browse Source

generator开始编写

wechat_public_accounts
blobt 5 years ago
parent
commit
f99a12b079
  1. 186
      vendor/blobt/generators/crud/Generator.php
  2. 50
      vendor/blobt/generators/crud/default/views/_search.php
  3. 100
      vendor/blobt/generators/crud/default/views/index.php

186
vendor/blobt/generators/crud/Generator.php

@ -0,0 +1,186 @@
<?php
/*
* The MIT License
*
* Copyright 2019 Blobt.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace blobt\generators\curd;
use Yii;
use yii\db\ActiveRecord;
use yii\db\BaseActiveRecord;
use yii\db\Schema;
use yii\gii\CodeFile;
use yii\helpers\Inflector;
use yii\helpers\VarDumper;
use yii\web\Controller;
/**
* Description of Generator
*
* @author Blobt
* @email 380255922@qq.com
* @created Oct 6, 2019
*/
class Generator extends \yii\gii\Generator {
public $modelClass;
public $controllerClass;
public $viewPath;
public $baseControllerClass = 'yii\web\Controller';
public $indexWidgetType = 'grid';
public $searchModelClass = '';
/**
* {@inheritdoc}
*/
public function getName() {
return 'CRUD Generator';
}
/**
* {@inheritdoc}
*/
public function requiredTemplates() {
return ['controller.php'];
}
/**
* {@inheritdoc}
*/
public function stickyAttributes() {
return array_merge(parent::stickyAttributes(), ['baseControllerClass', 'indexWidgetType']);
}
/**
* {@inheritdoc}
*/
public function generate() {
$controllerFile = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->controllerClass, '\\')) . '.php');
$files = [
new CodeFile($controllerFile, $this->render('controller.php')),
];
if (!empty($this->searchModelClass)) {
$searchModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->searchModelClass, '\\') . '.php'));
$files[] = new CodeFile($searchModel, $this->render('search.php'));
}
$viewPath = $this->getViewPath();
$templatePath = $this->getTemplatePath() . '/views';
foreach (scandir($templatePath) as $file) {
if (empty($this->searchModelClass) && $file === '_search.php') {
continue;
}
if (is_file($templatePath . '/' . $file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
$files[] = new CodeFile("$viewPath/$file", $this->render("views/$file"));
}
}
return $files;
}
/**
* @return string the controller ID (without the module ID prefix)
*/
public function getControllerID() {
$pos = strrpos($this->controllerClass, '\\');
$class = substr(substr($this->controllerClass, $pos + 1), 0, -10);
return Inflector::camel2id($class, '-', $this->strictInflector);
}
/**
* @return string the controller view path
*/
public function getViewPath() {
if (empty($this->viewPath)) {
return Yii::getAlias('@app/views/' . $this->getControllerID());
}
return Yii::getAlias(str_replace('\\', '/', $this->viewPath));
}
/**
* @return string
*/
public function getNameAttribute() {
foreach ($this->getColumnNames() as $name) {
if (!strcasecmp($name, 'name') || !strcasecmp($name, 'title')) {
return $name;
}
}
/* @var $class \yii\db\ActiveRecord */
$class = $this->modelClass;
$pk = $class::primaryKey();
return $pk[0];
}
/**
* Generates code for active field
* @param string $attribute
* @return string
*/
public function generateActiveField($attribute) {
$tableSchema = $this->getTableSchema();
if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
return "\$form->field(\$model, '$attribute')->passwordInput()";
}
return "\$form->field(\$model, '$attribute')";
}
$column = $tableSchema->columns[$attribute];
if ($column->phpType === 'boolean') {
return "\$form->field(\$model, '$attribute')->checkbox()";
}
if ($column->type === 'text') {
return "\$form->field(\$model, '$attribute')->textarea(['rows' => 6])";
}
if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
$input = 'passwordInput';
} else {
$input = 'textInput';
}
if (is_array($column->enumValues) && count($column->enumValues) > 0) {
$dropDownOptions = [];
foreach ($column->enumValues as $enumValue) {
$dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
}
return "\$form->field(\$model, '$attribute')->dropDownList("
. preg_replace("/\n\s*/", ' ', VarDumper::export($dropDownOptions)) . ", ['prompt' => ''])";
}
if ($column->phpType !== 'string' || $column->size === null) {
return "\$form->field(\$model, '$attribute')->$input()";
}
return "\$form->field(\$model, '$attribute')->$input(['maxlength' => true])";
}
}

50
vendor/blobt/generators/crud/default/views/_search.php

@ -17,33 +17,29 @@ use yii\widgets\ActiveForm;
/* @var $form yii\widgets\ActiveForm */ /* @var $form yii\widgets\ActiveForm */
?> ?>
<div class="<?= Inflector::camel2id(StringHelper::basename($generator->modelClass)) ?>-search">
<?= "<?php " ?>$form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
<?php if ($generator->enablePjax): ?>
'options' => [
'data-pjax' => 1
],
<?php endif; ?>
]); ?>
<?php
$count = 0;
foreach ($generator->getColumnNames() as $attribute) {
if (++$count < 6) {
echo " <?= " . $generator->generateActiveSearchField($attribute) . " ?>\n\n";
} else {
echo " <?php // echo " . $generator->generateActiveSearchField($attribute) . " ?>\n\n";
}
}
<?= "<?php " ?>$form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
'validateOnType' => true,
]);
?> ?>
<div class="form-group">
<?= "<?= " ?>Html::submitButton(<?= $generator->generateString('Search') ?>, ['class' => 'btn btn-primary']) ?>
<?= "<?= " ?>Html::resetButton(<?= $generator->generateString('Reset') ?>, ['class' => 'btn btn-outline-secondary']) ?>
<div class="col-sm-12">
<div class="dataTables_filter">
<?="<?= "?>$form->field($model, 'id', [
"template" => "{input}{error}",
"inputOptions" => [
"placeholder" => "检索ID",
"class" => "form-control",
],
"errorOptions" => [
"class" => "error-tips"
]
])
?>
<div class="form-group">
<?= "<?= " ?>Html::submitButton('<i class="fa fa-filter"></i>', ['class' => 'btn btn-default']) ?>
<?= "<?= " ?>Html::resetButton('<i class="fa fa-eraser"></i>', ['class' => 'btn btn-default']) ?>
</div>
</div> </div>
<?= "<?php " ?>ActiveForm::end(); ?>
</div> </div>
<?= "<?php " ?>ActiveForm::end(); ?>

100
vendor/blobt/generators/crud/default/views/index.php

@ -23,83 +23,39 @@ use blobt\grid\GridView;
$this->title = <?= $generator->generateString(Inflector::pluralize(Inflector::camel2words(StringHelper::basename($generator->modelClass)))) ?>; $this->title = <?= $generator->generateString(Inflector::pluralize(Inflector::camel2words(StringHelper::basename($generator->modelClass)))) ?>;
$this->params['breadcrumbs'][] = $this->title; $this->params['breadcrumbs'][] = $this->title;
?> ?>
<div class="row"> <div class="row">
<div class="col-xs-12"> <div class="col-xs-12">
<?= "<?= " ?>
GridView::widget([
<?= "<?= " ?>GridView::widget([
'dataProvider' => $dataProvider, 'dataProvider' => $dataProvider,
'filter' => $this->render("_search", ['model' => $searchModel]), 'filter' => $this->render("_search", ['model' => $searchModel]),
batch' => [
[
"label" => "删除",
"url" => "/category/deletes"
],
'batch' => [
[
"label" => "删除",
"url" => "<?=$generator->controllerID?>/deletes"
], ],
'columns' => [
],
'columns' => [
[
'class' => 'blobt\grid\CheckboxColumn',
'width' => '2%',
'align' => 'center'
], ],
]);
<?= "?>" ?>
</div>
</div>
<div class="<?= Inflector::camel2id(StringHelper::basename($generator->modelClass)) ?>-index">
<h2><?= "<?= " ?>Html::encode($this->title) ?></h2>
<p>
<?= "<?= " ?>Html::a(<?= $generator->generateString('Create ' . Inflector::camel2words(StringHelper::basename($generator->modelClass))) ?>, ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= $generator->enablePjax ? " <?php Pjax::begin(); ?>\n" : '' ?>
<?php if (!empty($generator->searchModelClass)): ?>
<?= " <?php " . ($generator->indexWidgetType === 'grid' ? "// " : "") ?>echo $this->render('_search', ['model' => $searchModel]); ?>
<?php endif; ?>
<?php if ($generator->indexWidgetType === 'grid'): ?>
<?= "<?= " ?>GridView::widget([
'dataProvider' => $dataProvider,
<?= !empty($generator->searchModelClass) ? "'filterModel' => \$searchModel,\n 'columns' => [\n" : "'columns' => [\n"; ?>
['class' => 'yii\grid\SerialColumn'],
<?php
$count = 0;
if (($tableSchema = $generator->getTableSchema()) === false) {
foreach ($generator->getColumnNames() as $name) {
if (++$count < 6) {
echo " '" . $name . "',\n";
} else {
echo " //'" . $name . "',\n";
}
}
<?php
$count = 0;
foreach ($generator->getColumnNames() as $name) {
if (++$count < 6) {
echo " '" . $name . "',\n";
} else { } else {
foreach ($tableSchema->columns as $column) {
$format = $generator->generateColumnFormat($column);
if (++$count < 6) {
echo " '" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
} else {
echo " //'" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
}
}
echo " //'" . $name . "',\n";
} }
?>
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php else: ?>
<?= "<?= " ?>ListView::widget([
'dataProvider' => $dataProvider,
'itemOptions' => ['class' => 'item'],
'itemView' => function ($model, $key, $index, $widget) {
return Html::a(Html::encode($model-><?= $nameAttribute ?>), ['view', <?= $urlParams ?>]);
},
]) ?>
<?php endif; ?>
<?= $generator->enablePjax ? " <?php Pjax::end(); ?>\n" : '' ?>
</div>
}
?>
[
'class' => 'blobt\grid\ActionColumn',
'align' => 'center'
],
]
]);
<?= "?>" ?>
</div>
</div>
Loading…
Cancel
Save