Skip to content

Commit

Permalink
51siyuan
Browse files Browse the repository at this point in the history
  • Loading branch information
yidashi committed Dec 14, 2016
1 parent 13d2e41 commit 826e2ba
Show file tree
Hide file tree
Showing 33 changed files with 1,523 additions and 129 deletions.
2 changes: 1 addition & 1 deletion backend/behaviors/DynamicFormBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function getAttributeType($attribute)
if(is_string($this->formAttributes[$attribute])) {
return $this->formAttributes[$attribute];
} else {
return isset($this->formAttributes[$attribute]['type']) ? $this->formAttributes[$attribute]['type'] : 'text';
return ArrayHelper::getValue($this->formAttributes[$attribute], 'type', 'text');
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion backend/controllers/AreaController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class AreaController extends Controller
public function actionIndex()
{
return $this->render("index", [
"blocks" => Block::find()->where(["used" => BooleanEnum::FLASE])->all(),
"blocks" => Block::find()->all(),
"areas" => Area::find()->all()
]);
}
Expand Down
2 changes: 2 additions & 0 deletions backend/controllers/ArticleController.php
Original file line number Diff line number Diff line change
Expand Up @@ -181,8 +181,10 @@ public function actionCreate($module = 'base')
}

$transaction->commit();
Yii::$app->session->setFlash('success', '发布成功');
} catch (\Exception $e) {
$transaction->rollBack();
Yii::$app->session->setFlash('error', $e->getMessage());
}
return $this->redirect(['index']);
}
Expand Down
30 changes: 11 additions & 19 deletions backend/controllers/BlockController.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,35 +32,28 @@ public function actionIndex()
/**
* Creates a new Area model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @param string $type
* @return mixed
*/
public function actionCreate($type=null)
public function actionCreate($type = 'text')
{
if($type == null)
{
$type = 'text';
}

// list($title,$model,$view,$widget) = AreaHelp::getBlockHook($type);

// $model = \Yii::createObject($model);
$model = new Block();
$model->loadDefaultValues();
$model->type = $type;
$model->widget = TextWidget::className();
$this->performAjaxValidation($model);
$model->widget = $model->getWidget();

if ($model->load(Yii::$app->request->post()))
{
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
Yii::$app->session->setFlash('success', Yii::t('common', 'created success'));
Yii::$app->session->setFlash('success', '操作成功');
} else {
Yii::$app->session->setFlash('error', Yii::t('common', 'created error. {0}', $model->formatErrors()));
Yii::$app->session->setFlash('error', current($model->getFirstErrors()));
}
return $this->refresh();
}

return $this->render('create',["model"=>$model]);
return $this->render('create',[
'model' => $model,
]);
}


Expand All @@ -69,15 +62,14 @@ public function actionCreate($type=null)
/**
* Creates a new Area model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);

$this->performAjaxValidation($model);
if ($model->load(Yii::$app->request->post()))
{
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
Yii::$app->session->setFlash('success', Yii::t('common', 'updated success'));
} else {
Expand Down
3 changes: 2 additions & 1 deletion backend/models/search/Article.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public function rules()
{
return [
[['id', 'category_id', 'created_at', 'updated_at', 'status'], 'integer'],
[['title', 'category', 'cover'], 'string'],
[['title', 'category', 'cover', 'module'], 'string'],
];
}

Expand Down Expand Up @@ -62,6 +62,7 @@ public function search($params)
'id' => $this->id,
'category_id' => $this->category_id,
'status' => $this->status,
'module' => $this->module,
]);

$query->andFilterWhere(['like', 'title', $this->title])
Expand Down
275 changes: 275 additions & 0 deletions backend/modules/migration/console/MigrateController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,275 @@
<?php
/**
* Created by PhpStorm.
* Author: ljt
* DateTime: 2016/11/25 11:30
* Description:
*/

namespace backend\modules\migration\console;

use migration\models\MigrationUtility;
use Yii;
use yii\base\Object;
use yii\helpers\Console;
use yii\helpers\FileHelper;
use migration\AppUtility;


