Commit 4aea8ca8 authored by Tobias Munk's avatar Tobias Munk

php-cs-fixer

parent 5b11e7df
<?php
/**
* @link http://www.diemeisterei.de/
*
* @copyright Copyright (c) 2014 diemeisterei GmbH, Stuttgart
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* file that was distributed with this source code
*/
namespace schmunk42\giiant;
use yii\base\Application;
use yii\base\BootstrapInterface;
/**
* Class Bootstrap
* @package schmunk42\giiant
* Class Bootstrap.
*
* @author Tobias Munk <tobias@diemeisterei.de>
*/
class Bootstrap implements BootstrapInterface
{
/**
* Bootstrap method to be called during application bootstrap stage.
*
......@@ -29,23 +27,21 @@ class Bootstrap implements BootstrapInterface
public function bootstrap($app)
{
if ($app->hasModule('gii')) {
if (!isset($app->getModule('gii')->generators['giiant-model'])) {
$app->getModule('gii')->generators['giiant-model'] = 'schmunk42\giiant\generators\model\Generator';
}
if (!isset($app->getModule('gii')->generators['giiant-extension'])) {
$app->getModule('gii')->generators['giiant-extension'] = 'schmunk42\giiant\generators\extension\Generator';
}
if (!isset($app->getModule('gii')->generators['giiant-crud'])) {
$app->getModule('gii')->generators['giiant-crud'] = [
'class' => 'schmunk42\giiant\generators\crud\Generator',
$app->getModule('gii')->generators['giiant-crud'] = [
'class' => 'schmunk42\giiant\generators\crud\Generator',
'templates' => [
'editable' => __DIR__.'/generators/crud/editable',
]
],
];
}
if (!isset($app->getModule('gii')->generators['giiant-module'])) {
......@@ -61,4 +57,4 @@ class Bootstrap implements BootstrapInterface
}
}
}
}
\ No newline at end of file
}
......@@ -3,12 +3,10 @@
* Created by PhpStorm.
* User: tobias
* Date: 19.03.14
* Time: 01:02
* Time: 01:02.
*/
namespace schmunk42\giiant\base;
use yii\base\Object;
class Provider extends Object
......@@ -21,4 +19,4 @@ class Provider extends Object
public $columnNames = [];
public $columnPatterns = [];
}
\ No newline at end of file
}
......@@ -35,14 +35,14 @@ class BatchController extends Controller
/**
* @var string the name of the table containing the translations. {{table}} will be replaced with the value in
* "Table Name" field.
* "Table Name" field
*/
public $languageTableName = "{{table}}_lang";
public $languageTableName = '{{table}}_lang';
/**
* @var string the column name where the language code is stored.
* @var string the column name where the language code is stored
*/
public $languageCodeColumn = "language";
public $languageCodeColumn = 'language';
/**
* @var bool whether to overwrite extended models (from ModelBase)
......@@ -95,24 +95,24 @@ class BatchController extends Controller
public $modelRemoveDuplicateRelations = false;
/**
* @var boolean whether the strings will be generated using `Yii::t()` or normal strings.
* @var bool whether the strings will be generated using `Yii::t()` or normal strings
*/
public $enableI18N = true;
/**
* @var boolean whether the entity names will be singular or the same as the table name.
* @var bool whether the entity names will be singular or the same as the table name
*/
public $singularEntities = true;
/**
* @var string the message category for models used by `Yii::t()` when `$enableI18N` is `true`.
* Defaults to `app`.
* Defaults to `app`
*/
public $modelMessageCategory = 'models';
/**
* @var string the message category for CRUDs used by `Yii::t()` when `$enableI18N` is `true`.
* Defaults to `app`.
* Defaults to `app`
*/
public $crudMessageCategory = 'cruds';
......@@ -157,7 +157,7 @@ class BatchController extends Controller
public $crudSkipRelations = [];
/**
* @var boolean whether to add accessFilter in behavior
* @var bool whether to add accessFilter in behavior
*/
public $crudAccessFilter;
......@@ -186,12 +186,12 @@ class BatchController extends Controller
public $modelQueryBaseClass = 'yii\db\ActiveQuery';
/**
* @var bool This indicates whether the generator should generate attribute labels by using the comments of the corresponding DB columns.
* @var bool This indicates whether the generator should generate attribute labels by using the comments of the corresponding DB columns
*/
public $modelGenerateLabelsFromComments = false;
/**
* @var bool This indicates whether the generator should generate attribute hints by using the comments of the corresponding DB columns.
* @var bool This indicates whether the generator should generate attribute hints by using the comments of the corresponding DB columns
*/
public $modelGenerateHintsFromComments = true;
/**
......@@ -205,7 +205,7 @@ class BatchController extends Controller
protected $modelGenerator;
/**
* @inheritdoc
* {@inheritdoc}
*/
public function options($id)
{
......@@ -251,7 +251,7 @@ class BatchController extends Controller
}
/**
* Loads application configuration and checks tables parameter
* Loads application configuration and checks tables parameter.
*
* @param \yii\base\Action $action
*
......@@ -277,9 +277,9 @@ class BatchController extends Controller
}
/**
* Run batch process to generate models and CRUDs for all given tables
* Run batch process to generate models and CRUDs for all given tables.
*
* @param string $message the message to be echoed.
* @param string $message the message to be echoed
*/
public function actionIndex()
{
......@@ -289,14 +289,15 @@ class BatchController extends Controller
}
/**
* Run batch process to generate models all given tables
* Run batch process to generate models all given tables.
*
* @throws \yii\console\Exception
*/
public function actionModels()
{
// create models
foreach ($this->tables AS $table) {
#var_dump($this->tableNameMap, $table);exit;
foreach ($this->tables as $table) {
//var_dump($this->tableNameMap, $table);exit;
$params = [
'interactive' => $this->interactive,
'overwrite' => $this->overwrite,
......@@ -336,11 +337,11 @@ class BatchController extends Controller
\Yii::$app = $app;
\Yii::$app->log->logger->flush(true);
}
}
/**
* Run batch process to generate CRUDs all given tables
* Run batch process to generate CRUDs all given tables.
*
* @throws \yii\console\Exception
*/
public function actionCruds()
......@@ -352,7 +353,7 @@ class BatchController extends Controller
$this->createDirectoryFromNamespace($this->crudControllerNamespace);
$this->createDirectoryFromNamespace($this->crudSearchModelNamespace);
foreach ($this->tables AS $table) {
foreach ($this->tables as $table) {
$table = str_replace($this->tablePrefix, '', $table);
$name = isset($this->tableNameMap[$table]) ? $this->tableNameMap[$table] :
$this->modelGenerator->generateClassName($table);
......@@ -360,10 +361,10 @@ class BatchController extends Controller
'interactive' => $this->interactive,
'overwrite' => $this->overwrite,
'template' => $this->template,
'modelClass' => $this->modelNamespace . '\\' . $name,
'searchModelClass' => $this->crudSearchModelNamespace . '\\' . $name . $this->crudSearchModelSuffix,
'modelClass' => $this->modelNamespace.'\\'.$name,
'searchModelClass' => $this->crudSearchModelNamespace.'\\'.$name.$this->crudSearchModelSuffix,
'controllerNs' => $this->crudControllerNamespace,
'controllerClass' => $this->crudControllerNamespace . '\\' . $name . 'Controller',
'controllerClass' => $this->crudControllerNamespace.'\\'.$name.'Controller',
'viewPath' => $this->crudViewPath,
'pathPrefix' => $this->crudPathPrefix,
'tablePrefix' => $this->tablePrefix,
......@@ -391,9 +392,10 @@ class BatchController extends Controller
}
/**
* Returns Yii's initial configuration array
* Returns Yii's initial configuration array.
*
* @todo should be removed, if this issue is closed -> https://github.com/yiisoft/yii2/pull/5687
*
* @return array
*/
protected function getYiiConfiguration()
......@@ -402,30 +404,29 @@ class BatchController extends Controller
$config = $GLOBALS['config'];
} else {
$config = \yii\helpers\ArrayHelper::merge(
require(\Yii::getAlias('@app') . '/../common/config/main.php'),
(is_file(\Yii::getAlias('@app') . '/../common/config/main-local.php')) ?
require(\Yii::getAlias('@app') . '/../common/config/main-local.php')
require(\Yii::getAlias('@app').'/../common/config/main.php'),
(is_file(\Yii::getAlias('@app').'/../common/config/main-local.php')) ?
require(\Yii::getAlias('@app').'/../common/config/main-local.php')
: [],
require(\Yii::getAlias('@app') . '/../console/config/main.php'),
(is_file(\Yii::getAlias('@app') . '/../console/config/main-local.php')) ?
require(\Yii::getAlias('@app') . '/../console/config/main-local.php')
require(\Yii::getAlias('@app').'/../console/config/main.php'),
(is_file(\Yii::getAlias('@app').'/../console/config/main-local.php')) ?
require(\Yii::getAlias('@app').'/../console/config/main-local.php')
: []
);
}
return $config;
}
/**
* Helper function to create
* Helper function to create.
*
* @param $ns Namespace
*/
private function createDirectoryFromNamespace($ns)
{
echo \Yii::getRootAlias($ns);
$dir = \Yii::getAlias('@' . str_replace('\\', '/', ltrim($ns, '\\')));
$dir = \Yii::getAlias('@'.str_replace('\\', '/', ltrim($ns, '\\')));
@mkdir($dir);
}
}
......@@ -57,7 +57,6 @@ class Generator extends \yii\gii\generators\crud\Generator
/**
* @var string Bootstrap CSS-class for form-layout
*/
public $formLayout = 'horizontal';
/**
......@@ -94,7 +93,7 @@ class Generator extends \yii\gii\generators\crud\Generator
* @var bool whether to add an access filter to controllers
*/
public $accessFilter = false;
public $generateAccessFilterMigrations = false;
public $baseTraits;
......@@ -125,13 +124,13 @@ class Generator extends \yii\gii\generators\crud\Generator
public $tidyOutput;
/**
* @var string form field for selecting and loading saved gii forms
* @var string form field for selecting and loading saved gii forms
*/
public $savedForm;
public $moduleNs;
public $migrationClass;
private $_p = [];
/**
......@@ -190,7 +189,7 @@ class Generator extends \yii\gii\generators\crud\Generator
/**
* {@inheritdoc}
*/
public function rules()
public function rules()
{
return array_merge(
parent::rules(), [
......@@ -204,9 +203,9 @@ class Generator extends \yii\gii\generators\crud\Generator
'formLayout',
'accessFilter',
'singularEntities',
'modelMessageCategory'
],
'safe'
'modelMessageCategory',
],
'safe',
],
[['viewPath'], 'required'],
]
......@@ -222,7 +221,8 @@ class Generator extends \yii\gii\generators\crud\Generator
}
/**
* all form fields for saving in saved forms
* all form fields for saving in saved forms.
*
* @return array
*/
public function formAttributes()
......@@ -238,15 +238,15 @@ class Generator extends \yii\gii\generators\crud\Generator
'singularEntities',
'indexWidgetType',
'formLayout',
'actionButtonClass',
'actionButtonClass',
'providerList',
'template',
'accessFilter',
'singularEntities',
'modelMessageCategory'
'modelMessageCategory',
];
}
/**
* @return string the action view file path
*/
......@@ -278,22 +278,22 @@ class Generator extends \yii\gii\generators\crud\Generator
*/
public function getModuleId()
{
if(!$this->moduleNs){
if (!$this->moduleNs) {
$controllerNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerClass, '\\'));
$this->moduleNs = \yii\helpers\StringHelper::dirname(ltrim($controllerNs, '\\'));
}
return \yii\helpers\StringHelper::basename($this->moduleNs);
}
public function generate()
{
$accessDefinitions = require($this->getTemplatePath() . '/access_definition.php');
$accessDefinitions = require $this->getTemplatePath().'/access_definition.php';
$this->controllerNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerClass, '\\'));
$this->moduleNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerNs, '\\'));
$controllerName = substr(\yii\helpers\StringHelper::basename($this->controllerClass),0,-10);
$controllerName = substr(\yii\helpers\StringHelper::basename($this->controllerClass), 0, -10);
if ($this->singularEntities) {
$this->modelClass = Inflector::singularize($this->modelClass);
$this->controllerClass = Inflector::singularize(
......@@ -306,19 +306,19 @@ class Generator extends \yii\gii\generators\crud\Generator
$baseControllerFile = StringHelper::dirname($controllerFile).'/base/'.StringHelper::basename($controllerFile);
$restControllerFile = StringHelper::dirname($controllerFile).'/api/'.StringHelper::basename($controllerFile);
/**
/*
* search generated migration and overwrite it or create new
*/
$migrationDir = StringHelper::dirname(StringHelper::dirname($controllerFile))
. '/migrations';
if(file_exists($migrationDir) && $migrationDirFiles = glob($migrationDir .'/m*_' . $controllerName . '00_access.php')){
$migrationDir = StringHelper::dirname(StringHelper::dirname($controllerFile))
.'/migrations';
if (file_exists($migrationDir) && $migrationDirFiles = glob($migrationDir.'/m*_'.$controllerName.'00_access.php')) {
$this->migrationClass = pathinfo($migrationDirFiles[0], PATHINFO_FILENAME);
}else{
$this->migrationClass = 'm' . date("ymd_Hi") . '00_' . $controllerName . '_access';
}
$files[] = new CodeFile($baseControllerFile, $this->render('controller.php',['accessDefinitions' => $accessDefinitions]));
} else {
$this->migrationClass = 'm'.date('ymd_Hi').'00_'.$controllerName.'_access';
}
$files[] = new CodeFile($baseControllerFile, $this->render('controller.php', ['accessDefinitions' => $accessDefinitions]));
$params['controllerClassName'] = \yii\helpers\StringHelper::basename($this->controllerClass);
if ($this->overwriteControllerClass || !is_file($controllerFile)) {
......@@ -328,7 +328,7 @@ class Generator extends \yii\gii\generators\crud\Generator
if ($this->overwriteRestControllerClass || !is_file($restControllerFile)) {
$files[] = new CodeFile($restControllerFile, $this->render('controller-rest.php', $params));
}
if (!empty($this->searchModelClass)) {
$searchModel = Yii::getAlias('@'.str_replace('\\', '/', ltrim($this->searchModelClass, '\\').'.php'));
if ($this->overwriteSearchModelClass || !is_file($searchModel)) {
......@@ -345,41 +345,40 @@ class Generator extends \yii\gii\generators\crud\Generator
}
if (is_file($templatePath.'/'.$file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
echo $file;
$files[] = new CodeFile("$viewPath/$file", $this->render("views/$file",['permisions' => $permisions]));
$files[] = new CodeFile("$viewPath/$file", $this->render("views/$file", ['permisions' => $permisions]));
}
}
if ($this->generateAccessFilterMigrations){
/**
if ($this->generateAccessFilterMigrations) {
/*
* access migration
*/
$migrationFile = $migrationDir . '/' . $this->migrationClass . '.php' ;
$migrationFile = $migrationDir.'/'.$this->migrationClass.'.php';
//var_dump($migrationFile);exit;
$files[] = new CodeFile($migrationFile, $this->render('migration_access.php',['accessDefinitions' => $accessDefinitions]));
$files[] = new CodeFile($migrationFile, $this->render('migration_access.php', ['accessDefinitions' => $accessDefinitions]));
/**
/*
* access roles translation
*/
$forRoleTranslationFile = StringHelper::dirname(StringHelper::dirname($controllerFile))
. '/messages/for-translation/'
. $controllerName.'.php' ;
$files[] = new CodeFile($forRoleTranslationFile, $this->render('roles-translation.php',['accessDefinitions' => $accessDefinitions]));
$forRoleTranslationFile = StringHelper::dirname(StringHelper::dirname($controllerFile))
.'/messages/for-translation/'
.$controllerName.'.php';
$files[] = new CodeFile($forRoleTranslationFile, $this->render('roles-translation.php', ['accessDefinitions' => $accessDefinitions]));
}
/**
/*
* create gii/[name]GiantCRUD.json with actual form data
*/
$suffix = str_replace(' ','', $this->getName());
$suffix = str_replace(' ', '', $this->getName());
$controllerFileinfo = pathinfo($controllerFile);
$formDataFile = StringHelper::dirname(StringHelper::dirname($controllerFile))
. '/gii/'
. str_replace('Controller',$suffix,$controllerFileinfo['filename']).'.json' ;
$formDataFile = StringHelper::dirname(StringHelper::dirname($controllerFile))
.'/gii/'
.str_replace('Controller', $suffix, $controllerFileinfo['filename']).'.json';
//$formData = json_encode($this->getFormAttributesValues());
$formData = json_encode(SaveForm::getFormAttributesValues($this,$this->formAttributes()));
$formData = json_encode(SaveForm::getFormAttributesValues($this, $this->formAttributes()));
$files[] = new CodeFile($formDataFile, $formData);
return $files;
}
......@@ -407,24 +406,26 @@ class Generator extends \yii\gii\generators\crud\Generator
}
parent::validateClass($attribute, $params);
}
public function var_export54($var, $indent="") {
public function var_export54($var, $indent = '')
{
switch (gettype($var)) {
case "string":
return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
case "array":
case 'string':
return '"'.addcslashes($var, "\\\$\"\r\n\t\v\f").'"';
case 'array':
$indexed = array_keys($var) === range(0, count($var) - 1);
$r = [];
foreach ($var as $key => $value) {
$r[] = "$indent "
. ($indexed ? "" : $this->var_export54($key) . " => ")
. $this->var_export54($value, "$indent ");
.($indexed ? '' : $this->var_export54($key).' => ')
.$this->var_export54($value, "$indent ");
}
return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
case "boolean":
return $var ? "TRUE" : "FALSE";
return "[\n".implode(",\n", $r)."\n".$indent.']';
case 'boolean':
return $var ? 'TRUE' : 'FALSE';
default:
return var_export($var, TRUE);
return var_export($var, true);
}
}
}
}
......@@ -97,10 +97,10 @@ trait ModelTrait
try {
$relation = @call_user_func(array($model, $method->name));
if ($relation instanceof \yii\db\ActiveQuery) {
#var_dump($relation->primaryModel->primaryKey);
//var_dump($relation->primaryModel->primaryKey);
if ($relation->multiple === false) {
$relationType = 'belongs_to';
} elseif ($this->isPivotRelation($relation)) { # TODO: detecttion
} elseif ($this->isPivotRelation($relation)) { // TODO: detecttion
$relationType = 'pivot';
} else {
$relationType = 'has_many';
......
......@@ -8,7 +8,7 @@ namespace schmunk42\giiant\generators\crud;
* @copyright Copyright (c) 2015 diemeisterei GmbH, Stuttgart
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* file that was distributed with this source code
*/
trait ParamTrait
{
......
......@@ -17,7 +17,7 @@ use yii\helpers\Json;
trait ProviderTrait
{
/**
* @return array Class names of the providers declared directly under crud/providers folder.
* @return array Class names of the providers declared directly under crud/providers folder
*/
public static function getCoreProviders()
{
......@@ -42,7 +42,7 @@ trait ProviderTrait
}
/**
* @return array List of providers. Keys and values contain the same strings.
* @return array List of providers. Keys and values contain the same strings
*/
public function generateProviderCheckboxListData()
{
......@@ -67,7 +67,7 @@ trait ProviderTrait
$obj = \Yii::createObject(['class' => $class]);
$obj->generator = $this;
$this->_p[] = $obj;
#\Yii::trace("Initialized provider '{$class}'", __METHOD__);
//\Yii::trace("Initialized provider '{$class}'", __METHOD__);
}
}
......@@ -164,7 +164,7 @@ trait ProviderTrait
}
// don't call parent anymore
}
public function attributeEditable($attribute, $model = null)
{
if ($model === null) {
......
......@@ -24,7 +24,6 @@ class Db
case 'longtext':
return false;
}
};
}
......@@ -32,7 +31,6 @@ class Db
{
// hide AI columns
return function ($attribute, $model, $generator) {
$column = $generator->getColumnByAttribute($attribute);
if (!$column) {
return;
......@@ -41,7 +39,6 @@ class Db
if ($column->autoIncrement) {
return false;
}
};
}
}
<?php
use schmunk42\giiant\helpers\SaveForm;
/**
/*
* @var yii\web\View
* @var yii\widgets\ActiveForm $form
* @var yii\gii\generators\crud\Generator $generator
*/
/**
/*
* JS for listbox "Saved Form"
* on chenging listbox, form fill with selected saved forma data
* currently work with input text, input checkbox and select form fields
......
......@@ -104,11 +104,11 @@ EOS;
return;
}
# handle columns with a primary key, to create links in pivot tables (changed at 0.3-dev; 03.02.2015)
# TODO double check with primary keys not named `id` of non-pivot tables
# TODO Note: condition does not apply in every case
// handle columns with a primary key, to create links in pivot tables (changed at 0.3-dev; 03.02.2015)
// TODO double check with primary keys not named `id` of non-pivot tables
// TODO Note: condition does not apply in every case
if ($column->isPrimaryKey) {
#return null; #TODO: double check with primary keys not named `id` of non-pivot tables
//return null; #TODO: double check with primary keys not named `id` of non-pivot tables
}
$relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column);
......@@ -163,11 +163,11 @@ EOS;
return;
}
# handle columns with a primary key, to create links in pivot tables (changed at 0.3-dev; 03.02.2015)
# TODO double check with primary keys not named `id` of non-pivot tables
# TODO Note: condition does not apply in every case
// handle columns with a primary key, to create links in pivot tables (changed at 0.3-dev; 03.02.2015)
// TODO double check with primary keys not named `id` of non-pivot tables
// TODO Note: condition does not apply in every case
if ($column->isPrimaryKey) {
#return null;
//return null;
}
$relation = $this->generator->getRelationByColumn($model, $column);
......@@ -208,9 +208,9 @@ EOS;
'format' => 'raw',
]
EOS;
return $code;
}
}
/**
......
......@@ -32,7 +32,7 @@ EOS;
return;
}
}
/**
* Formatter for detail view attributes, who have get[..]ValueLabel function.
*
......@@ -49,7 +49,7 @@ EOS;
return;
}
if($column->type != 'date'){
if ($column->type != 'date') {
return;
}
......@@ -70,5 +70,5 @@ EOS;
]).'</div>',
]
EOS;
}
}
}
......@@ -10,29 +10,27 @@ use yii\helpers\Inflector;
*
* @author Uldis Nelsons
*/
class EditableProvider extends \schmunk42\giiant\base\Provider {
class EditableProvider extends \schmunk42\giiant\base\Provider
{
public $skipVirtualAttributes = false;
/**
*
*
* @param $column ColumnSchema
*
* @return null|string
*/
public function attributeEditable($attribute) {
public function attributeEditable($attribute)
{
$this->generator->requires[] = '"kartik-v/yii2-editable": "@dev"';
$primaryKey = implode('_', $this->generator->getTableSchema()->primaryKey);
$column = $this->generator->getTableSchema()->columns[$attribute];
/**
/*
* search opts... method
*/
$modelClass = $this->generator->modelClass;
$optsFunc = 'opts' . str_replace('_', '', $attribute);
$optsCamelFunc = 'opts' . str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute))));
$optsFunc = 'opts'.str_replace('_', '', $attribute);
$optsCamelFunc = 'opts'.str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute))));
$useOptsFunc = false;
if (method_exists($modelClass::className(), $optsFunc)) {
......@@ -43,12 +41,13 @@ class EditableProvider extends \schmunk42\giiant\base\Provider {
$inputType = $this->getInputType($column);
$relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column);
if($relation){
$relModelStatic = $relation->modelClass . 'Static';
}
if ($relation) {
$relModelStatic = $relation->modelClass.'Static';
}
if ($relation && !$relation->multiple && method_exists($relModelStatic, 'getListData')) {
$relPk = key($relation->link);
$relName = $this->generator->getModelNameAttribute($relation->modelClass);
return <<<EOS
[
'attribute' => '{$attribute}',
......@@ -73,10 +72,10 @@ class EditableProvider extends \schmunk42\giiant\base\Provider {
]
EOS;
}elseif ($relation && !$relation->multiple) {
} elseif ($relation && !$relation->multiple) {
$relPk = key($relation->link);
$relName = $this->generator->getModelNameAttribute($relation->modelClass);
return <<<EOS
[
'attribute' => '{$attribute}',
......@@ -161,7 +160,8 @@ EOS;
*
* @return mixed|string
*/
public function relationGridEditable($name, $relation, $showAllRecords = false) {
public function relationGridEditable($name, $relation, $showAllRecords = false)
{
$model = new $relation->modelClass();
// column counter
......@@ -203,7 +203,7 @@ EOS;
}
$reflection = new \ReflectionClass($relation->modelClass);
$controller = $this->generator->pathPrefix . Inflector::camel2id($reflection->getShortName(), '-', true);
$controller = $this->generator->pathPrefix.Inflector::camel2id($reflection->getShortName(), '-', true);
// $actionColumn = <<<EOS
//[
// 'class' => '{$this->generator->actionButtonClass}',
......@@ -221,7 +221,7 @@ EOS;
// 'controller' => '$controller'
//]
//EOS;
//
// // add action column
// $columns .= $actionColumn.",\n";
// prepare grid column formatters
......@@ -252,11 +252,11 @@ EOS;
continue;
}
/**
/*
* search opts... method
*/
$optsFunc = 'opts' . str_replace('_', '', $attribute);
$optsCamelFunc = 'opts' . str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute))));
$optsFunc = 'opts'.str_replace('_', '', $attribute);
$optsCamelFunc = 'opts'.str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute))));
$useOptsFunc = false;
if (method_exists($model::className(), $optsFunc)) {
......@@ -265,15 +265,14 @@ EOS;
$useOptsFunc = $optsCamelFunc;
}
$tableColumn = $this->generator->getColumnByAttribute($attribute, $model);
$inputType = $this->getInputType($tableColumn);
$relRelation = $this->generator->getRelationByColumn($model->ClassName(), $tableColumn);
if($relRelation){
$relModelStatic = $relRelation->modelClass . 'Static';
if ($relRelation) {
$relModelStatic = $relRelation->modelClass.'Static';
}
if($tableColumn->type == 'date'){
if ($tableColumn->type == 'date') {
$hasDate = true;
$code = "
[
......@@ -301,8 +300,8 @@ EOS;
]
],
]";
}elseif ($relRelation && !$relRelation->multiple && method_exists($relModelStatic, 'getListData')) {
]";
} elseif ($relRelation && !$relRelation->multiple && method_exists($relModelStatic, 'getListData')) {
$hasParameterForValue = false;
$r = new \ReflectionMethod($relModelStatic, 'getListData');
$params = $r->getParameters();
......@@ -345,7 +344,6 @@ EOS;
]";
}
} elseif ($relRelation && !$relRelation->multiple) {
$relPk = key($relRelation->link);
$relName = $this->generator->getModelNameAttribute($relRelation->modelClass);
......@@ -391,15 +389,15 @@ EOS;
'{$controller}/editable-column-update'
]
],
'inputType' => " . $inputType . "
'inputType' => ".$inputType.'
]
]";
]';
}
//$code = $this->generator->columnFormat($attr, $model);
if ($code == false) {
continue;
}
$columns .= $code . ",\n";
$columns .= $code.",\n";
++$counter;
}
......@@ -412,7 +410,7 @@ EOS;
function(\$action, \$model, \$key, \$index) {
\$params = is_array(\$key) ? \$key : ['id' => (string) \$key];
\$params[0] = '{$controller}/' . \$action;
\$params['{$model->formName()}'] = ['" . key($relation->link) . "' => \$model->primaryKey()[0]];
\$params['{$model->formName()}'] = ['".key($relation->link)."' => \$model->primaryKey()[0]];
return Url::toRoute(\$params);
},
]
......@@ -424,7 +422,7 @@ EOS;
$firstPageLabel = $this->generator->generateString('First');
$lastPageLabel = $this->generator->generateString('Last');
$code = '';
if($hasDate){
if ($hasDate) {
$code .= <<<EOS
\$formatter = new IntlDateFormatter(\Yii::\$app->language,IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
\$datePattern = \$formatter->getPattern();
......@@ -454,8 +452,8 @@ EOS;
return $code;
}
public function getInputType($column) {
public function getInputType($column)
{
switch ($column->type) {
case 'double':
case 'integer':
......@@ -476,10 +474,9 @@ EOS;
}
if (!isset($inputType)) {
return false;
throw new \Exception('No Defined column type: ' . $column->type);
throw new \Exception('No Defined column type: '.$column->type);
}
return $inputType;
}
}
......@@ -7,32 +7,35 @@ namespace schmunk42\giiant\generators\extension;
use Yii;
use yii\gii\CodeFile;
class Generator extends \yii\gii\generators\extension\Generator {
class Generator extends \yii\gii\generators\extension\Generator
{
/**
* @var string the message category used by `Yii::t()` when `$enableI18N` is `true`.
* Defaults to `app`.
* Defaults to `app`
*/
public $messageCategory = 'app';
/**
* @inheritdoc
* {@inheritdoc}
*/
public function getName() {
public function getName()
{
return 'Giiant Extension';
}
public function rules() {
public function rules()
{
return array_merge(
parent::rules(), [
[['messageCategory'], 'required'],
[['enableI18N'], 'boolean'],
[['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
[['messageCategory'], 'validateMessageCategory', 'skipOnEmpty' => false],
]
);
}
public function attributeLabels() {
public function attributeLabels()
{
return array_merge(
parent::attributeLabels(), [
'messageCategory' => 'Message Category',
......@@ -40,7 +43,8 @@ class Generator extends \yii\gii\generators\extension\Generator {
);
}
public function hints() {
public function hints()
{
return array_merge(
parent::hints(), [
'messageCategory' => 'This is the category used by <code>Yii::t()</code> in case you enable I18N.',
......@@ -49,32 +53,32 @@ class Generator extends \yii\gii\generators\extension\Generator {
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function stickyAttributes()
{
return ['vendorName', 'outputPath', 'authorName', 'authorEmail', 'enableI18N'];
}
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function generate() {
public function generate()
{
$files = parent::generate();
$modulePath = $this->getOutputPath();
$packagePath = $modulePath . '/' . $this->packageName;
if($this->enableI18N){
$packagePath = $modulePath.'/'.$this->packageName;
if ($this->enableI18N) {
$files[] = new CodeFile(
$modulePath . '/' . $this->packageName . '/messages_config.php', $this->render("messages_config.php", ['packagePath' => $packagePath])
$modulePath.'/'.$this->packageName.'/messages_config.php', $this->render('messages_config.php', ['packagePath' => $packagePath])
);
}
$files[] = new CodeFile(
$modulePath . '/' . $this->packageName . '/Bootstrap.php', $this->render("Bootstrap.php")
$modulePath.'/'.$this->packageName.'/Bootstrap.php', $this->render('Bootstrap.php')
);
return $files;
}
}
......@@ -6,7 +6,7 @@
?>
<div class="alert alert-info">
Please read the
<?= \yii\helpers\Html::a('Extension Guidelines', 'http://www.yiiframework.com/doc-2.0/guide-structure-extensions.html', ['target'=>'new']) ?>
<?= \yii\helpers\Html::a('Extension Guidelines', 'http://www.yiiframework.com/doc-2.0/guide-structure-extensions.html', ['target' => 'new']) ?>
before creating an extension.
</div>
<div class="module-form">
......@@ -16,13 +16,13 @@
echo $form->field($generator, 'namespace');
echo $form->field($generator, 'type')->dropDownList($generator->optsType());
echo $form->field($generator, 'keywords');
echo $form->field($generator, 'license')->dropDownList($generator->optsLicense(), ['prompt'=>'Choose...']);
echo $form->field($generator, 'license')->dropDownList($generator->optsLicense(), ['prompt' => 'Choose...']);
echo $form->field($generator, 'title');
echo $form->field($generator, 'description');
echo $form->field($generator, 'authorName');
echo $form->field($generator, 'authorEmail');
echo $form->field($generator, 'enableI18N')->checkbox();
echo $form->field($generator, 'messageCategory');
echo $form->field($generator, 'messageCategory');
echo $form->field($generator, 'outputPath');
?>
</div>
<?php
/**
* @link http://www.phundament.com
*
* @copyright Copyright (c) 2014 herzog kommunikation GmbH
* @license http://www.phundament.com/license/
*/
namespace schmunk42\giiant\generators\model;
use Yii;
......@@ -17,6 +17,7 @@ use schmunk42\giiant\helpers\SaveForm;
* This generator will generate one or multiple ActiveRecord classes for the specified database table.
*
* @author Tobias Munk <schmunk@usrbin.de>
*
* @since 0.0.1
*/
class Generator extends \yii\gii\generators\model\Generator
......@@ -31,7 +32,6 @@ class Generator extends \yii\gii\generators\model\Generator
*/
public $baseTraits = null;
/**
* @var null string for the table prefix, which is ignored in generated class name
*/
......@@ -41,32 +41,32 @@ class Generator extends \yii\gii\generators\model\Generator
* @var bool whether or not to use BlameableBehavior
*/
public $useBlameableBehavior = true;
/**
* @var string the name of the column where the user who created the entry is stored
*/
public $createdByColumn = 'created_by';
/**
* @var string the name of the column where the user who updated the entry is stored
*/
public $updatedByColumn = 'updated_by';
/**
* @var bool whether or not to use TimestampBehavior
*/
public $useTimestampBehavior = true;
/**
* @var string the name of the column where the user who updated the entry is stored
*/
public $createdAtColumn = 'created_at';
/**
* @var string the name of the column where the user who updated the entry is stored
*/
public $updatedAtColumn = 'updated_at';
/**
* @var bool whether or not to use 2amigos/yii2-translateable-behavior
*/
......@@ -74,14 +74,14 @@ class Generator extends \yii\gii\generators\model\Generator
/**
* @var string the name of the table containing the translations. {{table}} will be replaced with the value in
* "Table Name" field.
* "Table Name" field
*/
public $languageTableName = "{{table}}_lang";
public $languageTableName = '{{table}}_lang';
/**
* @var string the column name where the language code is stored.
* @var string the column name where the language code is stored
*/
public $languageCodeColumn = "language";
public $languageCodeColumn = 'language';
/**
* @var string suffix to append to the base model, setting "Base" will result in a model named "PostBase"
......@@ -97,12 +97,12 @@ class Generator extends \yii\gii\generators\model\Generator
public $removeDuplicateRelations = false;
/**
* @var bool This indicates whether the generator should generate attribute hints by using the comments of the corresponding DB columns.
* @var bool This indicates whether the generator should generate attribute hints by using the comments of the corresponding DB columns
*/
public $generateHintsFromComments = true;
/**
* @var string form field for selecting and loading saved gii forms
* @var string form field for selecting and loading saved gii forms
*/
public $savedForm;
......@@ -111,7 +111,7 @@ class Generator extends \yii\gii\generators\model\Generator
protected $classNames2;
/**
* @inheritdoc
* {@inheritdoc}
*/
public function getName()
{
......@@ -119,7 +119,7 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function getDescription()
{
......@@ -127,7 +127,7 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function rules()
{
......@@ -135,21 +135,22 @@ class Generator extends \yii\gii\generators\model\Generator
parent::rules(),
[
[[
'generateModelClass',
'generateModelClass',
'useTranslatableBehavior',
'generateHintsFromComments',
'useBlameableBehavior',
'useBlameableBehavior',
'useTimestampBehavior',
'singularEntities'
'singularEntities',
], 'boolean'],
[['languageTableName', 'languageCodeColumn','createdByColumn', 'updatedByColumn', 'createdAtColumn', 'updatedAtColumn','savedForm'], 'string'],
[['languageTableName', 'languageCodeColumn', 'createdByColumn', 'updatedByColumn', 'createdAtColumn', 'updatedAtColumn', 'savedForm'], 'string'],
[['tablePrefix'], 'safe'],
]
);
}
/**
* all form fields for saving in saved forms
* all form fields for saving in saved forms.
*
* @return array
*/
public function formAttributes()
......@@ -162,10 +163,10 @@ class Generator extends \yii\gii\generators\model\Generator
'baseClass',
'db',
'generateRelations',
#'generateRelationsFromCurrentSchema',
//'generateRelationsFromCurrentSchema',
'generateLabelsFromComments',
'generateHintsFromComments',
'generateModelClass',
'generateModelClass',
'generateQuery',
'queryNs',
'queryClass',
......@@ -174,7 +175,7 @@ class Generator extends \yii\gii\generators\model\Generator
'singularEntities',
'messageCategory',
'useTranslatableBehavior',
'languageTableName',
'languageTableName',
'languageCodeColumn',
'useBlameableBehavior',
'createdByColumn',
......@@ -183,24 +184,24 @@ class Generator extends \yii\gii\generators\model\Generator
'createdAtColumn',
'updatedAtColumn',
];
}
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function attributeLabels()
{
return array_merge(
parent::attributeLabels(),
[
'generateModelClass' => 'Generate Model Class',
'generateHintsFromComments' => 'Generate Hints from DB Comments',
'generateModelClass' => 'Generate Model Class',
'generateHintsFromComments' => 'Generate Hints from DB Comments',
]
);
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function hints()
{
......@@ -226,7 +227,7 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function requiredTemplates()
{
......@@ -234,7 +235,7 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function generate()
{
......@@ -265,18 +266,18 @@ class Generator extends \yii\gii\generators\model\Generator
if (!empty($translations)) {
$params['translation'] = $translations;
}
$params['blameable'] = $this->generateBlameable($tableSchema);
$params['timestamp'] = $this->generateTimestamp($tableSchema);
$files[] = new CodeFile(
Yii::getAlias(
'@' . str_replace('\\', '/', $this->ns)
) . '/base/' . $className . $this->baseClassSuffix . '.php',
'@'.str_replace('\\', '/', $this->ns)
).'/base/'.$className.$this->baseClassSuffix.'.php',
$this->render('model.php', $params)
);
$modelClassFile = Yii::getAlias('@' . str_replace('\\', '/', $this->ns)) . '/' . $className . '.php';
$modelClassFile = Yii::getAlias('@'.str_replace('\\', '/', $this->ns)).'/'.$className.'.php';
if ($this->generateModelClass || !is_file($modelClassFile)) {
$files[] = new CodeFile(
$modelClassFile,
......@@ -286,8 +287,8 @@ class Generator extends \yii\gii\generators\model\Generator
if ($queryClassName) {
$queryClassFile = Yii::getAlias(
'@' . str_replace('\\', '/', $this->queryNs)
) . '/' . $queryClassName . '.php';
'@'.str_replace('\\', '/', $this->queryNs)
).'/'.$queryClassName.'.php';
if ($this->generateModelClass || !is_file($queryClassFile)) {
$params = [
'className' => $queryClassName,
......@@ -299,20 +300,20 @@ class Generator extends \yii\gii\generators\model\Generator
);
}
}
/**
/*
* create gii/[name]GiiantModel.json with actual form data
*/
$suffix = str_replace(' ','', $this->getName());
$formDataDir = Yii::getAlias('@' . str_replace('\\', '/', $this->ns));
$formDataFile = StringHelper::dirname($formDataDir)
. '/gii'
. '/' . $tableName .$suffix .'.json' ;
$formData = json_encode(SaveForm::getFormAttributesValues($this,$this->formAttributes()));
$files[] = new CodeFile($formDataFile, $formData);
$suffix = str_replace(' ', '', $this->getName());
$formDataDir = Yii::getAlias('@'.str_replace('\\', '/', $this->ns));
$formDataFile = StringHelper::dirname($formDataDir)
.'/gii'
.'/'.$tableName.$suffix.'.json';
$formData = json_encode(SaveForm::getFormAttributesValues($this, $this->formAttributes()));
$files[] = new CodeFile($formDataFile, $formData);
}
return $files;
}
......@@ -326,14 +327,15 @@ class Generator extends \yii\gii\generators\model\Generator
public function generateClassName($tableName, $useSchemaName = null)
{
#Yii::trace("Generating class name for '{$tableName}'...", __METHOD__);
//Yii::trace("Generating class name for '{$tableName}'...", __METHOD__);
if (isset($this->classNames2[$tableName])) {
#Yii::trace("Using '{$this->classNames2[$tableName]}' for '{$tableName}' from classNames2.", __METHOD__);
//Yii::trace("Using '{$this->classNames2[$tableName]}' for '{$tableName}' from classNames2.", __METHOD__);
return $this->classNames2[$tableName];
}
if (isset($this->tableNameMap[$tableName])) {
Yii::trace("Converted '{$tableName}' from tableNameMap.", __METHOD__);
return $this->classNames2[$tableName] = $this->tableNameMap[$tableName];
}
......@@ -353,7 +355,7 @@ class Generator extends \yii\gii\generators\model\Generator
if (($pos = strrpos($pattern, '.')) !== false) {
$pattern = substr($pattern, $pos + 1);
}
$patterns[] = '/^' . str_replace('*', '(\w+)', $pattern) . '$/';
$patterns[] = '/^'.str_replace('*', '(\w+)', $pattern).'$/';
}
$className = $tableName;
......@@ -371,14 +373,17 @@ class Generator extends \yii\gii\generators\model\Generator
}
Yii::trace("Converted '{$tableName}' to '{$returnName}'.", __METHOD__);
return $this->classNames2[$tableName] = $returnName;
}
/**
* Generates the attribute hints for the specified table.
*
* @param \yii\db\TableSchema $table the table schema
*
* @return array the generated attribute hints (name => hint)
* or an empty array if $this->generateHintsFromComments is false.
* or an empty array if $this->generateHintsFromComments is false
*/
public function generateHints($table)
{
......@@ -396,7 +401,7 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function generateRelationName($relations, $table, $key, $multiple)
{
......@@ -409,8 +414,8 @@ class Generator extends \yii\gii\generators\model\Generator
// inject namespace
$ns = "\\{$this->ns}\\";
foreach ($relations AS $model => $relInfo) {
foreach ($relInfo AS $relName => $relData) {
foreach ($relations as $model => $relInfo) {
foreach ($relInfo as $relName => $relData) {
// removed duplicated relations, eg. klientai, klientai0
if ($this->removeDuplicateRelations && is_numeric(substr($relName, -1))) {
......@@ -431,7 +436,7 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* prepare ENUM field values
* prepare ENUM field values.
*
* @param array $columns
*
......@@ -439,7 +444,6 @@ class Generator extends \yii\gii\generators\model\Generator
*/
public function getEnum($columns)
{
$enum = [];
foreach ($columns as $column) {
if (!$this->isEnum($column)) {
......@@ -447,17 +451,16 @@ class Generator extends \yii\gii\generators\model\Generator
}
$column_camel_name = str_replace(' ', '', ucwords(implode(' ', explode('_', $column->name))));
$enum[$column->name]['func_opts_name'] = 'opts' . $column_camel_name;
$enum[$column->name]['func_get_label_name'] = 'get' . $column_camel_name . 'ValueLabel';
$enum[$column->name]['func_opts_name'] = 'opts'.$column_camel_name;
$enum[$column->name]['func_get_label_name'] = 'get'.$column_camel_name.'ValueLabel';
$enum[$column->name]['values'] = [];
$enum_values = explode(',', substr($column->dbType, 4, strlen($column->dbType) - 1));
foreach ($enum_values as $value) {
$value = trim($value, "()'");
$const_name = strtoupper($column->name . '_' . $value);
$const_name = strtoupper($column->name.'_'.$value);
$const_name = preg_replace('/\s+/', '_', $const_name);
$const_name = str_replace(['-', '_', ' '], '_', $const_name);
$const_name = preg_replace('/[^A-Z0-9_]/', '', $const_name);
......@@ -472,15 +475,14 @@ class Generator extends \yii\gii\generators\model\Generator
'const_name' => $const_name,
'label' => $label,
];
}
}
return $enum;
return $enum;
}
/**
* validate is ENUM
* validate is ENUM.
*
* @param $column table column
*
......@@ -491,7 +493,6 @@ class Generator extends \yii\gii\generators\model\Generator
return substr(strtoupper($column->dbType), 0, 4) == 'ENUM';
}
/**
* Generates validation rules for the specified table and add enum value validation.
*
......@@ -520,30 +521,31 @@ class Generator extends \yii\gii\generators\model\Generator
foreach ($enum as $field_name => $field_details) {
$ea = array();
foreach ($field_details['values'] as $field_enum_values) {
$ea[] = 'self::' . $field_enum_values['const_name'];
$ea[] = 'self::'.$field_enum_values['const_name'];
}
$rules[] = "['" . $field_name . "', 'in', 'range' => [\n " . implode(
$rules[] = "['".$field_name."', 'in', 'range' => [\n ".implode(
",\n ",
$ea
) . ",\n ]\n ]";
).",\n ]\n ]";
}
// inject namespace for targetClass
$parentRules = parent::generateRules($table);
$ns = "\\{$this->ns}\\";
$match = "'targetClass' => ";
$replace = $match . $ns;
foreach ($parentRules AS $k => $parentRule) {
$replace = $match.$ns;
foreach ($parentRules as $k => $parentRule) {
$parentRules[$k] = str_replace($match, $replace, $parentRule);
}
}
$rules = array_merge($parentRules, $rules);
$table->columns = array_merge($table->columns, $columns);
return $rules;
}
/**
* @return \yii\db\Connection the DB connection from the DI container or as application component specified by [[db]].
* @return \yii\db\Connection the DB connection from the DI container or as application component specified by [[db]]
*/
protected function getDbConnection()
{
......@@ -567,7 +569,7 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function getTableNames()
{
......@@ -575,13 +577,13 @@ class Generator extends \yii\gii\generators\model\Generator
}
/**
* @param $relations all database's relations.
* @param $relations all database's relations
*
* @return array associative array containing the extracted relations and the modified translations.
* @return array associative array containing the extracted relations and the modified translations
*/
protected function extractTranslations($tableName, $relations)
{
$langTableName = str_replace("{{table}}", $tableName, $this->languageTableName);
$langTableName = str_replace('{{table}}', $tableName, $this->languageTableName);
if ($this->useTranslatableBehavior and isset($relations[$langTableName], $relations[$tableName])) {
$db = $this->getDbConnection();
......@@ -599,7 +601,6 @@ class Generator extends \yii\gii\generators\model\Generator
$langClassName = $this->generateClassName($langTableName);
foreach ($relations[$tableName] as $relationName => $relation) {
list($code, $referencedClassName) = $relation;
if ($referencedClassName === $langClassName) {
......@@ -618,30 +619,29 @@ class Generator extends \yii\gii\generators\model\Generator
}
unset($relations[$tableName][$relationName]);
return [
'relations' => $relations,
'translations' => [
'fields' => $fields,
'code' => $code,
'language_table' => $langTableName,
'language_table_pk' => $langTableSchema->primaryKey
]
'language_table_pk' => $langTableSchema->primaryKey,
],
];
}
}
}
return [
'relations' => $relations,
'translations' => []
'translations' => [],
];
}
/**
* @param \yii\db\TableSchema $table the table schema
*
*
* @return string[]
*/
protected function generateBlameable($table)
......@@ -652,15 +652,16 @@ class Generator extends \yii\gii\generators\model\Generator
if ($this->useBlameableBehavior && ($createdBy || $updatedBy)) {
return [
'createdByAttribute' => $createdBy,
'updatedByAttribute' => $updatedBy,
'updatedByAttribute' => $updatedBy,
];
}
return [];
}
/**
* @param \yii\db\TableSchema $table the table schema
*
*
* @return string[]
*/
protected function generateTimestamp($table)
......@@ -674,6 +675,7 @@ class Generator extends \yii\gii\generators\model\Generator
'updatedAtAttribute' => $updatedAt,
];
}
return [];
}
}
......@@ -7,7 +7,7 @@ use schmunk42\giiant\helpers\SaveForm;
/* @var $form yii\widgets\ActiveForm */
/* @var $generator yii\gii\generators\form\Generator */
/**
/*
* JS for listbox "Saved Form"
* on chenging listbox, form fill with selected saved forma data
* currently work with input text, input checkbox and select form fields
......@@ -18,8 +18,6 @@ echo $form->field($generator, 'savedForm')->dropDownList(
SaveForm::getSavedFormsListbox($generator->getName()), ['onchange' => 'fillForm(this.value)']
);
echo $form->field($generator, 'tableName');
echo $form->field($generator, 'tablePrefix');
echo $form->field($generator, 'modelClass');
......@@ -31,7 +29,7 @@ echo $form->field($generator, 'generateRelations')->dropDownList([
Generator::RELATIONS_ALL => Yii::t('yii', 'All relations'),
Generator::RELATIONS_ALL_INVERSE => Yii::t('yii', 'All relations with inverse'),
]);
#echo $form->field($generator, 'generateRelationsFromCurrentSchema')->checkbox();
//echo $form->field($generator, 'generateRelationsFromCurrentSchema')->checkbox();
echo $form->field($generator, 'generateLabelsFromComments')->checkbox();
echo $form->field($generator, 'generateHintsFromComments')->checkbox();
echo $form->field($generator, 'generateModelClass')->checkbox();
......
<?php
namespace schmunk42\giiant\generators\module;
use yii\gii\CodeFile;
......@@ -6,15 +7,16 @@ use yii\helpers\StringHelper;
/**
* @link http://www.diemeisterei.de/
*
* @copyright Copyright (c) 2015 diemeisterei GmbH, Stuttgart
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
* file that was distributed with this source code
*/
class Generator extends \yii\gii\generators\module\Generator
{
/**
* @inheritdoc
* {@inheritdoc}
*/
public function getName()
{
......@@ -22,46 +24,45 @@ class Generator extends \yii\gii\generators\module\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function requiredTemplates()
{
return ['module.php', 'controller.php', 'view.php'];
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function generate()
{
$files = [];
$modulePath = $this->getModulePath();
$files[] = new CodeFile(
$modulePath . '/' . StringHelper::basename($this->moduleClass) . '.php',
$this->render("module.php")
$modulePath.'/'.StringHelper::basename($this->moduleClass).'.php',
$this->render('module.php')
);
$files[] = new CodeFile(
$modulePath . '/controllers/DefaultController.php',
$this->render("controller.php")
$modulePath.'/controllers/DefaultController.php',
$this->render('controller.php')
);
$files[] = new CodeFile(
$modulePath . '/views/default/index.php',
$this->render("view.php")
$modulePath.'/views/default/index.php',
$this->render('view.php')
);
$files[] = new CodeFile(
$modulePath . '/traits/ActiveRecordDbConnectionTrait.php',
$this->render("db-connection-trait.php")
$modulePath.'/traits/ActiveRecordDbConnectionTrait.php',
$this->render('db-connection-trait.php')
);
return $files;
}
/**
* @return string the controller namespace of the module.
* @return string the controller namespace of the module
*/
public function getTraitsNamespace()
{
return substr($this->moduleClass, 0, strrpos($this->moduleClass, '\\')) . '\traits';
return substr($this->moduleClass, 0, strrpos($this->moduleClass, '\\')).'\traits';
}
}
\ No newline at end of file
}
......@@ -3,7 +3,7 @@
/* @var $generator yii\gii\generators\module\Generator */
?>
<?= "<?php" ?>
<?= '<?php' ?>
use rmrevin\yii\fontawesome\FA;
use yii\helpers\Inflector;
......
<?php
namespace schmunk42\giiant\generators\test;
use Yii;
......@@ -6,7 +7,7 @@ use yii\gii\CodeFile;
use yii\db\Schema;
/**
* This generator generates unit tests for crud operations
* This generator generates unit tests for crud operations.
*
* @author Github: gradosevic
*/
......@@ -19,29 +20,28 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
/**
* @var string Codeception's root path
*
*/
public $codeceptionPath = '/tests/codeception/';
/**
* @var string Controller's class name
*/
public $controllerClass = "";
public $controllerClass = '';
/**
* @var string Model's class name
*/
public $modelClass = "";
public $modelClass = '';
public $modelNs = "";
public $modelNs = '';
/**
* @var string Search model's class name
*/
public $searchModelClass = "";
public $searchModelClass = '';
/**
* @inheritdoc
* {@inheritdoc}
*/
public function getName()
{
......@@ -49,7 +49,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function getDescription()
{
......@@ -57,7 +57,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function requiredTemplates()
{
......@@ -66,14 +66,16 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
/**
* @param $table Table schema
*
* @return array Attributes containing all required model's information for test generator
*/
public function generateAttributes($table){
public function generateAttributes($table)
{
$labels = $this->generateLabels($table);
$attributes = [];
foreach ($table->columns as $column) {
$label = $column->name;
if(isset($labels[$column->name])){
if (isset($labels[$column->name])) {
$label = $labels[$column->name];
}
$attribute = [];
......@@ -117,20 +119,21 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
}
$attributes[] = $attribute;
}
return $attributes;
}
/**
* @inheritdoc
* {@inheritdoc}
*/
public function generate()
{
$files = [];
$files = [];
// $relations = $this->generateRelations();
$db = $this->getDbConnection();
$db = $this->getDbConnection();
$class = $this->modelNs.$this->modelClass;
$classTableNameMethod = "tableName";
$classTableNameMethod = 'tableName';
$this->tableName = $class::$classTableNameMethod();
//TODO: Add unit tests for search model
......@@ -141,24 +144,25 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
foreach ($this->getTableNames() as $tableName) {
$className = $this->generateClassName($tableName);
$tableSchema = $db->getTableSchema($tableName);
$params = [
'tableName' => $tableName,
'className' => $className,
'modelClass' => $this->modelClass,
'controllerClass'=> $this->controllerClass,
'labels' => $this->generateLabels($tableSchema),
'rules' => $this->generateRules($tableSchema),
'attributes' => $this->generateAttributes($tableSchema),
$params = [
'tableName' => $tableName,
'className' => $className,
'modelClass' => $this->modelClass,
'controllerClass' => $this->controllerClass,
'labels' => $this->generateLabels($tableSchema),
'rules' => $this->generateRules($tableSchema),
'attributes' => $this->generateAttributes($tableSchema),
//TODO: Add unit tests for relations
//'relations' => isset($relations[$tableName]) ? $relations[$tableName] : [],
'ns' => $this->ns,
'ns' => $this->ns,
];
$files[] = new CodeFile(
Yii::getAlias('@app/..'. $this->codeceptionPath . str_replace('\\', '/', $this->ns)) . '/' . $className . $this->baseClassSuffix . 'UnitTest.php',
Yii::getAlias('@app/..'.$this->codeceptionPath.str_replace('\\', '/', $this->ns)).'/'.$className.$this->baseClassSuffix.'UnitTest.php',
$this->render('unit.php', $params)
);
}
return $files;
}
}
......@@ -3,17 +3,16 @@
* This is the template for generating the crud operations unit test class of a specified model.
* DO NOT EDIT THIS FILE! It may be regenerated with Gii.
*
* @var yii\web\View $this
* @var yii\web\View
* @var schmunk42\giiant\generators\model\Generator $generator
* @var string $className class name
* @var array $relations list of relations (name => relation declaration)
* @var string[] $labels list of attribute labels (name => label)
* @var string[] $rules list of validation rules
* @var array[] $attributes list of attributes with labels and types
* @var string $modelClass fully qualified model class name
* @var string $controllerClass fully qualified controller class name
* @var string $className class name
* @var array $relations list of relations (name => relation declaration)
* @var string[] $labels list of attribute labels (name => label)
* @var string[] $rules list of validation rules
* @var array[] $attributes list of attributes with labels and types
* @var string $modelClass fully qualified model class name
* @var string $controllerClass fully qualified controller class name
*/
echo "<?php\n";
?>
namespace tests\codeception\backend\unit\models;
......@@ -58,8 +57,10 @@ class <?= $className ?>Test extends DbTestCase
{
$model = $this->newModelInstance();
$this->specify($this->modelName.' model should be created', function () use ($model) {
<?php foreach($attributes as $attr):
if(isPK($attr)){ continue;}?>
<?php foreach ($attributes as $attr):
if (isPK($attr)) {
continue;
}?>
expect('model\'s attribute "<?= $attr['label'] ?>" exists ', isset($model-><?= $attr['name'] ?>))->true();
<?php endforeach; ?>
});
......@@ -79,8 +80,10 @@ class <?= $className ?>Test extends DbTestCase
$reloadedModel = $this->loadModelById($this->modelPK);
$this->specify($this->modelName.' model should be saved', function () use ($reloadedModel, $model) {
<?php foreach($attributes as $attr):
if(isPK($attr)){ continue;}?>
<?php foreach ($attributes as $attr):
if (isPK($attr)) {
continue;
}?>
expect('model\'s attribute "<?= $attr['label'] ?>" saved correctly', $reloadedModel-><?= $attr['name'] ?>)->equals($model-><?= $attr['name'] ?>);
<?php endforeach; ?>
});
......@@ -100,8 +103,10 @@ class <?= $className ?>Test extends DbTestCase
$updatedModel = clone $originalModel;
<?php foreach($attributes as $attr):
if(isPK($attr)){ continue;}?>
<?php foreach ($attributes as $attr):
if (isPK($attr)) {
continue;
}?>
$updatedModel-><?php echo $attr['name'] ?> = $this->updateAttributeValue($originalModel-><?php echo $attr['name'] ?>, '<?php echo $attr['name'] ?>', '<?php echo $attr['type'] ?>');
<?php endforeach; ?>
if(!$updatedModel->save($this->isModelValidationEnabled)){
......@@ -110,7 +115,7 @@ class <?= $className ?>Test extends DbTestCase
$reloadedModel = $this->loadModelById($this->modelPK);
$this->specify($this->modelName.' model should be updated', function () use ($reloadedModel, $updatedModel) {
<?php foreach($attributes as $attr): ?>
<?php foreach ($attributes as $attr): ?>
expect('model\'s attribute "<?= $attr['label'] ?>" was updated ', $reloadedModel-><?= $attr['name'] ?>)->equals($updatedModel-><?= $attr['name'] ?>);
<?php endforeach; ?>
});
......@@ -150,8 +155,10 @@ class <?= $className ?>Test extends DbTestCase
{
$r = new \ReflectionClass($this->class);
$model = $r->newInstance();
<?php foreach($attributes as $attr):
if(isPK($attr)){ continue;}?>
<?php foreach ($attributes as $attr):
if (isPK($attr)) {
continue;
}?>
$model-><?php echo $attr['name'] ?> = GiiantFaker::<?php echo $attr['type'] ?>('<?php echo $attr['name'] ?>');
<?php endforeach; ?>
......@@ -191,21 +198,22 @@ class <?= $className ?>Test extends DbTestCase
}
<?php
#region HELPER FUNCTIONS
//region HELPER FUNCTIONS
function isPK($attribute){
function isPK($attribute)
{
return $attribute['primary'] === true;
}
function PKAttributeName($attributes){
foreach($attributes as $a):
if($a['primary'] === true){
function PKAttributeName($attributes)
{
foreach ($attributes as $a):
if ($a['primary'] === true) {
return $a['name'];
}
endforeach;
return "id";
}
return 'id';
}
#endregions
\ No newline at end of file
#endregions
<?php
namespace schmunk42\giiant\helpers;
use yii\faker;
class GiiantFaker extends \Faker\Factory{
class GiiantFaker extends \Faker\Factory
{
private static $fakerFactory;
const TYPE_STRING = "string";
const TYPE_INTEGER = "integer";
const TYPE_NUMBER = "number";
const TYPE_BOOLEAN = "boolean";
const TYPE_DATE = "date";
const TYPE_TIME = "time";
const TYPE_DATETIME = "datetime";
const TYPE_TIMESTAMP = "timestamp";
const TYPE_STRING = 'string';
const TYPE_INTEGER = 'integer';
const TYPE_NUMBER = 'number';
const TYPE_BOOLEAN = 'boolean';
const TYPE_DATE = 'date';
const TYPE_TIME = 'time';
const TYPE_DATETIME = 'datetime';
const TYPE_TIMESTAMP = 'timestamp';
const FORMAT_DATE = "Y-m-d";
const FORMAT_TIME = "H:i:s";
const FORMAT_DATETIME = "Y-m-d H:i:s";
const FORMAT_TIMESTAMP = "Y-m-d H:i:s";
const FORMAT_DATE = 'Y-m-d';
const FORMAT_TIME = 'H:i:s';
const FORMAT_DATETIME = 'Y-m-d H:i:s';
const FORMAT_TIMESTAMP = 'Y-m-d H:i:s';
/**
* Returns new instance of Faker generator class
* Returns new instance of Faker generator class.
*
* @return \Faker\Generator
*/
public static function create(){
if(self::$fakerFactory == null){
public static function create()
{
if (self::$fakerFactory == null) {
self::$fakerFactory = parent::create();
}
return self::$fakerFactory;
}
/**
* Returns Faker value
* Returns Faker value.
*
* @param string $type model's attribute type
* @param string $type model's attribute type
* @param string $methodName model's attribute type trying to match Faker's method name
* @param null $format custom data format used in Faker
* @param null $format custom data format used in Faker
*
* @return mixed
*/
public static function value($type = self::TYPE_STRING, $methodName = "", $format=null){
public static function value($type = self::TYPE_STRING, $methodName = '', $format = null)
{
self::create();
$preferredValue = self::provider($type, $methodName);
if($preferredValue !== null){
if ($preferredValue !== null) {
return $preferredValue;
}
switch($type):
switch ($type):
case self::TYPE_INTEGER:
return self::$fakerFactory->randomNumber;
case self::TYPE_NUMBER:
case self::TYPE_NUMBER:
return self::$fakerFactory->randomFloat;
case self::TYPE_BOOLEAN:
case self::TYPE_BOOLEAN:
return self::$fakerFactory->boolean;
case self::TYPE_DATE:
$format = ($format === NULL)? self::FORMAT_DATE:$format;
return self::$fakerFactory->date($format);
case self::TYPE_TIME:
$format = ($format === NULL)? self::FORMAT_TIME:$format;
return self::$fakerFactory->time($format);
case self::TYPE_DATETIME:
$format = ($format === NULL)? self::FORMAT_DATETIME:$format;
return self::$fakerFactory->dateTime()->format($format);
case self::TYPE_TIMESTAMP:
$format = ($format === NULL)? self::FORMAT_TIMESTAMP:$format;
return self::$fakerFactory->dateTime()->format($format);
default:
case self::TYPE_DATE:
$format = ($format === null) ? self::FORMAT_DATE : $format;
return self::$fakerFactory->date($format);
case self::TYPE_TIME:
$format = ($format === null) ? self::FORMAT_TIME : $format;
return self::$fakerFactory->time($format);
case self::TYPE_DATETIME:
$format = ($format === null) ? self::FORMAT_DATETIME : $format;
return self::$fakerFactory->dateTime()->format($format);
case self::TYPE_TIMESTAMP:
$format = ($format === null) ? self::FORMAT_TIMESTAMP : $format;
return self::$fakerFactory->dateTime()->format($format);
default:
return self::$fakerFactory->word;
endswitch;
}
/**
* Tries to execute Faker's provider methods like email, address, title etc, if method is found
* Tries to execute Faker's provider methods like email, address, title etc, if method is found.
*
* @param string $type model's attribute type
* @param string $type model's attribute type
* @param string $methodName model's attribute type trying to match Faker's method name
* @param null $format custom data format used in Faker
* @return null
* @param null $format custom data format used in Faker
*/
public static function provider($type = self::TYPE_STRING, $methodName = "", $format = null){
public static function provider($type = self::TYPE_STRING, $methodName = '', $format = null)
{
$fakerValue = null;
try{
try {
$fakerValue = self::$fakerFactory->$methodName;
switch($type):
switch ($type):
case self::TYPE_INTEGER:
$fakerValue = (int) $fakerValue;
break;
case self::TYPE_NUMBER:
break;
case self::TYPE_NUMBER:
$fakerValue = (float) $fakerValue;
break;
default:
break;
default:
$fakerValue = (string) $fakerValue;
break;
endswitch;
}catch (\Exception $e){
break;
endswitch;
} catch (\Exception $e) {
$fakerValue = null;
}
return $fakerValue;
}
/**
* @param string $methodName model's attribute type trying to match Faker's method name
*
* @return mixed
*/
public static function string($methodName = ""){
public static function string($methodName = '')
{
$val = self::provider(self::TYPE_STRING, $methodName);
return ($val === null)?self::value(self::TYPE_STRING):$val;
return ($val === null) ? self::value(self::TYPE_STRING) : $val;
}
/**
* @param string $methodName model's attribute type trying to match Faker's method name
*
* @return mixed
*/
public static function integer($methodName = ""){
public static function integer($methodName = '')
{
$val = self::provider(self::TYPE_INTEGER, $methodName);
return ($val === null)?self::value(self::TYPE_INTEGER):$val;
return ($val === null) ? self::value(self::TYPE_INTEGER) : $val;
}
/**
* @param string $methodName model's attribute type trying to match Faker's method name
*
* @return mixed
*/
public static function number($methodName = ""){
public static function number($methodName = '')
{
$val = self::provider(self::TYPE_NUMBER, $methodName);
return ($val === null)?self::value(self::TYPE_NUMBER):$val;
return ($val === null) ? self::value(self::TYPE_NUMBER) : $val;
}
/**
* @return mixed
*/
public static function boolean(){
public static function boolean()
{
return self::value(self::TYPE_BOOLEAN);
}
/**
* @param null $format - Custom format
*
* @return mixed
*/
public static function date($format = null){
public static function date($format = null)
{
return self::value(self::TYPE_DATE, $format);
}
/**
* @param null $format - Custom format
*
* @return mixed
*/
public static function time($format = null){
public static function time($format = null)
{
return self::value(self::TYPE_TIME, $format);
}
/**
* @param null $format - Custom format
*
* @return mixed
*/
public static function datetime($format = null){
public static function datetime($format = null)
{
return self::value(self::TYPE_DATETIME, $format);
}
/**
* @param null $format - Custom format
*
* @return mixed
*/
public static function timestamp($format = null){
public static function timestamp($format = null)
{
return self::value(self::TYPE_TIMESTAMP, $format);
}
}
\ No newline at end of file
}
......@@ -4,18 +4,20 @@ namespace schmunk42\giiant\helpers;
use yii\helpers\StringHelper;
class SaveForm {
class SaveForm
{
public static $savedFormList = false;
public static function hint() {
public static function hint()
{
return ['savedForm' => 'Choose saved form ad load it data to form.'];
}
/**
* get form attributes values.
*/
public static function getFormAttributesValues($generator, $attributes) {
public static function getFormAttributesValues($generator, $attributes)
{
$values = [];
foreach ($attributes as $name) {
$values[strtolower($name)] = [
......@@ -28,28 +30,29 @@ class SaveForm {
}
/**
* walk througt all modules gii directories and collect Giant crud generator saved forms
*
* walk througt all modules gii directories and collect Giant crud generator saved forms.
*
* @return array
*/
public static function loadSavedForms($generatorName) {
public static function loadSavedForms($generatorName)
{
$suffix = str_replace(' ', '', $generatorName);
if (self::$savedFormList) {
return self::$savedFormList;
}
/**
/*
* get all possible gii directories with out validation on existing
*/
$giiDirs = [];
$giiDirs[] = \Yii::getAlias('@app/gii');
if ($commonGiiDir = \Yii::getAlias('@common/gii', false))
if ($commonGiiDir = \Yii::getAlias('@common/gii', false)) {
$giiDirs[] = $commonGiiDir;
}
foreach (\Yii::$app->modules as $moduleId => $module) {
/**
/*
* get module base path
*/
if (method_exists($module, 'getBasePath')) {
......@@ -59,33 +62,32 @@ class SaveForm {
$basePath = StringHelper::dirname($reflector->getFileName());
}
$basePath .= '/gii';
$giiDirs[] = $basePath;
}
/**
}
/*
* from all gii directories collec forms
*/
$forms = [];
foreach($giiDirs as $basePath){
/**
* search in module gii directory all forms json files
foreach ($giiDirs as $basePath) {
/*
* search in module gii directory all forms json files
* with required suffix
*/
if (!file_exists($basePath)) {
continue;
}
$files = scandir($basePath);
foreach ($files as $file) {
if (!preg_match('#' . $suffix . '\.json$#', $file)) {
if (!preg_match('#'.$suffix.'\.json$#', $file)) {
continue;
}
$name = preg_replace('#' . $suffix . '\.json$#', '', $file);
$forms[$moduleId . $name] = [
'jsonData' => file_get_contents($basePath . '/' . $file),
'label' => $moduleId . ' - ' . $name,
$name = preg_replace('#'.$suffix.'\.json$#', '', $file);
$forms[$moduleId.$name] = [
'jsonData' => file_get_contents($basePath.'/'.$file),
'label' => $moduleId.' - '.$name,
];
}
}
......@@ -94,32 +96,38 @@ class SaveForm {
}
/**
* get array for form field "Saved form" data
* get array for form field "Saved form" data.
*
* @return array
*/
public static function getSavedFormsListbox($generatorName) {
public static function getSavedFormsListbox($generatorName)
{
$r = ['0' => ' - '];
foreach (SaveForm::loadSavedForms($generatorName) as $k => $row) {
foreach (self::loadSavedForms($generatorName) as $k => $row) {
$r[$k] = $row['label'];
}
return $r;
}
/**
* creata js statement for seting to variable savedFormas array with all forms and it data in json format
* creata js statement for seting to variable savedFormas array with all forms and it data in json format.
*
* @return string
*/
public static function getSavedFormsJs($generatorName) {
public static function getSavedFormsJs($generatorName)
{
$js = [];
foreach (SaveForm::loadSavedForms($generatorName) as $k => $row) {
$js[] = $k . ":'" . $row['jsonData'] . "'";
foreach (self::loadSavedForms($generatorName) as $k => $row) {
$js[] = $k.":'".$row['jsonData']."'";
}
return "var savedForms = {" . str_replace('\\', '\\\\', implode(',', $js)) . "};";
return 'var savedForms = {'.str_replace('\\', '\\\\', implode(',', $js)).'};';
}
public static function jsFillForm() {
public static function jsFillForm()
{
return '
function fillForm(id){
if (id=="0") return;
......@@ -169,5 +177,4 @@ class SaveForm {
}
';
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment