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

php-cs-fixer

parent 5b11e7df
<?php <?php
/** /**
* @link http://www.diemeisterei.de/ * @link http://www.diemeisterei.de/
*
* @copyright Copyright (c) 2014 diemeisterei GmbH, Stuttgart * @copyright Copyright (c) 2014 diemeisterei GmbH, Stuttgart
* *
* For the full copyright and license information, please view the LICENSE * 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; namespace schmunk42\giiant;
use yii\base\Application; use yii\base\Application;
use yii\base\BootstrapInterface; use yii\base\BootstrapInterface;
/** /**
* Class Bootstrap * Class Bootstrap.
* @package schmunk42\giiant *
* @author Tobias Munk <tobias@diemeisterei.de> * @author Tobias Munk <tobias@diemeisterei.de>
*/ */
class Bootstrap implements BootstrapInterface class Bootstrap implements BootstrapInterface
{ {
/** /**
* Bootstrap method to be called during application bootstrap stage. * Bootstrap method to be called during application bootstrap stage.
* *
...@@ -29,7 +27,6 @@ class Bootstrap implements BootstrapInterface ...@@ -29,7 +27,6 @@ class Bootstrap implements BootstrapInterface
public function bootstrap($app) public function bootstrap($app)
{ {
if ($app->hasModule('gii')) { if ($app->hasModule('gii')) {
if (!isset($app->getModule('gii')->generators['giiant-model'])) { if (!isset($app->getModule('gii')->generators['giiant-model'])) {
$app->getModule('gii')->generators['giiant-model'] = 'schmunk42\giiant\generators\model\Generator'; $app->getModule('gii')->generators['giiant-model'] = 'schmunk42\giiant\generators\model\Generator';
} }
...@@ -43,9 +40,8 @@ class Bootstrap implements BootstrapInterface ...@@ -43,9 +40,8 @@ class Bootstrap implements BootstrapInterface
'class' => 'schmunk42\giiant\generators\crud\Generator', 'class' => 'schmunk42\giiant\generators\crud\Generator',
'templates' => [ 'templates' => [
'editable' => __DIR__.'/generators/crud/editable', 'editable' => __DIR__.'/generators/crud/editable',
] ],
]; ];
} }
if (!isset($app->getModule('gii')->generators['giiant-module'])) { if (!isset($app->getModule('gii')->generators['giiant-module'])) {
......
...@@ -3,12 +3,10 @@ ...@@ -3,12 +3,10 @@
* Created by PhpStorm. * Created by PhpStorm.
* User: tobias * User: tobias
* Date: 19.03.14 * Date: 19.03.14
* Time: 01:02 * Time: 01:02.
*/ */
namespace schmunk42\giiant\base; namespace schmunk42\giiant\base;
use yii\base\Object; use yii\base\Object;
class Provider extends Object class Provider extends Object
......
...@@ -35,14 +35,14 @@ class BatchController extends Controller ...@@ -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 * @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) * @var bool whether to overwrite extended models (from ModelBase)
...@@ -95,24 +95,24 @@ class BatchController extends Controller ...@@ -95,24 +95,24 @@ class BatchController extends Controller
public $modelRemoveDuplicateRelations = false; 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; 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; public $singularEntities = true;
/** /**
* @var string the message category for models used by `Yii::t()` when `$enableI18N` is `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'; public $modelMessageCategory = 'models';
/** /**
* @var string the message category for CRUDs used by `Yii::t()` when `$enableI18N` is `true`. * @var string the message category for CRUDs used by `Yii::t()` when `$enableI18N` is `true`.
* Defaults to `app`. * Defaults to `app`
*/ */
public $crudMessageCategory = 'cruds'; public $crudMessageCategory = 'cruds';
...@@ -157,7 +157,7 @@ class BatchController extends Controller ...@@ -157,7 +157,7 @@ class BatchController extends Controller
public $crudSkipRelations = []; public $crudSkipRelations = [];
/** /**
* @var boolean whether to add accessFilter in behavior * @var bool whether to add accessFilter in behavior
*/ */
public $crudAccessFilter; public $crudAccessFilter;
...@@ -186,12 +186,12 @@ class BatchController extends Controller ...@@ -186,12 +186,12 @@ class BatchController extends Controller
public $modelQueryBaseClass = 'yii\db\ActiveQuery'; 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; 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; public $modelGenerateHintsFromComments = true;
/** /**
...@@ -205,7 +205,7 @@ class BatchController extends Controller ...@@ -205,7 +205,7 @@ class BatchController extends Controller
protected $modelGenerator; protected $modelGenerator;
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function options($id) public function options($id)
{ {
...@@ -251,7 +251,7 @@ class BatchController extends Controller ...@@ -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 * @param \yii\base\Action $action
* *
...@@ -277,9 +277,9 @@ class BatchController extends Controller ...@@ -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() public function actionIndex()
{ {
...@@ -289,14 +289,15 @@ class BatchController extends Controller ...@@ -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 * @throws \yii\console\Exception
*/ */
public function actionModels() public function actionModels()
{ {
// create models // create models
foreach ($this->tables AS $table) { foreach ($this->tables as $table) {
#var_dump($this->tableNameMap, $table);exit; //var_dump($this->tableNameMap, $table);exit;
$params = [ $params = [
'interactive' => $this->interactive, 'interactive' => $this->interactive,
'overwrite' => $this->overwrite, 'overwrite' => $this->overwrite,
...@@ -336,11 +337,11 @@ class BatchController extends Controller ...@@ -336,11 +337,11 @@ class BatchController extends Controller
\Yii::$app = $app; \Yii::$app = $app;
\Yii::$app->log->logger->flush(true); \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 * @throws \yii\console\Exception
*/ */
public function actionCruds() public function actionCruds()
...@@ -352,7 +353,7 @@ class BatchController extends Controller ...@@ -352,7 +353,7 @@ class BatchController extends Controller
$this->createDirectoryFromNamespace($this->crudControllerNamespace); $this->createDirectoryFromNamespace($this->crudControllerNamespace);
$this->createDirectoryFromNamespace($this->crudSearchModelNamespace); $this->createDirectoryFromNamespace($this->crudSearchModelNamespace);
foreach ($this->tables AS $table) { foreach ($this->tables as $table) {
$table = str_replace($this->tablePrefix, '', $table); $table = str_replace($this->tablePrefix, '', $table);
$name = isset($this->tableNameMap[$table]) ? $this->tableNameMap[$table] : $name = isset($this->tableNameMap[$table]) ? $this->tableNameMap[$table] :
$this->modelGenerator->generateClassName($table); $this->modelGenerator->generateClassName($table);
...@@ -360,10 +361,10 @@ class BatchController extends Controller ...@@ -360,10 +361,10 @@ class BatchController extends Controller
'interactive' => $this->interactive, 'interactive' => $this->interactive,
'overwrite' => $this->overwrite, 'overwrite' => $this->overwrite,
'template' => $this->template, 'template' => $this->template,
'modelClass' => $this->modelNamespace . '\\' . $name, 'modelClass' => $this->modelNamespace.'\\'.$name,
'searchModelClass' => $this->crudSearchModelNamespace . '\\' . $name . $this->crudSearchModelSuffix, 'searchModelClass' => $this->crudSearchModelNamespace.'\\'.$name.$this->crudSearchModelSuffix,
'controllerNs' => $this->crudControllerNamespace, 'controllerNs' => $this->crudControllerNamespace,
'controllerClass' => $this->crudControllerNamespace . '\\' . $name . 'Controller', 'controllerClass' => $this->crudControllerNamespace.'\\'.$name.'Controller',
'viewPath' => $this->crudViewPath, 'viewPath' => $this->crudViewPath,
'pathPrefix' => $this->crudPathPrefix, 'pathPrefix' => $this->crudPathPrefix,
'tablePrefix' => $this->tablePrefix, 'tablePrefix' => $this->tablePrefix,
...@@ -391,9 +392,10 @@ class BatchController extends Controller ...@@ -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 * @todo should be removed, if this issue is closed -> https://github.com/yiisoft/yii2/pull/5687
*
* @return array * @return array
*/ */
protected function getYiiConfiguration() protected function getYiiConfiguration()
...@@ -402,30 +404,29 @@ class BatchController extends Controller ...@@ -402,30 +404,29 @@ class BatchController extends Controller
$config = $GLOBALS['config']; $config = $GLOBALS['config'];
} else { } else {
$config = \yii\helpers\ArrayHelper::merge( $config = \yii\helpers\ArrayHelper::merge(
require(\Yii::getAlias('@app') . '/../common/config/main.php'), require(\Yii::getAlias('@app').'/../common/config/main.php'),
(is_file(\Yii::getAlias('@app') . '/../common/config/main-local.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-local.php')
: [], : [],
require(\Yii::getAlias('@app') . '/../console/config/main.php'), require(\Yii::getAlias('@app').'/../console/config/main.php'),
(is_file(\Yii::getAlias('@app') . '/../console/config/main-local.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-local.php')
: [] : []
); );
} }
return $config; return $config;
} }
/** /**
* Helper function to create * Helper function to create.
* *
* @param $ns Namespace * @param $ns Namespace
*/ */
private function createDirectoryFromNamespace($ns) private function createDirectoryFromNamespace($ns)
{ {
echo \Yii::getRootAlias($ns); echo \Yii::getRootAlias($ns);
$dir = \Yii::getAlias('@' . str_replace('\\', '/', ltrim($ns, '\\'))); $dir = \Yii::getAlias('@'.str_replace('\\', '/', ltrim($ns, '\\')));
@mkdir($dir); @mkdir($dir);
} }
} }
...@@ -57,7 +57,6 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -57,7 +57,6 @@ class Generator extends \yii\gii\generators\crud\Generator
/** /**
* @var string Bootstrap CSS-class for form-layout * @var string Bootstrap CSS-class for form-layout
*/ */
public $formLayout = 'horizontal'; public $formLayout = 'horizontal';
/** /**
...@@ -204,9 +203,9 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -204,9 +203,9 @@ class Generator extends \yii\gii\generators\crud\Generator
'formLayout', 'formLayout',
'accessFilter', 'accessFilter',
'singularEntities', 'singularEntities',
'modelMessageCategory' 'modelMessageCategory',
], ],
'safe' 'safe',
], ],
[['viewPath'], 'required'], [['viewPath'], 'required'],
] ]
...@@ -222,7 +221,8 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -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 * @return array
*/ */
public function formAttributes() public function formAttributes()
...@@ -243,7 +243,7 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -243,7 +243,7 @@ class Generator extends \yii\gii\generators\crud\Generator
'template', 'template',
'accessFilter', 'accessFilter',
'singularEntities', 'singularEntities',
'modelMessageCategory' 'modelMessageCategory',
]; ];
} }
...@@ -278,21 +278,21 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -278,21 +278,21 @@ class Generator extends \yii\gii\generators\crud\Generator
*/ */
public function getModuleId() public function getModuleId()
{ {
if(!$this->moduleNs){ if (!$this->moduleNs) {
$controllerNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerClass, '\\')); $controllerNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerClass, '\\'));
$this->moduleNs = \yii\helpers\StringHelper::dirname(ltrim($controllerNs, '\\')); $this->moduleNs = \yii\helpers\StringHelper::dirname(ltrim($controllerNs, '\\'));
} }
return \yii\helpers\StringHelper::basename($this->moduleNs); return \yii\helpers\StringHelper::basename($this->moduleNs);
} }
public function generate() 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->controllerNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerClass, '\\'));
$this->moduleNs = \yii\helpers\StringHelper::dirname(ltrim($this->controllerNs, '\\')); $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) { if ($this->singularEntities) {
$this->modelClass = Inflector::singularize($this->modelClass); $this->modelClass = Inflector::singularize($this->modelClass);
...@@ -306,19 +306,19 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -306,19 +306,19 @@ class Generator extends \yii\gii\generators\crud\Generator
$baseControllerFile = StringHelper::dirname($controllerFile).'/base/'.StringHelper::basename($controllerFile); $baseControllerFile = StringHelper::dirname($controllerFile).'/base/'.StringHelper::basename($controllerFile);
$restControllerFile = StringHelper::dirname($controllerFile).'/api/'.StringHelper::basename($controllerFile); $restControllerFile = StringHelper::dirname($controllerFile).'/api/'.StringHelper::basename($controllerFile);
/** /*
* search generated migration and overwrite it or create new * search generated migration and overwrite it or create new
*/ */
$migrationDir = StringHelper::dirname(StringHelper::dirname($controllerFile)) $migrationDir = StringHelper::dirname(StringHelper::dirname($controllerFile))
. '/migrations'; .'/migrations';
if(file_exists($migrationDir) && $migrationDirFiles = glob($migrationDir .'/m*_' . $controllerName . '00_access.php')){ if (file_exists($migrationDir) && $migrationDirFiles = glob($migrationDir.'/m*_'.$controllerName.'00_access.php')) {
$this->migrationClass = pathinfo($migrationDirFiles[0], PATHINFO_FILENAME); $this->migrationClass = pathinfo($migrationDirFiles[0], PATHINFO_FILENAME);
}else{ } else {
$this->migrationClass = 'm' . date("ymd_Hi") . '00_' . $controllerName . '_access'; $this->migrationClass = 'm'.date('ymd_Hi').'00_'.$controllerName.'_access';
} }
$files[] = new CodeFile($baseControllerFile, $this->render('controller.php',['accessDefinitions' => $accessDefinitions])); $files[] = new CodeFile($baseControllerFile, $this->render('controller.php', ['accessDefinitions' => $accessDefinitions]));
$params['controllerClassName'] = \yii\helpers\StringHelper::basename($this->controllerClass); $params['controllerClassName'] = \yii\helpers\StringHelper::basename($this->controllerClass);
if ($this->overwriteControllerClass || !is_file($controllerFile)) { if ($this->overwriteControllerClass || !is_file($controllerFile)) {
...@@ -345,39 +345,38 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -345,39 +345,38 @@ class Generator extends \yii\gii\generators\crud\Generator
} }
if (is_file($templatePath.'/'.$file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') { if (is_file($templatePath.'/'.$file) && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
echo $file; 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 * access migration
*/ */
$migrationFile = $migrationDir . '/' . $this->migrationClass . '.php' ; $migrationFile = $migrationDir.'/'.$this->migrationClass.'.php';
//var_dump($migrationFile);exit; //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 * access roles translation
*/ */
$forRoleTranslationFile = StringHelper::dirname(StringHelper::dirname($controllerFile)) $forRoleTranslationFile = StringHelper::dirname(StringHelper::dirname($controllerFile))
. '/messages/for-translation/' .'/messages/for-translation/'
. $controllerName.'.php' ; .$controllerName.'.php';
$files[] = new CodeFile($forRoleTranslationFile, $this->render('roles-translation.php',['accessDefinitions' => $accessDefinitions])); $files[] = new CodeFile($forRoleTranslationFile, $this->render('roles-translation.php', ['accessDefinitions' => $accessDefinitions]));
} }
/** /*
* create gii/[name]GiantCRUD.json with actual form data * create gii/[name]GiantCRUD.json with actual form data
*/ */
$suffix = str_replace(' ','', $this->getName()); $suffix = str_replace(' ', '', $this->getName());
$controllerFileinfo = pathinfo($controllerFile); $controllerFileinfo = pathinfo($controllerFile);
$formDataFile = StringHelper::dirname(StringHelper::dirname($controllerFile)) $formDataFile = StringHelper::dirname(StringHelper::dirname($controllerFile))
. '/gii/' .'/gii/'
. str_replace('Controller',$suffix,$controllerFileinfo['filename']).'.json' ; .str_replace('Controller', $suffix, $controllerFileinfo['filename']).'.json';
//$formData = json_encode($this->getFormAttributesValues()); //$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); $files[] = new CodeFile($formDataFile, $formData);
return $files; return $files;
...@@ -408,23 +407,25 @@ class Generator extends \yii\gii\generators\crud\Generator ...@@ -408,23 +407,25 @@ class Generator extends \yii\gii\generators\crud\Generator
parent::validateClass($attribute, $params); parent::validateClass($attribute, $params);
} }
public function var_export54($var, $indent="") { public function var_export54($var, $indent = '')
{
switch (gettype($var)) { switch (gettype($var)) {
case "string": case 'string':
return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"'; return '"'.addcslashes($var, "\\\$\"\r\n\t\v\f").'"';
case "array": case 'array':
$indexed = array_keys($var) === range(0, count($var) - 1); $indexed = array_keys($var) === range(0, count($var) - 1);
$r = []; $r = [];
foreach ($var as $key => $value) { foreach ($var as $key => $value) {
$r[] = "$indent " $r[] = "$indent "
. ($indexed ? "" : $this->var_export54($key) . " => ") .($indexed ? '' : $this->var_export54($key).' => ')
. $this->var_export54($value, "$indent "); .$this->var_export54($value, "$indent ");
} }
return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
case "boolean": return "[\n".implode(",\n", $r)."\n".$indent.']';
return $var ? "TRUE" : "FALSE"; case 'boolean':
return $var ? 'TRUE' : 'FALSE';
default: default:
return var_export($var, TRUE); return var_export($var, true);
} }
} }
} }
...@@ -97,10 +97,10 @@ trait ModelTrait ...@@ -97,10 +97,10 @@ trait ModelTrait
try { try {
$relation = @call_user_func(array($model, $method->name)); $relation = @call_user_func(array($model, $method->name));
if ($relation instanceof \yii\db\ActiveQuery) { if ($relation instanceof \yii\db\ActiveQuery) {
#var_dump($relation->primaryModel->primaryKey); //var_dump($relation->primaryModel->primaryKey);
if ($relation->multiple === false) { if ($relation->multiple === false) {
$relationType = 'belongs_to'; $relationType = 'belongs_to';
} elseif ($this->isPivotRelation($relation)) { # TODO: detecttion } elseif ($this->isPivotRelation($relation)) { // TODO: detecttion
$relationType = 'pivot'; $relationType = 'pivot';
} else { } else {
$relationType = 'has_many'; $relationType = 'has_many';
......
...@@ -8,7 +8,7 @@ namespace schmunk42\giiant\generators\crud; ...@@ -8,7 +8,7 @@ namespace schmunk42\giiant\generators\crud;
* @copyright Copyright (c) 2015 diemeisterei GmbH, Stuttgart * @copyright Copyright (c) 2015 diemeisterei GmbH, Stuttgart
* *
* For the full copyright and license information, please view the LICENSE * 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 trait ParamTrait
{ {
......
...@@ -17,7 +17,7 @@ use yii\helpers\Json; ...@@ -17,7 +17,7 @@ use yii\helpers\Json;
trait ProviderTrait 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() public static function getCoreProviders()
{ {
...@@ -42,7 +42,7 @@ trait ProviderTrait ...@@ -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() public function generateProviderCheckboxListData()
{ {
...@@ -67,7 +67,7 @@ trait ProviderTrait ...@@ -67,7 +67,7 @@ trait ProviderTrait
$obj = \Yii::createObject(['class' => $class]); $obj = \Yii::createObject(['class' => $class]);
$obj->generator = $this; $obj->generator = $this;
$this->_p[] = $obj; $this->_p[] = $obj;
#\Yii::trace("Initialized provider '{$class}'", __METHOD__); //\Yii::trace("Initialized provider '{$class}'", __METHOD__);
} }
} }
......
...@@ -24,7 +24,6 @@ class Db ...@@ -24,7 +24,6 @@ class Db
case 'longtext': case 'longtext':
return false; return false;
} }
}; };
} }
...@@ -32,7 +31,6 @@ class Db ...@@ -32,7 +31,6 @@ class Db
{ {
// hide AI columns // hide AI columns
return function ($attribute, $model, $generator) { return function ($attribute, $model, $generator) {
$column = $generator->getColumnByAttribute($attribute); $column = $generator->getColumnByAttribute($attribute);
if (!$column) { if (!$column) {
return; return;
...@@ -41,7 +39,6 @@ class Db ...@@ -41,7 +39,6 @@ class Db
if ($column->autoIncrement) { if ($column->autoIncrement) {
return false; return false;
} }
}; };
} }
} }
<?php <?php
use schmunk42\giiant\helpers\SaveForm; use schmunk42\giiant\helpers\SaveForm;
/**
/*
* @var yii\web\View * @var yii\web\View
* @var yii\widgets\ActiveForm $form * @var yii\widgets\ActiveForm $form
* @var yii\gii\generators\crud\Generator $generator * @var yii\gii\generators\crud\Generator $generator
*/ */
/** /*
* JS for listbox "Saved Form" * JS for listbox "Saved Form"
* on chenging listbox, form fill with selected saved forma data * on chenging listbox, form fill with selected saved forma data
* currently work with input text, input checkbox and select form fields * currently work with input text, input checkbox and select form fields
......
...@@ -104,11 +104,11 @@ EOS; ...@@ -104,11 +104,11 @@ EOS;
return; return;
} }
# handle columns with a primary key, to create links in pivot tables (changed at 0.3-dev; 03.02.2015) // 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 double check with primary keys not named `id` of non-pivot tables
# TODO Note: condition does not apply in every case // TODO Note: condition does not apply in every case
if ($column->isPrimaryKey) { 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); $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column);
...@@ -163,11 +163,11 @@ EOS; ...@@ -163,11 +163,11 @@ EOS;
return; return;
} }
# handle columns with a primary key, to create links in pivot tables (changed at 0.3-dev; 03.02.2015) // 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 double check with primary keys not named `id` of non-pivot tables
# TODO Note: condition does not apply in every case // TODO Note: condition does not apply in every case
if ($column->isPrimaryKey) { if ($column->isPrimaryKey) {
#return null; //return null;
} }
$relation = $this->generator->getRelationByColumn($model, $column); $relation = $this->generator->getRelationByColumn($model, $column);
...@@ -208,9 +208,9 @@ EOS; ...@@ -208,9 +208,9 @@ EOS;
'format' => 'raw', 'format' => 'raw',
] ]
EOS; EOS;
return $code; return $code;
} }
} }
/** /**
......
...@@ -49,7 +49,7 @@ EOS; ...@@ -49,7 +49,7 @@ EOS;
return; return;
} }
if($column->type != 'date'){ if ($column->type != 'date') {
return; return;
} }
......
...@@ -10,29 +10,27 @@ use yii\helpers\Inflector; ...@@ -10,29 +10,27 @@ use yii\helpers\Inflector;
* *
* @author Uldis Nelsons * @author Uldis Nelsons
*/ */
class EditableProvider extends \schmunk42\giiant\base\Provider { class EditableProvider extends \schmunk42\giiant\base\Provider
{
public $skipVirtualAttributes = false; public $skipVirtualAttributes = false;
/** /**
*
*
* @param $column ColumnSchema * @param $column ColumnSchema
* *
* @return null|string * @return null|string
*/ */
public function attributeEditable($attribute) { public function attributeEditable($attribute)
{
$this->generator->requires[] = '"kartik-v/yii2-editable": "@dev"'; $this->generator->requires[] = '"kartik-v/yii2-editable": "@dev"';
$primaryKey = implode('_', $this->generator->getTableSchema()->primaryKey); $primaryKey = implode('_', $this->generator->getTableSchema()->primaryKey);
$column = $this->generator->getTableSchema()->columns[$attribute]; $column = $this->generator->getTableSchema()->columns[$attribute];
/** /*
* search opts... method * search opts... method
*/ */
$modelClass = $this->generator->modelClass; $modelClass = $this->generator->modelClass;
$optsFunc = 'opts' . str_replace('_', '', $attribute); $optsFunc = 'opts'.str_replace('_', '', $attribute);
$optsCamelFunc = 'opts' . str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute)))); $optsCamelFunc = 'opts'.str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute))));
$useOptsFunc = false; $useOptsFunc = false;
if (method_exists($modelClass::className(), $optsFunc)) { if (method_exists($modelClass::className(), $optsFunc)) {
...@@ -43,12 +41,13 @@ class EditableProvider extends \schmunk42\giiant\base\Provider { ...@@ -43,12 +41,13 @@ class EditableProvider extends \schmunk42\giiant\base\Provider {
$inputType = $this->getInputType($column); $inputType = $this->getInputType($column);
$relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column); $relation = $this->generator->getRelationByColumn($this->generator->modelClass, $column);
if($relation){ if ($relation) {
$relModelStatic = $relation->modelClass . 'Static'; $relModelStatic = $relation->modelClass.'Static';
} }
if ($relation && !$relation->multiple && method_exists($relModelStatic, 'getListData')) { if ($relation && !$relation->multiple && method_exists($relModelStatic, 'getListData')) {
$relPk = key($relation->link); $relPk = key($relation->link);
$relName = $this->generator->getModelNameAttribute($relation->modelClass); $relName = $this->generator->getModelNameAttribute($relation->modelClass);
return <<<EOS return <<<EOS
[ [
'attribute' => '{$attribute}', 'attribute' => '{$attribute}',
...@@ -73,10 +72,10 @@ class EditableProvider extends \schmunk42\giiant\base\Provider { ...@@ -73,10 +72,10 @@ class EditableProvider extends \schmunk42\giiant\base\Provider {
] ]
EOS; EOS;
} elseif ($relation && !$relation->multiple) {
}elseif ($relation && !$relation->multiple) {
$relPk = key($relation->link); $relPk = key($relation->link);
$relName = $this->generator->getModelNameAttribute($relation->modelClass); $relName = $this->generator->getModelNameAttribute($relation->modelClass);
return <<<EOS return <<<EOS
[ [
'attribute' => '{$attribute}', 'attribute' => '{$attribute}',
...@@ -161,7 +160,8 @@ EOS; ...@@ -161,7 +160,8 @@ EOS;
* *
* @return mixed|string * @return mixed|string
*/ */
public function relationGridEditable($name, $relation, $showAllRecords = false) { public function relationGridEditable($name, $relation, $showAllRecords = false)
{
$model = new $relation->modelClass(); $model = new $relation->modelClass();
// column counter // column counter
...@@ -203,7 +203,7 @@ EOS; ...@@ -203,7 +203,7 @@ EOS;
} }
$reflection = new \ReflectionClass($relation->modelClass); $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 // $actionColumn = <<<EOS
//[ //[
// 'class' => '{$this->generator->actionButtonClass}', // 'class' => '{$this->generator->actionButtonClass}',
...@@ -221,7 +221,7 @@ EOS; ...@@ -221,7 +221,7 @@ EOS;
// 'controller' => '$controller' // 'controller' => '$controller'
//] //]
//EOS; //EOS;
//
// // add action column // // add action column
// $columns .= $actionColumn.",\n"; // $columns .= $actionColumn.",\n";
// prepare grid column formatters // prepare grid column formatters
...@@ -252,11 +252,11 @@ EOS; ...@@ -252,11 +252,11 @@ EOS;
continue; continue;
} }
/** /*
* search opts... method * search opts... method
*/ */
$optsFunc = 'opts' . str_replace('_', '', $attribute); $optsFunc = 'opts'.str_replace('_', '', $attribute);
$optsCamelFunc = 'opts' . str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute)))); $optsCamelFunc = 'opts'.str_replace(' ', '', ucwords(implode(' ', explode('_', $attribute))));
$useOptsFunc = false; $useOptsFunc = false;
if (method_exists($model::className(), $optsFunc)) { if (method_exists($model::className(), $optsFunc)) {
...@@ -265,15 +265,14 @@ EOS; ...@@ -265,15 +265,14 @@ EOS;
$useOptsFunc = $optsCamelFunc; $useOptsFunc = $optsCamelFunc;
} }
$tableColumn = $this->generator->getColumnByAttribute($attribute, $model); $tableColumn = $this->generator->getColumnByAttribute($attribute, $model);
$inputType = $this->getInputType($tableColumn); $inputType = $this->getInputType($tableColumn);
$relRelation = $this->generator->getRelationByColumn($model->ClassName(), $tableColumn); $relRelation = $this->generator->getRelationByColumn($model->ClassName(), $tableColumn);
if($relRelation){ if ($relRelation) {
$relModelStatic = $relRelation->modelClass . 'Static'; $relModelStatic = $relRelation->modelClass.'Static';
} }
if($tableColumn->type == 'date'){ if ($tableColumn->type == 'date') {
$hasDate = true; $hasDate = true;
$code = " $code = "
[ [
...@@ -302,7 +301,7 @@ EOS; ...@@ -302,7 +301,7 @@ EOS;
], ],
]"; ]";
}elseif ($relRelation && !$relRelation->multiple && method_exists($relModelStatic, 'getListData')) { } elseif ($relRelation && !$relRelation->multiple && method_exists($relModelStatic, 'getListData')) {
$hasParameterForValue = false; $hasParameterForValue = false;
$r = new \ReflectionMethod($relModelStatic, 'getListData'); $r = new \ReflectionMethod($relModelStatic, 'getListData');
$params = $r->getParameters(); $params = $r->getParameters();
...@@ -345,7 +344,6 @@ EOS; ...@@ -345,7 +344,6 @@ EOS;
]"; ]";
} }
} elseif ($relRelation && !$relRelation->multiple) { } elseif ($relRelation && !$relRelation->multiple) {
$relPk = key($relRelation->link); $relPk = key($relRelation->link);
$relName = $this->generator->getModelNameAttribute($relRelation->modelClass); $relName = $this->generator->getModelNameAttribute($relRelation->modelClass);
...@@ -391,15 +389,15 @@ EOS; ...@@ -391,15 +389,15 @@ EOS;
'{$controller}/editable-column-update' '{$controller}/editable-column-update'
] ]
], ],
'inputType' => " . $inputType . " 'inputType' => ".$inputType.'
] ]
]"; ]';
} }
//$code = $this->generator->columnFormat($attr, $model); //$code = $this->generator->columnFormat($attr, $model);
if ($code == false) { if ($code == false) {
continue; continue;
} }
$columns .= $code . ",\n"; $columns .= $code.",\n";
++$counter; ++$counter;
} }
...@@ -412,7 +410,7 @@ EOS; ...@@ -412,7 +410,7 @@ EOS;
function(\$action, \$model, \$key, \$index) { function(\$action, \$model, \$key, \$index) {
\$params = is_array(\$key) ? \$key : ['id' => (string) \$key]; \$params = is_array(\$key) ? \$key : ['id' => (string) \$key];
\$params[0] = '{$controller}/' . \$action; \$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); return Url::toRoute(\$params);
}, },
] ]
...@@ -424,7 +422,7 @@ EOS; ...@@ -424,7 +422,7 @@ EOS;
$firstPageLabel = $this->generator->generateString('First'); $firstPageLabel = $this->generator->generateString('First');
$lastPageLabel = $this->generator->generateString('Last'); $lastPageLabel = $this->generator->generateString('Last');
$code = ''; $code = '';
if($hasDate){ if ($hasDate) {
$code .= <<<EOS $code .= <<<EOS
\$formatter = new IntlDateFormatter(\Yii::\$app->language,IntlDateFormatter::SHORT, IntlDateFormatter::NONE); \$formatter = new IntlDateFormatter(\Yii::\$app->language,IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
\$datePattern = \$formatter->getPattern(); \$datePattern = \$formatter->getPattern();
...@@ -454,8 +452,8 @@ EOS; ...@@ -454,8 +452,8 @@ EOS;
return $code; return $code;
} }
public function getInputType($column) { public function getInputType($column)
{
switch ($column->type) { switch ($column->type) {
case 'double': case 'double':
case 'integer': case 'integer':
...@@ -476,10 +474,9 @@ EOS; ...@@ -476,10 +474,9 @@ EOS;
} }
if (!isset($inputType)) { if (!isset($inputType)) {
return false; return false;
throw new \Exception('No Defined column type: ' . $column->type); throw new \Exception('No Defined column type: '.$column->type);
} }
return $inputType; return $inputType;
} }
} }
...@@ -7,22 +7,24 @@ namespace schmunk42\giiant\generators\extension; ...@@ -7,22 +7,24 @@ namespace schmunk42\giiant\generators\extension;
use Yii; use Yii;
use yii\gii\CodeFile; 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`. * @var string the message category used by `Yii::t()` when `$enableI18N` is `true`.
* Defaults to `app`. * Defaults to `app`
*/ */
public $messageCategory = 'app'; public $messageCategory = 'app';
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function getName() { public function getName()
{
return 'Giiant Extension'; return 'Giiant Extension';
} }
public function rules() { public function rules()
{
return array_merge( return array_merge(
parent::rules(), [ parent::rules(), [
[['messageCategory'], 'required'], [['messageCategory'], 'required'],
...@@ -32,7 +34,8 @@ class Generator extends \yii\gii\generators\extension\Generator { ...@@ -32,7 +34,8 @@ class Generator extends \yii\gii\generators\extension\Generator {
); );
} }
public function attributeLabels() { public function attributeLabels()
{
return array_merge( return array_merge(
parent::attributeLabels(), [ parent::attributeLabels(), [
'messageCategory' => 'Message Category', 'messageCategory' => 'Message Category',
...@@ -40,7 +43,8 @@ class Generator extends \yii\gii\generators\extension\Generator { ...@@ -40,7 +43,8 @@ class Generator extends \yii\gii\generators\extension\Generator {
); );
} }
public function hints() { public function hints()
{
return array_merge( return array_merge(
parent::hints(), [ parent::hints(), [
'messageCategory' => 'This is the category used by <code>Yii::t()</code> in case you enable I18N.', '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 { ...@@ -49,32 +53,32 @@ class Generator extends \yii\gii\generators\extension\Generator {
} }
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function stickyAttributes() public function stickyAttributes()
{ {
return ['vendorName', 'outputPath', 'authorName', 'authorEmail', 'enableI18N']; return ['vendorName', 'outputPath', 'authorName', 'authorEmail', 'enableI18N'];
} }
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function generate() { public function generate()
{
$files = parent::generate(); $files = parent::generate();
$modulePath = $this->getOutputPath(); $modulePath = $this->getOutputPath();
$packagePath = $modulePath . '/' . $this->packageName; $packagePath = $modulePath.'/'.$this->packageName;
if($this->enableI18N){ if ($this->enableI18N) {
$files[] = new CodeFile( $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( $files[] = new CodeFile(
$modulePath . '/' . $this->packageName . '/Bootstrap.php', $this->render("Bootstrap.php") $modulePath.'/'.$this->packageName.'/Bootstrap.php', $this->render('Bootstrap.php')
); );
return $files; return $files;
} }
} }
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
?> ?>
<div class="alert alert-info"> <div class="alert alert-info">
Please read the 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. before creating an extension.
</div> </div>
<div class="module-form"> <div class="module-form">
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
echo $form->field($generator, 'namespace'); echo $form->field($generator, 'namespace');
echo $form->field($generator, 'type')->dropDownList($generator->optsType()); echo $form->field($generator, 'type')->dropDownList($generator->optsType());
echo $form->field($generator, 'keywords'); 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, 'title');
echo $form->field($generator, 'description'); echo $form->field($generator, 'description');
echo $form->field($generator, 'authorName'); echo $form->field($generator, 'authorName');
......
This diff is collapsed.
...@@ -7,7 +7,7 @@ use schmunk42\giiant\helpers\SaveForm; ...@@ -7,7 +7,7 @@ use schmunk42\giiant\helpers\SaveForm;
/* @var $form yii\widgets\ActiveForm */ /* @var $form yii\widgets\ActiveForm */
/* @var $generator yii\gii\generators\form\Generator */ /* @var $generator yii\gii\generators\form\Generator */
/** /*
* JS for listbox "Saved Form" * JS for listbox "Saved Form"
* on chenging listbox, form fill with selected saved forma data * on chenging listbox, form fill with selected saved forma data
* currently work with input text, input checkbox and select form fields * currently work with input text, input checkbox and select form fields
...@@ -18,8 +18,6 @@ echo $form->field($generator, 'savedForm')->dropDownList( ...@@ -18,8 +18,6 @@ echo $form->field($generator, 'savedForm')->dropDownList(
SaveForm::getSavedFormsListbox($generator->getName()), ['onchange' => 'fillForm(this.value)'] SaveForm::getSavedFormsListbox($generator->getName()), ['onchange' => 'fillForm(this.value)']
); );
echo $form->field($generator, 'tableName'); echo $form->field($generator, 'tableName');
echo $form->field($generator, 'tablePrefix'); echo $form->field($generator, 'tablePrefix');
echo $form->field($generator, 'modelClass'); echo $form->field($generator, 'modelClass');
...@@ -31,7 +29,7 @@ echo $form->field($generator, 'generateRelations')->dropDownList([ ...@@ -31,7 +29,7 @@ echo $form->field($generator, 'generateRelations')->dropDownList([
Generator::RELATIONS_ALL => Yii::t('yii', 'All relations'), Generator::RELATIONS_ALL => Yii::t('yii', 'All relations'),
Generator::RELATIONS_ALL_INVERSE => Yii::t('yii', 'All relations with inverse'), 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, 'generateLabelsFromComments')->checkbox();
echo $form->field($generator, 'generateHintsFromComments')->checkbox(); echo $form->field($generator, 'generateHintsFromComments')->checkbox();
echo $form->field($generator, 'generateModelClass')->checkbox(); echo $form->field($generator, 'generateModelClass')->checkbox();
......
<?php <?php
namespace schmunk42\giiant\generators\module; namespace schmunk42\giiant\generators\module;
use yii\gii\CodeFile; use yii\gii\CodeFile;
...@@ -6,15 +7,16 @@ use yii\helpers\StringHelper; ...@@ -6,15 +7,16 @@ use yii\helpers\StringHelper;
/** /**
* @link http://www.diemeisterei.de/ * @link http://www.diemeisterei.de/
*
* @copyright Copyright (c) 2015 diemeisterei GmbH, Stuttgart * @copyright Copyright (c) 2015 diemeisterei GmbH, Stuttgart
* *
* For the full copyright and license information, please view the LICENSE * 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 class Generator extends \yii\gii\generators\module\Generator
{ {
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function getName() public function getName()
{ {
...@@ -22,46 +24,45 @@ class Generator extends \yii\gii\generators\module\Generator ...@@ -22,46 +24,45 @@ class Generator extends \yii\gii\generators\module\Generator
} }
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function requiredTemplates() public function requiredTemplates()
{ {
return ['module.php', 'controller.php', 'view.php']; return ['module.php', 'controller.php', 'view.php'];
} }
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function generate() public function generate()
{ {
$files = []; $files = [];
$modulePath = $this->getModulePath(); $modulePath = $this->getModulePath();
$files[] = new CodeFile( $files[] = new CodeFile(
$modulePath . '/' . StringHelper::basename($this->moduleClass) . '.php', $modulePath.'/'.StringHelper::basename($this->moduleClass).'.php',
$this->render("module.php") $this->render('module.php')
); );
$files[] = new CodeFile( $files[] = new CodeFile(
$modulePath . '/controllers/DefaultController.php', $modulePath.'/controllers/DefaultController.php',
$this->render("controller.php") $this->render('controller.php')
); );
$files[] = new CodeFile( $files[] = new CodeFile(
$modulePath . '/views/default/index.php', $modulePath.'/views/default/index.php',
$this->render("view.php") $this->render('view.php')
); );
$files[] = new CodeFile( $files[] = new CodeFile(
$modulePath . '/traits/ActiveRecordDbConnectionTrait.php', $modulePath.'/traits/ActiveRecordDbConnectionTrait.php',
$this->render("db-connection-trait.php") $this->render('db-connection-trait.php')
); );
return $files; return $files;
} }
/** /**
* @return string the controller namespace of the module. * @return string the controller namespace of the module
*/ */
public function getTraitsNamespace() public function getTraitsNamespace()
{ {
return substr($this->moduleClass, 0, strrpos($this->moduleClass, '\\')) . '\traits'; return substr($this->moduleClass, 0, strrpos($this->moduleClass, '\\')).'\traits';
} }
} }
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
/* @var $generator yii\gii\generators\module\Generator */ /* @var $generator yii\gii\generators\module\Generator */
?> ?>
<?= "<?php" ?> <?= '<?php' ?>
use rmrevin\yii\fontawesome\FA; use rmrevin\yii\fontawesome\FA;
use yii\helpers\Inflector; use yii\helpers\Inflector;
......
<?php <?php
namespace schmunk42\giiant\generators\test; namespace schmunk42\giiant\generators\test;
use Yii; use Yii;
...@@ -6,7 +7,7 @@ use yii\gii\CodeFile; ...@@ -6,7 +7,7 @@ use yii\gii\CodeFile;
use yii\db\Schema; use yii\db\Schema;
/** /**
* This generator generates unit tests for crud operations * This generator generates unit tests for crud operations.
* *
* @author Github: gradosevic * @author Github: gradosevic
*/ */
...@@ -19,29 +20,28 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -19,29 +20,28 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
/** /**
* @var string Codeception's root path * @var string Codeception's root path
*
*/ */
public $codeceptionPath = '/tests/codeception/'; public $codeceptionPath = '/tests/codeception/';
/** /**
* @var string Controller's class name * @var string Controller's class name
*/ */
public $controllerClass = ""; public $controllerClass = '';
/** /**
* @var string Model's class name * @var string Model's class name
*/ */
public $modelClass = ""; public $modelClass = '';
public $modelNs = ""; public $modelNs = '';
/** /**
* @var string Search model's class name * @var string Search model's class name
*/ */
public $searchModelClass = ""; public $searchModelClass = '';
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function getName() public function getName()
{ {
...@@ -49,7 +49,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -49,7 +49,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
} }
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function getDescription() public function getDescription()
{ {
...@@ -57,7 +57,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -57,7 +57,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
} }
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function requiredTemplates() public function requiredTemplates()
{ {
...@@ -66,14 +66,16 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -66,14 +66,16 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
/** /**
* @param $table Table schema * @param $table Table schema
*
* @return array Attributes containing all required model's information for test generator * @return array Attributes containing all required model's information for test generator
*/ */
public function generateAttributes($table){ public function generateAttributes($table)
{
$labels = $this->generateLabels($table); $labels = $this->generateLabels($table);
$attributes = []; $attributes = [];
foreach ($table->columns as $column) { foreach ($table->columns as $column) {
$label = $column->name; $label = $column->name;
if(isset($labels[$column->name])){ if (isset($labels[$column->name])) {
$label = $labels[$column->name]; $label = $labels[$column->name];
} }
$attribute = []; $attribute = [];
...@@ -117,11 +119,12 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -117,11 +119,12 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
} }
$attributes[] = $attribute; $attributes[] = $attribute;
} }
return $attributes; return $attributes;
} }
/** /**
* @inheritdoc * {@inheritdoc}
*/ */
public function generate() public function generate()
{ {
...@@ -130,7 +133,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -130,7 +133,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
$db = $this->getDbConnection(); $db = $this->getDbConnection();
$class = $this->modelNs.$this->modelClass; $class = $this->modelNs.$this->modelClass;
$classTableNameMethod = "tableName"; $classTableNameMethod = 'tableName';
$this->tableName = $class::$classTableNameMethod(); $this->tableName = $class::$classTableNameMethod();
//TODO: Add unit tests for search model //TODO: Add unit tests for search model
...@@ -145,7 +148,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -145,7 +148,7 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
'tableName' => $tableName, 'tableName' => $tableName,
'className' => $className, 'className' => $className,
'modelClass' => $this->modelClass, 'modelClass' => $this->modelClass,
'controllerClass'=> $this->controllerClass, 'controllerClass' => $this->controllerClass,
'labels' => $this->generateLabels($tableSchema), 'labels' => $this->generateLabels($tableSchema),
'rules' => $this->generateRules($tableSchema), 'rules' => $this->generateRules($tableSchema),
'attributes' => $this->generateAttributes($tableSchema), 'attributes' => $this->generateAttributes($tableSchema),
...@@ -155,10 +158,11 @@ class Generator extends \schmunk42\giiant\generators\model\Generator ...@@ -155,10 +158,11 @@ class Generator extends \schmunk42\giiant\generators\model\Generator
]; ];
$files[] = new CodeFile( $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) $this->render('unit.php', $params)
); );
} }
return $files; return $files;
} }
} }
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
* This is the template for generating the crud operations unit test class of a specified model. * 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. * 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 schmunk42\giiant\generators\model\Generator $generator
* @var string $className class name * @var string $className class name
* @var array $relations list of relations (name => relation declaration) * @var array $relations list of relations (name => relation declaration)
...@@ -13,7 +13,6 @@ ...@@ -13,7 +13,6 @@
* @var string $modelClass fully qualified model class name * @var string $modelClass fully qualified model class name
* @var string $controllerClass fully qualified controller class name * @var string $controllerClass fully qualified controller class name
*/ */
echo "<?php\n"; echo "<?php\n";
?> ?>
namespace tests\codeception\backend\unit\models; namespace tests\codeception\backend\unit\models;
...@@ -58,8 +57,10 @@ class <?= $className ?>Test extends DbTestCase ...@@ -58,8 +57,10 @@ class <?= $className ?>Test extends DbTestCase
{ {
$model = $this->newModelInstance(); $model = $this->newModelInstance();
$this->specify($this->modelName.' model should be created', function () use ($model) { $this->specify($this->modelName.' model should be created', function () use ($model) {
<?php foreach($attributes as $attr): <?php foreach ($attributes as $attr):
if(isPK($attr)){ continue;}?> if (isPK($attr)) {
continue;
}?>
expect('model\'s attribute "<?= $attr['label'] ?>" exists ', isset($model-><?= $attr['name'] ?>))->true(); expect('model\'s attribute "<?= $attr['label'] ?>" exists ', isset($model-><?= $attr['name'] ?>))->true();
<?php endforeach; ?> <?php endforeach; ?>
}); });
...@@ -79,8 +80,10 @@ class <?= $className ?>Test extends DbTestCase ...@@ -79,8 +80,10 @@ class <?= $className ?>Test extends DbTestCase
$reloadedModel = $this->loadModelById($this->modelPK); $reloadedModel = $this->loadModelById($this->modelPK);
$this->specify($this->modelName.' model should be saved', function () use ($reloadedModel, $model) { $this->specify($this->modelName.' model should be saved', function () use ($reloadedModel, $model) {
<?php foreach($attributes as $attr): <?php foreach ($attributes as $attr):
if(isPK($attr)){ continue;}?> if (isPK($attr)) {
continue;
}?>
expect('model\'s attribute "<?= $attr['label'] ?>" saved correctly', $reloadedModel-><?= $attr['name'] ?>)->equals($model-><?= $attr['name'] ?>); expect('model\'s attribute "<?= $attr['label'] ?>" saved correctly', $reloadedModel-><?= $attr['name'] ?>)->equals($model-><?= $attr['name'] ?>);
<?php endforeach; ?> <?php endforeach; ?>
}); });
...@@ -100,8 +103,10 @@ class <?= $className ?>Test extends DbTestCase ...@@ -100,8 +103,10 @@ class <?= $className ?>Test extends DbTestCase
$updatedModel = clone $originalModel; $updatedModel = clone $originalModel;
<?php foreach($attributes as $attr): <?php foreach ($attributes as $attr):
if(isPK($attr)){ continue;}?> if (isPK($attr)) {
continue;
}?>
$updatedModel-><?php echo $attr['name'] ?> = $this->updateAttributeValue($originalModel-><?php echo $attr['name'] ?>, '<?php echo $attr['name'] ?>', '<?php echo $attr['type'] ?>'); $updatedModel-><?php echo $attr['name'] ?> = $this->updateAttributeValue($originalModel-><?php echo $attr['name'] ?>, '<?php echo $attr['name'] ?>', '<?php echo $attr['type'] ?>');
<?php endforeach; ?> <?php endforeach; ?>
if(!$updatedModel->save($this->isModelValidationEnabled)){ if(!$updatedModel->save($this->isModelValidationEnabled)){
...@@ -110,7 +115,7 @@ class <?= $className ?>Test extends DbTestCase ...@@ -110,7 +115,7 @@ class <?= $className ?>Test extends DbTestCase
$reloadedModel = $this->loadModelById($this->modelPK); $reloadedModel = $this->loadModelById($this->modelPK);
$this->specify($this->modelName.' model should be updated', function () use ($reloadedModel, $updatedModel) { $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'] ?>); expect('model\'s attribute "<?= $attr['label'] ?>" was updated ', $reloadedModel-><?= $attr['name'] ?>)->equals($updatedModel-><?= $attr['name'] ?>);
<?php endforeach; ?> <?php endforeach; ?>
}); });
...@@ -150,8 +155,10 @@ class <?= $className ?>Test extends DbTestCase ...@@ -150,8 +155,10 @@ class <?= $className ?>Test extends DbTestCase
{ {
$r = new \ReflectionClass($this->class); $r = new \ReflectionClass($this->class);
$model = $r->newInstance(); $model = $r->newInstance();
<?php foreach($attributes as $attr): <?php foreach ($attributes as $attr):
if(isPK($attr)){ continue;}?> if (isPK($attr)) {
continue;
}?>
$model-><?php echo $attr['name'] ?> = GiiantFaker::<?php echo $attr['type'] ?>('<?php echo $attr['name'] ?>'); $model-><?php echo $attr['name'] ?> = GiiantFaker::<?php echo $attr['type'] ?>('<?php echo $attr['name'] ?>');
<?php endforeach; ?> <?php endforeach; ?>
...@@ -191,21 +198,22 @@ class <?= $className ?>Test extends DbTestCase ...@@ -191,21 +198,22 @@ class <?= $className ?>Test extends DbTestCase
} }
<?php <?php
#region HELPER FUNCTIONS //region HELPER FUNCTIONS
function isPK($attribute){ function isPK($attribute)
{
return $attribute['primary'] === true; return $attribute['primary'] === true;
} }
function PKAttributeName($attributes){ function PKAttributeName($attributes)
foreach($attributes as $a): {
if($a['primary'] === true){ foreach ($attributes as $a):
if ($a['primary'] === true) {
return $a['name']; return $a['name'];
} }
endforeach; endforeach;
return "id";
}
return 'id';
}
#endregions #endregions
<?php <?php
namespace schmunk42\giiant\helpers; namespace schmunk42\giiant\helpers;
use yii\faker; use yii\faker;
class GiiantFaker extends \Faker\Factory{ class GiiantFaker extends \Faker\Factory
{
private static $fakerFactory; private static $fakerFactory;
const TYPE_STRING = "string"; const TYPE_STRING = 'string';
const TYPE_INTEGER = "integer"; const TYPE_INTEGER = 'integer';
const TYPE_NUMBER = "number"; const TYPE_NUMBER = 'number';
const TYPE_BOOLEAN = "boolean"; const TYPE_BOOLEAN = 'boolean';
const TYPE_DATE = "date"; const TYPE_DATE = 'date';
const TYPE_TIME = "time"; const TYPE_TIME = 'time';
const TYPE_DATETIME = "datetime"; const TYPE_DATETIME = 'datetime';
const TYPE_TIMESTAMP = "timestamp"; const TYPE_TIMESTAMP = 'timestamp';
const FORMAT_DATE = "Y-m-d"; const FORMAT_DATE = 'Y-m-d';
const FORMAT_TIME = "H:i:s"; const FORMAT_TIME = 'H:i:s';
const FORMAT_DATETIME = "Y-m-d H:i:s"; const FORMAT_DATETIME = 'Y-m-d H:i:s';
const FORMAT_TIMESTAMP = "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 * @return \Faker\Generator
*/ */
public static function create(){ public static function create()
if(self::$fakerFactory == null){ {
if (self::$fakerFactory == null) {
self::$fakerFactory = parent::create(); self::$fakerFactory = parent::create();
} }
return self::$fakerFactory; 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 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 * @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(); self::create();
$preferredValue = self::provider($type, $methodName); $preferredValue = self::provider($type, $methodName);
if($preferredValue !== null){ if ($preferredValue !== null) {
return $preferredValue; return $preferredValue;
} }
switch($type): switch ($type):
case self::TYPE_INTEGER: case self::TYPE_INTEGER:
return self::$fakerFactory->randomNumber; return self::$fakerFactory->randomNumber;
case self::TYPE_NUMBER: case self::TYPE_NUMBER:
...@@ -55,16 +61,20 @@ class GiiantFaker extends \Faker\Factory{ ...@@ -55,16 +61,20 @@ class GiiantFaker extends \Faker\Factory{
case self::TYPE_BOOLEAN: case self::TYPE_BOOLEAN:
return self::$fakerFactory->boolean; return self::$fakerFactory->boolean;
case self::TYPE_DATE: case self::TYPE_DATE:
$format = ($format === NULL)? self::FORMAT_DATE:$format; $format = ($format === null) ? self::FORMAT_DATE : $format;
return self::$fakerFactory->date($format); return self::$fakerFactory->date($format);
case self::TYPE_TIME: case self::TYPE_TIME:
$format = ($format === NULL)? self::FORMAT_TIME:$format; $format = ($format === null) ? self::FORMAT_TIME : $format;
return self::$fakerFactory->time($format); return self::$fakerFactory->time($format);
case self::TYPE_DATETIME: case self::TYPE_DATETIME:
$format = ($format === NULL)? self::FORMAT_DATETIME:$format; $format = ($format === null) ? self::FORMAT_DATETIME : $format;
return self::$fakerFactory->dateTime()->format($format); return self::$fakerFactory->dateTime()->format($format);
case self::TYPE_TIMESTAMP: case self::TYPE_TIMESTAMP:
$format = ($format === NULL)? self::FORMAT_TIMESTAMP:$format; $format = ($format === null) ? self::FORMAT_TIMESTAMP : $format;
return self::$fakerFactory->dateTime()->format($format); return self::$fakerFactory->dateTime()->format($format);
default: default:
return self::$fakerFactory->word; return self::$fakerFactory->word;
...@@ -72,18 +82,18 @@ class GiiantFaker extends \Faker\Factory{ ...@@ -72,18 +82,18 @@ class GiiantFaker extends \Faker\Factory{
} }
/** /**
* 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 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 null
*/ */
public static function provider($type = self::TYPE_STRING, $methodName = "", $format = null){ public static function provider($type = self::TYPE_STRING, $methodName = '', $format = null)
{
$fakerValue = null; $fakerValue = null;
try{ try {
$fakerValue = self::$fakerFactory->$methodName; $fakerValue = self::$fakerFactory->$methodName;
switch($type): switch ($type):
case self::TYPE_INTEGER: case self::TYPE_INTEGER:
$fakerValue = (int) $fakerValue; $fakerValue = (int) $fakerValue;
break; break;
...@@ -94,75 +104,94 @@ class GiiantFaker extends \Faker\Factory{ ...@@ -94,75 +104,94 @@ class GiiantFaker extends \Faker\Factory{
$fakerValue = (string) $fakerValue; $fakerValue = (string) $fakerValue;
break; break;
endswitch; endswitch;
}catch (\Exception $e){ } catch (\Exception $e) {
$fakerValue = null; $fakerValue = null;
} }
return $fakerValue; return $fakerValue;
} }
/** /**
* @param string $methodName model's attribute type trying to match Faker's method name * @param string $methodName model's attribute type trying to match Faker's method name
*
* @return mixed * @return mixed
*/ */
public static function string($methodName = ""){ public static function string($methodName = '')
{
$val = self::provider(self::TYPE_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 * @param string $methodName model's attribute type trying to match Faker's method name
*
* @return mixed * @return mixed
*/ */
public static function integer($methodName = ""){ public static function integer($methodName = '')
{
$val = self::provider(self::TYPE_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 * @param string $methodName model's attribute type trying to match Faker's method name
*
* @return mixed * @return mixed
*/ */
public static function number($methodName = ""){ public static function number($methodName = '')
{
$val = self::provider(self::TYPE_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 * @return mixed
*/ */
public static function boolean(){ public static function boolean()
{
return self::value(self::TYPE_BOOLEAN); return self::value(self::TYPE_BOOLEAN);
} }
/** /**
* @param null $format - Custom format * @param null $format - Custom format
*
* @return mixed * @return mixed
*/ */
public static function date($format = null){ public static function date($format = null)
{
return self::value(self::TYPE_DATE, $format); return self::value(self::TYPE_DATE, $format);
} }
/** /**
* @param null $format - Custom format * @param null $format - Custom format
*
* @return mixed * @return mixed
*/ */
public static function time($format = null){ public static function time($format = null)
{
return self::value(self::TYPE_TIME, $format); return self::value(self::TYPE_TIME, $format);
} }
/** /**
* @param null $format - Custom format * @param null $format - Custom format
*
* @return mixed * @return mixed
*/ */
public static function datetime($format = null){ public static function datetime($format = null)
{
return self::value(self::TYPE_DATETIME, $format); return self::value(self::TYPE_DATETIME, $format);
} }
/** /**
* @param null $format - Custom format * @param null $format - Custom format
*
* @return mixed * @return mixed
*/ */
public static function timestamp($format = null){ public static function timestamp($format = null)
{
return self::value(self::TYPE_TIMESTAMP, $format); return self::value(self::TYPE_TIMESTAMP, $format);
} }
} }
...@@ -4,18 +4,20 @@ namespace schmunk42\giiant\helpers; ...@@ -4,18 +4,20 @@ namespace schmunk42\giiant\helpers;
use yii\helpers\StringHelper; use yii\helpers\StringHelper;
class SaveForm { class SaveForm
{
public static $savedFormList = false; public static $savedFormList = false;
public static function hint() { public static function hint()
{
return ['savedForm' => 'Choose saved form ad load it data to form.']; return ['savedForm' => 'Choose saved form ad load it data to form.'];
} }
/** /**
* get form attributes values. * get form attributes values.
*/ */
public static function getFormAttributesValues($generator, $attributes) { public static function getFormAttributesValues($generator, $attributes)
{
$values = []; $values = [];
foreach ($attributes as $name) { foreach ($attributes as $name) {
$values[strtolower($name)] = [ $values[strtolower($name)] = [
...@@ -28,28 +30,29 @@ class SaveForm { ...@@ -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 * @return array
*/ */
public static function loadSavedForms($generatorName) { public static function loadSavedForms($generatorName)
{
$suffix = str_replace(' ', '', $generatorName); $suffix = str_replace(' ', '', $generatorName);
if (self::$savedFormList) { if (self::$savedFormList) {
return self::$savedFormList; return self::$savedFormList;
} }
/** /*
* get all possible gii directories with out validation on existing * get all possible gii directories with out validation on existing
*/ */
$giiDirs = []; $giiDirs = [];
$giiDirs[] = \Yii::getAlias('@app/gii'); $giiDirs[] = \Yii::getAlias('@app/gii');
if ($commonGiiDir = \Yii::getAlias('@common/gii', false)) if ($commonGiiDir = \Yii::getAlias('@common/gii', false)) {
$giiDirs[] = $commonGiiDir; $giiDirs[] = $commonGiiDir;
}
foreach (\Yii::$app->modules as $moduleId => $module) { foreach (\Yii::$app->modules as $moduleId => $module) {
/** /*
* get module base path * get module base path
*/ */
if (method_exists($module, 'getBasePath')) { if (method_exists($module, 'getBasePath')) {
...@@ -63,12 +66,12 @@ class SaveForm { ...@@ -63,12 +66,12 @@ class SaveForm {
$giiDirs[] = $basePath; $giiDirs[] = $basePath;
} }
/** /*
* from all gii directories collec forms * from all gii directories collec forms
*/ */
$forms = []; $forms = [];
foreach($giiDirs as $basePath){ foreach ($giiDirs as $basePath) {
/** /*
* search in module gii directory all forms json files * search in module gii directory all forms json files
* with required suffix * with required suffix
*/ */
...@@ -76,16 +79,15 @@ class SaveForm { ...@@ -76,16 +79,15 @@ class SaveForm {
continue; continue;
} }
$files = scandir($basePath); $files = scandir($basePath);
foreach ($files as $file) { foreach ($files as $file) {
if (!preg_match('#' . $suffix . '\.json$#', $file)) { if (!preg_match('#'.$suffix.'\.json$#', $file)) {
continue; continue;
} }
$name = preg_replace('#' . $suffix . '\.json$#', '', $file); $name = preg_replace('#'.$suffix.'\.json$#', '', $file);
$forms[$moduleId . $name] = [ $forms[$moduleId.$name] = [
'jsonData' => file_get_contents($basePath . '/' . $file), 'jsonData' => file_get_contents($basePath.'/'.$file),
'label' => $moduleId . ' - ' . $name, 'label' => $moduleId.' - '.$name,
]; ];
} }
} }
...@@ -94,32 +96,38 @@ class SaveForm { ...@@ -94,32 +96,38 @@ class SaveForm {
} }
/** /**
* get array for form field "Saved form" data * get array for form field "Saved form" data.
*
* @return array * @return array
*/ */
public static function getSavedFormsListbox($generatorName) { public static function getSavedFormsListbox($generatorName)
{
$r = ['0' => ' - ']; $r = ['0' => ' - '];
foreach (SaveForm::loadSavedForms($generatorName) as $k => $row) { foreach (self::loadSavedForms($generatorName) as $k => $row) {
$r[$k] = $row['label']; $r[$k] = $row['label'];
} }
return $r; 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 * @return string
*/ */
public static function getSavedFormsJs($generatorName) { public static function getSavedFormsJs($generatorName)
{
$js = []; $js = [];
foreach (SaveForm::loadSavedForms($generatorName) as $k => $row) { foreach (self::loadSavedForms($generatorName) as $k => $row) {
$js[] = $k . ":'" . $row['jsonData'] . "'"; $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 ' return '
function fillForm(id){ function fillForm(id){
if (id=="0") return; if (id=="0") return;
...@@ -169,5 +177,4 @@ class SaveForm { ...@@ -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