class MigrateController extends \yii\console\controllers\MigrateController
{
/**
* dump migrate file
*
* @return string
*/
public function actionDump()
{
set_time_limit(0);
$model = new MigrationUtility();
$upStr = new OutputString();
$downStr = new OutputString();
$data = [
'tableSchemas' => array_keys(MigrationUtility::getTableNames()),
'tableDatas' => array_keys(MigrationUtility::getTableNames()),
'migrationPath' => $this->migrationPath
];
if ($model->load($data, '')) {

if (!empty($model->tableSchemas)) {
list ($up, $down) = $this->generalTableSchemas($model->tableSchemas, $model->tableOption);
$upStr->outputStringArray = array_merge($upStr->outputStringArray, $up->outputStringArray);
$downStr->outputStringArray = array_merge($downStr->outputStringArray, $down->outputStringArray);
}

if (! empty($model->tableDatas)) {
list ($up, $down) = $this->generalTableDatas($model->tableDatas);
$upStr->outputStringArray = array_merge($upStr->outputStringArray, $up->outputStringArray);
$downStr->outputStringArray = array_merge($downStr->outputStringArray, $down->outputStringArray);
}

$path = Yii::getAlias($model->migrationPath);
if (!is_dir($path)) {
FileHelper::createDirectory($path);
}

$name = 'm' . gmdate('ymd_His') . '_' . $model->migrationName;
$file = $path . DIRECTORY_SEPARATOR . $name . '.php';

$content = $this->renderFile(Yii::getAlias("@backend/modules/migration/views/migration.php"), [
'className' => $name,
'up' => $upStr->output(),
'down' => $downStr->output()
]);
file_put_contents($file, $content);
$this->stdout('成功生成迁移文件 ' . $file, Console::FG_GREEN);
}
}

public function getTableName($name)
{
$prefix = \Yii::$app->db->tablePrefix;

return str_replace($prefix, '', $name);
}

public function generalTableSchemas($tables, $tableOption)
{
$initialTabLevel = 0;
$upStr = new OutputString([
'tabLevel' => $initialTabLevel
]);

$upStr->addStr('$this->execute(\'SET foreign_key_checks = 0\');');
$upStr->addStr(' ');
foreach ($tables as $table) {
$upStr->tabLevel = $initialTabLevel;

$tablePrepared = $this->getTableName($table);

// 添加表结构
$upStr->addStr('$this->createTable(\'{{%' . $tablePrepared . '}}\', [');
$upStr->tabLevel ++;
$tableSchema = \Yii::$app->db->getTableSchema($table);

foreach ($tableSchema->columns as $column) {
$appUtility = new AppUtility($column);
$upStr->addStr($appUtility->string . "',");
}
if (! empty($tableSchema->primaryKey)) {
$upStr->addStr("'PRIMARY KEY (`" . implode("`,`", $tableSchema->primaryKey) . "`)'");
}

$upStr->tabLevel --;
$upStr->addStr('], "' . $tableOption . '");');


// 添加索引
$tableIndexes = Yii::$app->db->createCommand('SHOW INDEX FROM `' . $table . '`')->queryAll();
$indexs = [];
foreach ($tableIndexes as $item) {
if ($item['Key_name'] == 'PRIMARY') {
continue;
}
if (! isset($indexs[$item["Key_name"]])) {
$indexs[$item["Key_name"]] = [];
$indexs[$item["Key_name"]]["unique"] = ($item['Non_unique']) ? 0 : 1;
}
$indexs[$item["Key_name"]]["columns"][] = $item['Column_name'];
}

if (! empty($indexs)) {
$upStr->addStr(' ');
}

foreach ($indexs as $index => $item) {
$str = '$this->createIndex(\'' . $index . '\',\'{{%' . $tablePrepared . '}}\',\'' . implode(', ', $item['columns']) . '\',' . $item['unique'] . ');';
$upStr->addStr($str);
}

$upStr->addStr(' ');
}

//添加外键
$sql = "SELECT tb1.CONSTRAINT_NAME, tb1.TABLE_NAME, tb1.COLUMN_NAME,
tb1.REFERENCED_TABLE_NAME, tb1.REFERENCED_COLUMN_NAME, tb2.MATCH_OPTION,
tb2.UPDATE_RULE, tb2.DELETE_RULE
FROM information_schema.KEY_COLUMN_USAGE AS tb1
INNER JOIN information_schema.REFERENTIAL_CONSTRAINTS AS tb2 ON
tb1.CONSTRAINT_NAME = tb2.CONSTRAINT_NAME AND tb1.CONSTRAINT_SCHEMA = tb2.CONSTRAINT_SCHEMA
WHERE TABLE_SCHEMA = DATABASE()
AND REFERENCED_TABLE_SCHEMA = DATABASE() AND REFERENCED_COLUMN_NAME IS NOT NULL";
$foreignKeys = Yii::$app->db->createCommand($sql)->queryAll();
foreach ($foreignKeys as $fk)
{
$str = '$this->addForeignKey(';
$str .= '\'' . $fk['CONSTRAINT_NAME'] . '\', ';
$str .= '\'{{%' . $this->getTableName($fk['TABLE_NAME']) . '}}\', ';
$str .= '\'' . $fk['COLUMN_NAME'] . '\', ';
$str .= '\'{{%' . $this->getTableName($fk['REFERENCED_TABLE_NAME']) . '}}\', ';
$str .= '\'' . $fk['REFERENCED_COLUMN_NAME'] . '\', ';
$str .= '\'' . $fk['DELETE_RULE'] . '\', ';
$str .= '\'' . $fk['UPDATE_RULE'] . '\' ';
$str .= ');';
$upStr->addStr($str);
}


$upStr->addStr(' ');
$upStr->addStr('$this->execute(\'SET foreign_key_checks = 1;\');');

$downStr = new OutputString();
/* DROP TABLE */
$downStr->addStr('$this->execute(\'SET foreign_key_checks = 0\');');
foreach ($tables as $table) {
if (! empty($table)) {
$downStr->addStr('$this->dropTable(\'{{%' . $tablePrepared . '}}\');');
}
}
$downStr->addStr('$this->execute(\'SET foreign_key_checks = 1;\');');

return [
$upStr,
$downStr
];
}

public function generalTableDatas($tables)
{
$initialTabLevel = 0;
$upStr = new OutputString([
'tabLevel' => $initialTabLevel
]);
$upStr->addStr('$this->execute(\'SET foreign_key_checks = 0\');');
$upStr->addStr(' ');
foreach ($tables as $table) {

$tablePrepared = $this->getTableName($table);

$upStr->addStr('/* Table ' . $table . ' */');
$tableSchema = \Yii::$app->db->getTableSchema($table);
$data = Yii::$app->db->createCommand('SELECT * FROM `' . $table . '`')->queryAll();
$out = '$this->batchInsert(\'{{%' . $tablePrepared . '}}\',[';
foreach ($tableSchema->columns as $column) {
$out .= "'" . $column->name . "',";
}
$out = rtrim($out, ',') . '],[';
foreach ($data as $row) {
$out .= '[';
foreach ($row as $field) {
if ($field === null) {
$out .= "null,";
} else {
$out .= "'" . addcslashes($field, "'") . "',";
}
}
$out = rtrim($out, ',') . "],\n";
}
$out = rtrim($out, ',') . ']);';
$upStr->addStr($out);
$upStr->addStr(' ');
}
$upStr->addStr('$this->execute(\'SET foreign_key_checks = 1;\');');
$downStr = new OutputString();
return [
$upStr,
$downStr
];
}
}

/**
* Class OutputString
*
* @author Nils Lindentals <[email protected]>
*
* @package c006\utility\migration\controllers
*/
class OutputString extends Object
{

/**
*
* @var string
*/
public $nw = "\n";

/**
*
* @var string
*/
public $tab = "\t";

/**
*
* @var string
*/
public $outputStringArray = array();

/**
*
* @var int
*/
public $tabLevel = 0;

/**
* Adds string to output string array with "tab" prefix
*
* @var string $str
*/
public function addStr($str)
{
$str = str_replace($this->tab, '', $str);
$this->outputStringArray[] = str_repeat($this->tab, $this->tabLevel) . $str;
}

/**
* Returns string output
*/
public function output()
{
return implode($this->nw, $this->outputStringArray);
}
}
Loading

0 comments on commit 826e2ba

Please sign in to comment.