Example #1
0
 public function api_items($slug)
 {
     $menu = MenuItem::find()->where(['route_string' => $slug])->one();
     if (!$menu) {
         $menuItem = new MenuItem(['name' => Inflector::humanize($slug), 'url' => $slug]);
         $menuItem->makeRoot();
     }
     return $this->formatItem($menu ? $menu->children : []);
 }
Example #2
0
 public function init()
 {
     if (!$this->name) {
         $this->name = Inflector::humanize($this->id);
     }
     if (!$this->controller instanceof UserController) {
         throw new InvalidParamException(\Yii::t('app', 'This action is designed to work with: {controller}', ['controller' => UserController::className()]));
     }
     $this->defaultView = $this->id;
     if ($this->viewName) {
         $this->defaultView = $this->viewName;
     }
     parent::init();
 }
Example #3
0
 public function init()
 {
     //Если название не задано, покажем что нибудь.
     if (!$this->name) {
         $this->name = Inflector::humanize($this->id);
     }
     if (!$this->controller instanceof AdminController) {
         throw new InvalidParamException(\Yii::t('app', 'This action is designed to work with the controller: ') . AdminController::className());
     }
     $this->defaultView = $this->id;
     if ($this->viewName) {
         $this->defaultView = $this->viewName;
     }
     parent::init();
 }
Example #4
0
 /**
  * Create a new ActiveWindow class based on you properties.
  */
 public function actionCreate()
 {
     $name = $this->prompt("Please enter a name for the Active Window:", ['required' => true]);
     $className = $this->createClassName($name, $this->suffix);
     $moduleId = $this->selectModule(['text' => 'What module should ' . $className . ' belong to?', 'onlyAdmin' => true]);
     $module = Yii::$app->getModule($moduleId);
     $folder = $module->basePath . DIRECTORY_SEPARATOR . 'aws';
     $file = $folder . DIRECTORY_SEPARATOR . $className . '.php';
     $content = $this->view->render('@luya/console/commands/views/aw/create.php', ['className' => $className, 'namespace' => $module->getNamespace() . '\\aws', 'luya' => $this->getLuyaVersion(), 'moduleId' => $moduleId, 'alias' => Inflector::humanize(Inflector::camel2words($className))]);
     FileHelper::createDirectory($folder);
     if (FileHelper::writeFile($file, $content)) {
         return $this->outputSuccess("The Active Window file '{$file}' has been writtensuccessfull.");
     }
     return $this->outputError("Error while writing the Actice Window file '{$file}'.");
 }
Example #5
0
 /**
  * Get core menu
  * @return array
  * @var $ids array has 'Menu Lable' => 'Controller' pairs
  */
 protected function getCoreMenus()
 {
     $mid = '/' . $this->getUniqueId() . '/';
     $ids = ['Assignments' => 'assignment', 'Roles' => 'role', 'Permissions' => 'permission', 'Routes' => 'route', 'Rules' => 'rule', 'Menus' => 'menu'];
     $config = components\Configs::instance();
     $result = [];
     foreach ($ids as $lable => $id) {
         if ($id !== 'menu' || $config->db !== null && $config->db->schema->getTableSchema($config->menuTable) !== null) {
             $result[$id] = ['label' => Yii::t('rbac-admin', $lable), 'url' => [$mid . $id]];
         }
     }
     foreach (array_keys($this->controllerMap) as $id) {
         $result[$id] = ['label' => Yii::t('rbac-admin', Inflector::humanize($id)), 'url' => [$mid . $id]];
     }
     return $result;
 }
 /**
  * Paginated endpoint for display all commodities from Eddb
  * @return array
  */
 public function actionIndex()
 {
     $query = Commodity::find();
     if (Yii::$app->request->get('category', false)) {
         // Find the requested category first
         $category = CommodityCategory::find()->where(['name' => Inflector::humanize(Yii::$app->request->get('category', NULL))])->one();
         if ($category === NULL) {
             throw new HttpException(404, 'Could not find commodities for the requested category');
         }
         // Append it to the query
         $query->andWhere(['category_id' => $category->id]);
     }
     // Also provide filtering by name
     if (Yii::$app->request->get('name', false)) {
         $query->andWhere(['name' => Inflector::humanize(Yii::$app->request->get('name', 'nothing'))]);
     }
     return ResponseBuilder::build($query, 'commodities', Yii::$app->request->get('sort', 'id'), Yii::$app->request->get('order', 'asc'));
 }
Example #7
0
 private function normalizeController()
 {
     $controllers = [];
     $this->menus = [];
     $mid = '/' . $this->getUniqueId() . '/';
     $items = ArrayHelper::merge($this->getCoreItems(), $this->items);
     foreach ($items as $id => $config) {
         $label = Inflector::humanize($id);
         $visible = true;
         if (is_array($config)) {
             $label = ArrayHelper::remove($config, 'label', $label);
             $visible = ArrayHelper::remove($config, 'visible', true);
         }
         if ($visible) {
             $this->menus[] = ['label' => $label, 'url' => [$mid . $id]];
             $controllers[$id] = $config;
         }
     }
     $this->controllerMap = ArrayHelper::merge($this->controllerMap, $controllers);
 }
Example #8
0
 /**
  * Initializes the PNotify widget.
  * 
  * @param    void
  * @return   void
  * 
  * @since    1.0.0
  *
  */
 public function init()
 {
     parent::init();
     //assets
     PNotifyAsset::register($this->getView());
     //base objects
     $session = \Yii::$app->getSession();
     $flashes = $session->getAllFlashes();
     //go through all flashes
     foreach ($flashes as $type => $data) {
         //only for registered types
         if (in_array($type, $this->alertTypes)) {
             $data = (array) $data;
             //all mesages for this type
             foreach ($data as $i => $message) {
                 //show PNotify flash
                 Yii::$app->view->registerJs(static::populate('window.PNotifyObj.info("{title}", "{text}", "{type}");', ['title' => \yii\helpers\Inflector::humanize($type), 'text' => $message, 'type' => $type]));
             }
             $session->removeFlash($type);
         }
     }
 }
Example #9
0
 /**
  * Generates code for active field
  *
  * @param string $attribute
  *
  * @return string
  */
 public function generateActiveField($attribute)
 {
     $tableSchema = $this->getTableSchema();
     if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
             return "\$form->field(\$model, '{$attribute}')->passwordInput()";
         } else {
             return "\$form->field(\$model, '{$attribute}')";
         }
     }
     $column = $tableSchema->columns[$attribute];
     if (in_array($column->dbType, ['smallint(1)', 'tinyint(1)'])) {
         return "\$form->field(\$model->loadDefaultValues(), '{$attribute}')->checkbox(['class'=>'b-switch'], false)";
     } elseif ($column->type === 'text') {
         return "\$form->field(\$model, '{$attribute}', ['enableClientValidation'=>false, 'enableAjaxValidation'=>false])->textarea(['rows' => 6])";
     } elseif ($this->isImage($column->name)) {
         return $this->_generateImageField($column);
     } elseif ($column->name === 'name') {
         return "\$form->field(\$model, '{$attribute}')->textInput(['maxlength' => 255, 'autofocus'=>\$model->isNewRecord ? true:false])";
     } elseif ($this->_isFk($column)) {
         return "\$form->field(\$model, '{$attribute}')\n\t\t->dropDownList(\n\t\t\tArrayHelper::map(" . Inflector::id2camel(rtrim($attribute, '_id'), '_') . "::find()->asArray()->all(), 'id', 'name'),\n\t\t\t['prompt'=>'']\n\t\t)";
     } elseif (stripos($column->name, 'price') !== false) {
         return "\$form->field(\$model, '{$attribute}',\n\t\t['inputTemplate' => '<div class=\"row\"><div class=\"col-sm-4\"><div class=\"input-group\">{input}<span class=\"input-group-addon\">€</span></div></div></div>',]\n\t)->textInput()";
     } else {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
             $input = 'passwordInput';
         } else {
             $input = 'textInput';
         }
         if (is_array($column->enumValues) && count($column->enumValues) > 0) {
             $dropDownOptions = [];
             foreach ($column->enumValues as $enumValue) {
                 $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
             }
             return "\$form->field(\$model, '{$attribute}')->dropDownList(" . preg_replace("/\n\\s*/", ' ', VarDumper::export($dropDownOptions)) . ", ['prompt' => ''])";
         } elseif ($column->phpType !== 'string' || $column->size === null) {
             return "\$form->field(\$model, '{$attribute}')->{$input}()";
         } else {
             return "\$form->field(\$model, '{$attribute}')->{$input}(['maxlength' => {$column->size}])";
         }
     }
 }
 public function generateTabularActiveField($tableName, $attribute)
 {
     $db = Yii::$app->get('db', false);
     $tableSchema = $db->getSchema()->getTableSchema($tableName);
     if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
             return "\$form->field(\${$tableName}Mod, '{$attribute}', ['template' => '{input}{hint}{error}'])->passwordInput()";
         } else {
             return "\$form->field(\${$tableName}Mod, '{$attribute}', ['template' => '{input}{hint}{error}'])";
         }
     }
     $column = $tableSchema->columns[$attribute];
     if ($column->isPrimaryKey) {
         return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->textInput(['readonly' => true, 'style' => 'width : 60px']);";
     } elseif ($column->phpType === 'boolean') {
         return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->checkbox([], false)";
     } elseif ($column->type === 'smallint' && $column->size == 1) {
         return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->checkbox([], false)";
     } elseif ($column->type === 'text') {
         return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->textarea(['rows' => 6])";
     } elseif ($column->type === 'date') {
         return " ''\n                ?>\n                 <?php\n    echo \\kartik\\date\\DatePicker::widget([\n        'model' => \${$tableName}Mod,\n        'attribute' => \"[\$index]{$attribute}\",\n        'options' => ['placeholder' => 'Select date ...', 'class' => 'detaildatepicker'],\n        'pluginOptions' => [      \n            'todayHighlight' => true,\n            'autoclose'=>true,\n            'format' => 'yyyy-mm-dd'                    \n        ]\n]);\n    ?>\n    <?= ''\n             ";
     } elseif ($column->type === 'datetime') {
         return " ''\n                ?>\n                 <?php\n    echo kartik\\datetime\\DateTimePicker::widget([\n        'model' => \${$tableName}Mod,\n        'attribute' => \"[\$index]{$attribute}\",\n        'options' => ['placeholder' => 'Select time ...', 'class' => 'detaildatetimepicker'],\n        'pluginOptions' => [      \n            'todayHighlight' => true,\n            'autoclose'=>true,\n            'format' => 'yyyy-mm-dd hh:ii'                    \n        ]\n]);\n    ?>\n    <?= ''\n             ";
     } elseif ($column->type === 'integer' && $this->getForeignKeyInfo($attribute, $tableName) !== null) {
         $foreignKeyInfo = $this->getForeignKeyInfo($attribute, $tableName);
         $foreignTable = $foreignKeyInfo['foreignTable'];
         $foreignKey = $foreignKeyInfo['foreignKey'];
         $modGen = new yii\gii\generators\model\Generator();
         $className = $modGen->generateClassName($foreignTable);
         $foreignFieldName = $this->getNameAttributeOfTable($foreignTable);
         return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->dropDownList(\\yii\\helpers\\ArrayHelper::map(app\\models\\{$className}::find()->orderBy('{$foreignFieldName}')->asArray()->all(), '{$foreignKey}', '{$foreignFieldName}'), ['prompt' => 'Select...'])";
     } else {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
             $input = 'passwordInput';
         } else {
             $input = 'textInput';
         }
         if (is_array($column->enumValues) && count($column->enumValues) > 0) {
             $dropDownOptions = [];
             foreach ($column->enumValues as $enumValue) {
                 $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
             }
             return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->dropDownList(" . preg_replace("/\n\\s*/", ' ', VarDumper::export($dropDownOptions)) . ", ['prompt' => ''])";
         } elseif ($column->phpType !== 'string' || $column->size === null) {
             return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->{$input}()";
         } else {
             return "\$form->field(\${$tableName}Mod, \"[\$index]{$attribute}\", ['template' => '{input}{hint}{error}'])->{$input}(['maxlength' => {$column->size}])";
         }
     }
 }
Example #11
0
    /**
     * Generates code for active field
     * @param string $attribute
     * @return string
     */
    
    public function generateActiveField($attribute)
    {
        $tableSchema = $this->getTableSchema();
        
        
        if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
            if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
                return "\$form->field(\$model, '$attribute')->passwordInput()";
            } else {
                return "\$form->field(\$model, '$attribute')";
            }
        }
        $column = $tableSchema->columns[$attribute];
       

        if ($column->phpType === 'boolean') {
            return "\$form->field(\$model, '$attribute')->checkbox()";
        } elseif ($column->type === 'text') {
            return "\$form->field(\$model, '$attribute')->textarea(['rows' => 6])";
        } else {
            if (preg_match('/^(password|pass|passwd|passcode|contrasena)$/i', $column->name)) {
                $input = 'passwordInput';
            } else {
                $input = 'textInput';
            }
            if (is_array($column->enumValues) && count($column->enumValues) > 0) {
                $dropDownOptions = [];
                foreach ($column->enumValues as $enumValue) {
                    $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
                }
                return "\$form->field(\$model, '$attribute')->dropDownList("
                    . preg_replace("/\n\s*/", ' ', VarDumper::export($dropDownOptions)).", ['prompt' => ''])";
            } elseif ($column->phpType !== 'string' || $column->size === null) {
	            $partes = explode('_',$column->name); 
							$finalCampo=$partes[count($partes)-1];
	            if($finalCampo == "did"){			
		            $this->c++;
 					return "\$form->field(\$model, '$attribute')->dropDownList(ArrayHelper::map(app\\models\\".ucfirst($tableSchema->foreignKeys[$this->c][0])."::find()->asArray()->all(), 'id', 'nombre'), ['prompt'=>'-Seleccione-'])";
	            }else if($finalCampo == "aid"){
		            $this->c++;
		            return "\$form->field(\$model, '$attribute')->widget(Select2::classname(), [
							    'data' => ArrayHelper::map(app\\models\\".ucfirst($tableSchema->foreignKeys[$this->c][0])."::find()->asArray()->all(), 'id', 'nombre'),
							    'language' => 'es',
							    'theme' => Select2::THEME_CLASSIC,
							    'options' => ['placeholder' => '-Seleccione-'],
							    'pluginOptions' => [
							        'allowClear' => true
							    ],
								]);";
				}else if($finalCampo == "f"){
					return "\$form->field(\$model, '$attribute')->widget(DateControl::classname(), [
					    'type'=>DateControl::FORMAT_DATE,							    
					]);";								
	            }else if($finalCampo == "ft"){
		          	return "\$form->field(\$model, '$attribute')->widget(DateControl::classname(), [
								    'type'=>DateControl::FORMAT_DATETIME,							    
								]);";
				}else if($finalCampo == "m"){
					return "\$form->field(\$model, '$attribute')->widget(MaskMoney::classname(), [
					    'pluginOptions' => [
					        'prefix' => '$ ',
					        'suffix' => '',
					        'allowNegative' => false
					    ]
					]);";
		          }else{
		            return "\$form->field(\$model, '$attribute')->$input()";
	            }
                
            } else {
                return "\$form->field(\$model, '$attribute')->$input(['maxlength' => true])";
            }
        }
    }
Example #12
0
 public function getFieldType($params)
 {
     $params = ArrayHelper::merge(['lang' => false, 'bsCol' => false], $params);
     /* @var $attribute string */
     /* @var $model \yii\db\ActiveRecord */
     /* @var $modelStr string */
     /* @var $attributeStr string */
     /* @var $lang bool */
     /* @var $fix bool */
     extract($params);
     $field = "\$form->field(" . $modelStr . ", " . $attributeStr . ")";
     $tableSchema = $model->getTableSchema();
     if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
             return $field . "->passwordInput()";
         } else {
             return $field;
         }
     }
     $column = $tableSchema->columns[$attribute];
     if ($lang) {
         $t = "\t\t\t\t\t";
         $t2 = "\t\t\t\t\t";
         $t3 = "\t\t\t\t\t\t";
     } else {
         if ($fix) {
             $t = "\t\t\t\t";
             $t2 = "\t\t\t";
             $t3 = "\t\t\t\t";
         } else {
             $t = "\t\t";
             $t2 = "\t";
             $t3 = "\t\t";
         }
     }
     $column->comment = strtolower($column->comment);
     if ($column->comment == 'redactor') {
         return "\\pavlinter\\adm\\Adm::widget('Redactor',[\n{$t3}'form' => \$form,\n{$t3}'model'      => " . $modelStr . ",\n{$t3}'attribute'  => " . $attributeStr . "\n{$t2}])";
     }
     if ($column->comment == 'fileinput') {
         return "\\pavlinter\\adm\\Adm::widget('FileInput',[\n{$t3}'form'        => \$form,\n{$t3}'model'       => " . $modelStr . ",\n{$t3}'attribute'   => " . $attributeStr . "\n{$t2}])";
     }
     if ($column->comment == 'checkbox') {
         return "\$form->field(" . $modelStr . ", " . $attributeStr . ", [\"template\" => \"{input}\\n{label}\\n{hint}\\n{error}\"])->widget(\\kartik\\checkbox\\CheckboxX::classname(), [\n{$t3}'pluginOptions' => [\n\t{$t3}'threeState' => false\n{$t3}]\n{$t2}]);";
     }
     if ($column->comment == 'select2' || $column->comment == 'range' || $column->dbType === 'tinyint(1)') {
         if ($column->comment == 'range' || $column->dbType === 'tinyint(1)') {
             $data = "\$model::{$column->name}_list()";
         } else {
             $data = '[]';
         }
         return $field . "->widget(\\kartik\\widgets\\Select2::classname(), [\n{$t3}'data' => {$data},\n{$t3}'options' => ['placeholder' => Adm::t('','Select ...', ['dot' => false])],\n{$t3}'pluginOptions' => [\n\t{$t3}'allowClear' => true,\n{$t3}]\n{$t2}]);";
     }
     if ($column->phpType === 'boolean' || $column->phpType === 'tinyint(1)') {
         return $field . "->checkbox()";
     } elseif ($column->type === 'text' || $column->comment == 'textarea') {
         return $field . "->textarea(['rows' => 6])";
     } else {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
             $input = 'passwordInput';
         } else {
             $input = 'textInput';
         }
         if (is_array($column->enumValues) && count($column->enumValues) > 0) {
             $dropDownOptions = [];
             foreach ($column->enumValues as $enumValue) {
                 $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
             }
             return $field . "->dropDownList(" . preg_replace("/\n\\s*/", ' ', VarDumper::export($dropDownOptions)) . ", ['prompt' => ''])";
         } elseif ($column->phpType !== 'string' || $column->size === null) {
             return $field . "->{$input}()";
         } else {
             return $field . "->{$input}(['maxlength' => {$column->size}])";
         }
     }
 }
Example #13
0
 /**
  * Generates code for active field
  * @param string $attribute
  * @return string
  */
 public function generateActiveField($attribute)
 {
     $items_generator = $this->items_generator;
     $tableSchema = $this->getTableSchema();
     if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
             return $items_generator::generateField($attribute, null, $this->templateType, 'passwordInput', null);
         } else {
             return $items_generator::generateField($attribute, null, $this->templateType, null, null);
         }
     }
     $column = $tableSchema->columns[$attribute];
     if ($column->phpType === 'boolean') {
         return $items_generator::generateField($attribute, null, $this->templateType, 'checkbox', null);
     } elseif ($column->type === 'text') {
         return $items_generator::generateField($attribute, null, $this->templateType, 'textarea', ['rows' => 6]);
     } else {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
             $input = 'passwordInput';
         } else {
             $input = 'textInput';
         }
         if (is_array($column->enumValues) && count($column->enumValues) > 0) {
             $dropDownOptions = [];
             foreach ($column->enumValues as $enumValue) {
                 $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
             }
             return $items_generator::generateField($attribute, $dropDownOptions, $this->templateType, 'dropDownList', ['prompt' => '']);
         } elseif ($column->phpType !== 'string' || $column->size === null) {
             return $items_generator::generateField($attribute, null, $this->templateType, $input, null);
         } else {
             return $items_generator::generateField($attribute, null, $this->templateType, $input, ['maxlength' => true]);
         }
     }
 }
 /**
  * Generates code for active field
  * @param string $attribute
  * @return string
  */
 public function generateActiveField($attribute)
 {
     $tableSchema = $this->getTableSchema();
     if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
             return "\$form->field(\$model, '{$attribute}')->passwordInput()";
         } else {
             return "\$form->field(\$model, '{$attribute}')";
         }
     }
     $column = $tableSchema->columns[$attribute];
     if ($column->phpType === 'boolean') {
         return "\$form->field(\$model, '{$attribute}')->checkbox()";
     } elseif ($column->type === 'text') {
         return "\$form->field(\$model, '{$attribute}')->textarea(['rows' => 6])";
     } else {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
             $input = 'passwordInput';
         } else {
             $input = 'textInput';
         }
         if (is_array($column->enumValues) && count($column->enumValues) > 0) {
             $dropDownOptions = [];
             foreach ($column->enumValues as $enumValue) {
                 $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
             }
             return "\$form->field(\$model, '{$attribute}')->dropDownList(" . preg_replace("/\n\\s*/", ' ', VarDumper::export($dropDownOptions)) . ", ['prompt' => ''])";
         } elseif ($column->phpType !== 'string' || $column->size === null) {
             return "\$form->field(\$model, '{$attribute}')->{$input}()";
         } else {
             return "\$form->field(\$model, '{$attribute}')->{$input}(['maxlength' => {$column->size}])";
         }
     }
 }
 /**
  * Import station commodities information
  * @param array $station
  * @param string $class
  * @param array $data
  * @return boolean
  */
 private function importStationCommodity($station, $class, $model, $data)
 {
     Yii::$app->db->createCommand('DELETE FROM station_commodities WHERE station_id = :station_id AND type=:type')->bindValue(':station_id', $station['id'])->bindValue(':type', $class)->execute();
     $i = 0;
     foreach ($data as $d) {
         if ($class === 'listings') {
             $commodity = Commodity::find()->where(['id' => $d['commodity_id']])->one();
         } else {
             $commodity = Commodity::find()->where(['name' => $d])->one();
         }
         if ($commodity !== NULL) {
             $model->attributes = ['station_id' => $station['id'], 'commodity_id' => $commodity->id, 'type' => (string) $class, 'supply' => isset($d['supply']) ? $d['supply'] : null, 'buy_price' => isset($d['buy_price']) ? $d['buy_price'] : null, 'sell_price' => isset($d['sell_price']) ? $d['sell_price'] : null, 'demand' => isset($d['demand']) ? $d['demand'] : null];
             if ($model->save()) {
                 $i++;
             }
         } else {
             Yii::warning("{$station['id']}::{$station['name']} - Couldn't find commodity {$commodity}", __METHOD__);
         }
     }
     $inflected = \yii\helpers\Inflector::humanize($class);
     $this->stdOut("    - {$inflected} :: {$i}\n");
 }
Example #16
0
foreach ($generator->getConstIDs() as $key => $const) {
    ?>
    const <?php 
    echo strtoupper($const);
    ?>
 = <?php 
    echo $key + $generator->start;
    ?>
;
<?php 
}
?>

    public static $list = [
<?php 
foreach ($generator->getConstIDs() as $key => $const) {
    ?>
       self::<?php 
    echo strtoupper($const);
    ?>
 => '<?php 
    echo Inflector::humanize($const);
    ?>
',
<?php 
}
?>
   ];
}

Example #17
0
    public function actionCreate()
    {
        $module = $this->prompt('Module Name (e.g. galleryadmin):');
        $modulePre = $new_str = preg_replace('/admin$/', '', $module);
        $modelName = $this->prompt('Model Name (e.g. Album)');
        $apiEndpoint = $this->prompt('Api Endpoint (e.g. api-' . $modulePre . '-' . strtolower($modelName) . ')');
        $sqlTable = $this->prompt('Database Table name (e.g. ' . strtolower($modulePre) . '_' . Inflector::underscore($modelName) . ')');
        if (!$this->confirm("Create '{$modelName}' controller, api & model based on sql table '{$sqlTable}' in module '{$module}' for api endpoint '{$apiEndpoint}'?")) {
            return $this->outputError('Crud creation aborted.');
        }
        $shema = Yii::$app->db->getTableSchema($sqlTable);
        if (!$shema) {
            return $this->outputError("Could not read informations from database table '{$sqlTable}', table does not exist.");
        }
        $yiiModule = Yii::$app->getModule($module);
        $basePath = $yiiModule->basePath;
        $ns = $yiiModule->getNamespace();
        $modelName = ucfirst($modelName);
        $fileName = ucfirst(strtolower($modelName));
        $modelNs = '\\' . $ns . '\\models\\' . $modelName;
        $data = ['api' => ['folder' => 'apis', 'ns' => $ns . '\\apis', 'file' => $fileName . 'Controller.php', 'class' => $fileName . 'Controller', 'route' => strtolower($module) . '-' . strtolower($modelName) . '-index'], 'controller' => ['folder' => 'controllers', 'ns' => $ns . '\\controllers', 'file' => $fileName . 'Controller.php', 'class' => $fileName . 'Controller'], 'model' => ['folder' => 'models', 'ns' => $ns . '\\models', 'file' => $modelName . '.php', 'class' => $modelName]];
        $apiClass = null;
        foreach ($data as $name => $item) {
            $folder = $basePath . DIRECTORY_SEPARATOR . $item['folder'];
            if (!file_exists($folder)) {
                mkdir($folder);
            }
            if (file_exists($folder . DIRECTORY_SEPARATOR . $item['file'])) {
                echo $this->ansiFormat("Can not create {$folder}" . DIRECTORY_SEPARATOR . $item['file'] . ', file does already exists!', Console::FG_RED) . PHP_EOL;
            } else {
                $content = '<?php' . PHP_EOL . PHP_EOL;
                $content .= 'namespace ' . $item['ns'] . ';' . PHP_EOL . PHP_EOL;
                switch ($name) {
                    case 'api':
                        $content .= 'class ' . $item['class'] . ' extends \\admin\\ngrest\\base\\Api' . PHP_EOL;
                        $content .= '{' . PHP_EOL;
                        $content .= '    public $modelClass = \'' . $modelNs . '\';' . PHP_EOL;
                        $content .= '}';
                        break;
                    case 'controller':
                        $content .= 'class ' . $item['class'] . ' extends \\admin\\ngrest\\base\\Controller' . PHP_EOL;
                        $content .= '{' . PHP_EOL;
                        $content .= '    public $modelClass = \'' . $modelNs . '\';' . PHP_EOL;
                        $content .= '}';
                        break;
                    case 'model':
                        $names = [];
                        $allfields = [];
                        $ngrest = ['text' => [], 'textarea' => []];
                        foreach ($shema->columns as $k => $v) {
                            $allfields[] = $v->name;
                            if ($v->phpType == 'string') {
                                $names[] = $v->name;
                                if ($v->type == 'text') {
                                    $ngrest['textarea'][] = $v->name;
                                }
                                if ($v->type == 'string') {
                                    $ngrest['text'][] = $v->name;
                                }
                            }
                        }
                        $content .= 'class ' . $item['class'] . ' extends \\admin\\ngrest\\base\\Model' . PHP_EOL;
                        $content .= '{' . PHP_EOL;
                        $content .= '    /* yii model properties */' . PHP_EOL . PHP_EOL;
                        $content .= '    public static function tableName()' . PHP_EOL;
                        $content .= '    {' . PHP_EOL;
                        $content .= '        return \'' . $sqlTable . '\';' . PHP_EOL;
                        $content .= '    }' . PHP_EOL . PHP_EOL;
                        $content .= '    public function rules()' . PHP_EOL;
                        $content .= '    {' . PHP_EOL;
                        $content .= '        return [' . PHP_EOL;
                        $content .= '            [[\'' . implode("', '", $names) . '\'], \'required\'],' . PHP_EOL;
                        $content .= '        ];' . PHP_EOL;
                        $content .= '    }' . PHP_EOL . PHP_EOL;
                        $content .= '    public function scenarios()' . PHP_EOL;
                        $content .= '    {' . PHP_EOL;
                        $content .= '        return [' . PHP_EOL;
                        $content .= '            \'restcreate\' => [\'' . implode("', '", $allfields) . '\'],' . PHP_EOL;
                        $content .= '            \'restupdate\' => [\'' . implode("', '", $allfields) . '\'],' . PHP_EOL;
                        $content .= '        ];' . PHP_EOL;
                        $content .= '    }' . PHP_EOL . PHP_EOL;
                        $content .= '    /* ngrest model properties */' . PHP_EOL . PHP_EOL;
                        $content .= '    public function genericSearchFields()' . PHP_EOL;
                        $content .= '    {' . PHP_EOL;
                        $content .= '        return [\'' . implode("', '", $names) . '\'];' . PHP_EOL;
                        $content .= '    }' . PHP_EOL . PHP_EOL;
                        $content .= '    public function ngRestApiEndpoint()' . PHP_EOL;
                        $content .= '    {' . PHP_EOL;
                        $content .= '        return \'' . $apiEndpoint . '\';' . PHP_EOL;
                        $content .= '    }' . PHP_EOL . PHP_EOL;
                        $content .= '    public function ngRestConfig($config)' . PHP_EOL;
                        $content .= '    {' . PHP_EOL;
                        foreach ($ngrest['text'] as $n) {
                            $content .= '        $config->list->field(\'' . $n . '\', \'' . Inflector::humanize($n) . '\')->text();' . PHP_EOL;
                        }
                        foreach ($ngrest['textarea'] as $n) {
                            $content .= '        $config->list->field(\'' . $n . '\', \'' . Inflector::humanize($n) . '\')->textarea();' . PHP_EOL;
                        }
                        $content .= '        $config->create->copyFrom(\'list\');' . PHP_EOL;
                        $content .= '        $config->update->copyFrom(\'list\');' . PHP_EOL;
                        $content .= '        return $config;' . PHP_EOL;
                        $content .= '    }' . PHP_EOL;
                        $content .= '}';
                        break;
                }
                if (file_put_contents($folder . DIRECTORY_SEPARATOR . $item['file'], $content)) {
                    echo $this->ansiFormat('- File ' . $folder . DIRECTORY_SEPARATOR . $item['file'] . ' created.', Console::FG_GREEN) . PHP_EOL;
                }
            }
        }
        $getMenu = 'public function getMenu()
{
    return $this->node(\'' . Inflector::humanize($modelName) . '\', \'http://materializecss.com/icons.html\')
        ->group(\'GROUP\')
            ->itemApi(\'' . Inflector::humanize($modelName) . '\', \'' . $data['api']['route'] . '\', \'http://materializecss.com/icons.html\', \'' . $apiEndpoint . '\')
    ->menu();
}
            ';
        $mname = $this->ansiFormat($basePath . '/Module.php', Console::BOLD);
        $a = $this->ansiFormat('$apis', Console::BOLD);
        echo PHP_EOL . 'Modify the ' . $a . ' var in ' . $mname . ' like below:' . PHP_EOL . PHP_EOL;
        echo $this->ansiFormat('public $apis = [
    \'' . $apiEndpoint . '\' => \'' . $data['api']['ns'] . '\\' . $data['api']['class'] . '\',
];', Console::FG_YELLOW);
        echo PHP_EOL . PHP_EOL . 'Update the getMenu() method like below:' . PHP_EOL . PHP_EOL;
        echo $this->ansiFormat($getMenu, Console::FG_YELLOW);
        echo PHP_EOL;
        return 0;
    }
Example #18
0
?>
<div class="table-responsive">
    <table class="table table-condensed table-bordered table-striped table-hover request-table" style="table-layout: fixed;">
        <thead>
            <tr>
                <th>Name</th>
                <th>Value</th>
            </tr>
        </thead>
        <tbody>
        <?php 
foreach ($request as $name => $value) {
    ?>
            <tr>
                <th><?php 
    echo Html::encode(\yii\helpers\Inflector::humanize($name));
    ?>
</th>
                <td>
<?php 
    if (preg_match('/_{0,1}(size|length)_{0,1}/', $name)) {
        echo $formatter->asSize($value);
    } else {
        if (strpos($name, 'speed') !== false) {
            echo $formatter->asSize($value) . '/s';
        } else {
            if (strpos($name, 'time') !== false && is_numeric($value) && $value >= 0) {
                echo number_format($value, 2) . 's';
            } else {
                if ($name == 'http_code') {
                    $type = substr($value, 0, 1);
Example #19
0
 public static function statusDropdown()
 {
     static $dropdown;
     if ($dropdown === null) {
         $reflClass = new ReflectionClass(get_called_class());
         $constants = $reflClass->getConstants();
         foreach ($constants as $constantName => $constantValue) {
             if (preg_match('/^ST_/', $constantName)) {
                 $prettyName = str_replace("ST_", "", $constantName);
                 $prettyName = Inflector::humanize(strtolower($prettyName));
                 $dropdown[$constantValue] = Yii::t('user', $prettyName);
             }
         }
     }
     return $dropdown;
 }
 /**
  * Generates code for active search field
  * @param string $attribute
  * @return string
  */
 public function generateActiveSearchField($attribute, $tableSchema = null, $relations = null)
 {
     if (is_null($tableSchema)) {
         $tableSchema = $this->getTableSchema();
     }
     if (is_null($relations)) {
         $relations = $this->relations;
     }
     $fk = [];
     foreach ($relations as $key => $value) {
         if (isset($value[5])) {
             $fk[$value[5]] = $value;
             $fk[$value[5]][] = $key;
         }
     }
     $humanize = Inflector::humanize($attribute, true);
     if ($tableSchema === false) {
         return "\$form->field(\$model, '{$attribute}')";
     }
     $column = $tableSchema->columns[$attribute];
     if ($column->phpType === 'boolean') {
         return "\$form->field(\$model, '{$attribute}')->checkbox()";
     } else {
         return "\$form->field(\$model, '{$attribute}')";
     }
 }
Example #21
0
 public function testHumanize()
 {
     $this->assertEquals("Me my self and i", Inflector::humanize('me_my_self_and_i'));
     $this->assertEquals("Me My Self And I", Inflector::humanize('me_my_self_and_i', true));
 }
Example #22
0
 /**
  * Humanize the class name
  *
  * @return string The humanized name.
  */
 public function humanizeName($name)
 {
     return $name = Inflector::humanize(Inflector::camel2words($name));
 }
Example #23
0
 /**
  * Get avalible menu.
  * @return array
  */
 public function getMenus()
 {
     if ($this->_normalizeMenus === null) {
         $mid = '/' . $this->getUniqueId() . '/';
         // resolve core menus
         $this->_normalizeMenus = [];
         $config = components\Configs::instance();
         foreach ($this->_coreItems as $id => $lable) {
             if ($id !== 'menu' || $config->db !== null && $config->db->schema->getTableSchema($config->menuTable) !== null) {
                 $this->_normalizeMenus[$id] = ['label' => Yii::t('rbac-admin', $lable), 'url' => [$mid . $id]];
             }
         }
         foreach (array_keys($this->controllerMap) as $id) {
             $this->_normalizeMenus[$id] = ['label' => Yii::t('rbac-admin', Inflector::humanize($id)), 'url' => [$mid . $id]];
         }
         // user configure menus
         foreach ($this->_menus as $id => $value) {
             if (empty($value)) {
                 unset($this->_normalizeMenus[$id]);
             } else {
                 if (is_string($value)) {
                     $value = ['label' => $value];
                 }
                 $this->_normalizeMenus[$id] = isset($this->_normalizeMenus[$id]) ? array_merge($this->_normalizeMenus[$id], $value) : $value;
                 if (!isset($this->_normalizeMenus[$id]['url'])) {
                     $this->_normalizeMenus[$id]['url'] = [$mid . $id];
                 }
             }
         }
     }
     return $this->_normalizeMenus;
 }
Example #24
0
 /**
  * Generates code for active field
  * @param string $attribute
  * @return string
  */
 public function generateActiveField($attribute)
 {
     $tableSchema = $this->getTableSchema();
     if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
             return $this->generatePasswordInputField($attribute);
         } else {
             //return "\$form->field(\$model, '$attribute')";
             return $this->generateInputTextField($attribute);
         }
     }
     $column = $tableSchema->columns[$attribute];
     if ($column->phpType === 'boolean' || preg_match('/^(is_)$/i', $column->name)) {
         return "\$form->field(\$model, '{$attribute}')->checkbox()";
     } elseif ($column->type === 'text') {
         return $this->generateTextareaField($attribute);
     } else {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
             $input = 'passwordInput';
         } else {
             $input = 'textInput';
         }
         if (is_array($column->enumValues) && count($column->enumValues) > 0) {
             $dropDownOptions = [];
             foreach ($column->enumValues as $enumValue) {
                 $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
             }
             return $this->generateDropdownlistField($attribute, $dropDownOptions);
         } elseif ($column->phpType !== 'string' || $column->size === null) {
             if ($input === 'passwordInput') {
                 return $this->generatePasswordInputField($attribute);
             } else {
                 return $this->generateInputTextField($attribute);
             }
         } else {
             if ($input === 'passwordInput') {
                 return $this->generatePasswordInputField($attribute, "['maxlength' => true]");
             } else {
                 return $this->generateInputTextField($attribute, "['maxlength' => true]");
             }
         }
     }
 }
Example #25
0
 /**
  * Get avalible menu.
  * @return array
  */
 public function getMenus()
 {
     if ($this->_normalizeMenus === null) {
         $mid = '/' . $this->getUniqueId() . '/';
         // resolve core menus
         $this->_normalizeMenus = [];
         $config = components\Configs::instance();
         $conditions = ['user' => $config->db && $config->db->schema->getTableSchema($config->userTable), 'assignment' => ($userClass = Yii::$app->getUser()->identityClass) && is_subclass_of($userClass, 'yii\\db\\BaseActiveRecord'), 'menu' => $config->db && $config->db->schema->getTableSchema($config->menuTable)];
         foreach ($this->_coreItems as $id => $lable) {
             if (!isset($conditions[$id]) || $conditions[$id]) {
                 $this->_normalizeMenus[$id] = ['label' => Yii::t('rbac-admin', $lable), 'url' => [$mid . $id]];
             }
         }
         foreach (array_keys($this->controllerMap) as $id) {
             $this->_normalizeMenus[$id] = ['label' => Yii::t('rbac-admin', Inflector::humanize($id)), 'url' => [$mid . $id]];
         }
         // user configure menus
         foreach ($this->_menus as $id => $value) {
             if (empty($value)) {
                 unset($this->_normalizeMenus[$id]);
                 continue;
             }
             if (is_string($value)) {
                 $value = ['label' => $value];
             }
             $this->_normalizeMenus[$id] = isset($this->_normalizeMenus[$id]) ? array_merge($this->_normalizeMenus[$id], $value) : $value;
             if (!isset($this->_normalizeMenus[$id]['url'])) {
                 $this->_normalizeMenus[$id]['url'] = [$mid . $id];
             }
         }
     }
     return $this->_normalizeMenus;
 }
Example #26
0
 public function actionCreate()
 {
     $type = $this->select('Do you want to create an app or module Block?', ['app' => 'Creates a project block inside your @app Namespace (casual).', 'module' => 'Creating a block inside a later specified Module.']);
     $module = false;
     if ($type == 'module' && count($this->getModuleProposal()) === 0) {
         return $this->outputError('Your project does not have Project-Modules registered!');
     }
     if ($type == 'module') {
         $module = $this->select('Choose a module to create the block inside:', $this->getModuleProposal());
     }
     $blockName = $this->prompt('Insert a name for your Block (e.g. HeadTeaser):', ['required' => true]);
     if (substr(strtolower($blockName), -5) !== 'block') {
         $blockName = $blockName . 'Block';
     }
     $blockName = Inflector::camelize($blockName);
     // vars
     $config = ['vars' => [], 'cfgs' => [], 'placeholders' => []];
     $doConfigure = $this->confirm('Would you like to configure this Block? (vars, cfgs, placeholders)', false);
     if ($doConfigure) {
         $doVars = $this->confirm('Add new Variable (vars)?', false);
         $i = 1;
         while ($doVars) {
             $item = $this->varCreator('Variabel (vars) #' . $i, 'var');
             $this->phpdoc[] = '{{vars.' . $item['var'] . '}}';
             $config['vars'][] = $item;
             $doVars = $this->confirm('Add one more?', false);
             ++$i;
         }
         $doCfgs = $this->confirm('Add new Configuration (cgfs)?', false);
         $i = 1;
         while ($doCfgs) {
             $item = $this->varCreator('Configration (cfgs) #' . $i, 'cfg');
             $this->phpdoc[] = '{{cfgs.' . $item['var'] . '}}';
             $config['cfgs'][] = $item;
             $doCfgs = $this->confirm('Add one more?', false);
             ++$i;
         }
         $doPlaceholders = $this->confirm('Add new Placeholder (placeholders)?', false);
         $i = 1;
         while ($doPlaceholders) {
             $item = $this->placeholderCreator('Placeholder (placeholders) #' . $i);
             $this->phpdoc[] = '{{placeholders.' . $item['var'] . '}}';
             $config['placeholders'][] = $item;
             $doPlaceholders = $this->confirm('Add one more?', false);
             ++$i;
         }
     }
     if ($module) {
         $moduleObject = Yii::$app->getModule($module);
         $basePath = $moduleObject->basePath;
         $ns = $moduleObject->getNamespace();
     } else {
         $basePath = Yii::$app->basePath;
         $ns = 'app';
     }
     $ns = $ns . '\\blocks';
     $content = '<?php' . PHP_EOL . PHP_EOL;
     $content .= 'namespace ' . $ns . ';' . PHP_EOL . PHP_EOL;
     $content .= '/**' . PHP_EOL;
     $content .= ' * Block created with Luya Block Creator Version ' . \luya\Module::VERSION . ' at ' . date('d.m.Y H:i') . PHP_EOL;
     $content .= ' */' . PHP_EOL;
     $content .= 'class ' . $blockName . ' extends \\cmsadmin\\base\\Block' . PHP_EOL;
     $content .= '{' . PHP_EOL;
     if ($module) {
         $content .= PHP_EOL . '    public $module = \'' . $module . '\';' . PHP_EOL . PHP_EOL;
     }
     // method name
     $content .= '    public function name()' . PHP_EOL;
     $content .= '    {' . PHP_EOL;
     $content .= '        return \'' . Inflector::humanize($blockName) . '\';' . PHP_EOL;
     $content .= '    }' . PHP_EOL . PHP_EOL;
     // method icon
     $content .= '    public function icon()' . PHP_EOL;
     $content .= '    {' . PHP_EOL;
     $content .= '        return \'extension\'; // choose icon from: http://materializecss.com/icons.html' . PHP_EOL;
     $content .= '    }' . PHP_EOL . PHP_EOL;
     $content .= '    public function config()' . PHP_EOL;
     $content .= '    {' . PHP_EOL;
     $content .= '        return [' . PHP_EOL;
     // get vars
     if (count($config['vars'])) {
         $content .= '           \'vars\' => [' . PHP_EOL;
         foreach ($config['vars'] as $k => $v) {
             $content .= '               [\'var\' => \'' . $v['var'] . '\', \'label\' => \'' . $v['label'] . '\', \'type\' => \'' . $v['type'] . '\'';
             if (isset($v['options'])) {
                 $content .= ', \'options\' => ' . $v['options'];
             }
             $content .= '],' . PHP_EOL;
         }
         $content .= '           ],' . PHP_EOL;
     }
     // get cfgs
     if (count($config['cfgs'])) {
         $content .= '           \'cfgs\' => [' . PHP_EOL;
         foreach ($config['cfgs'] as $k => $v) {
             $content .= '               [\'var\' => \'' . $v['var'] . '\', \'label\' => \'' . $v['label'] . '\', \'type\' => \'' . $v['type'] . '\'';
             if (isset($v['options'])) {
                 $content .= ', \'options\' => ' . $v['options'];
             }
             $content .= '],' . PHP_EOL;
         }
         $content .= '           ],' . PHP_EOL;
     }
     // get placeholders
     if (count($config['placeholders'])) {
         $content .= '           \'placeholders\' => [' . PHP_EOL;
         foreach ($config['placeholders'] as $k => $v) {
             $content .= '               [\'var\' => \'' . $v['var'] . '\', \'label\' => \'' . $v['label'] . '\'],' . PHP_EOL;
         }
         $content .= '           ],' . PHP_EOL;
     }
     $content .= '        ];' . PHP_EOL;
     $content .= '    }' . PHP_EOL . PHP_EOL;
     // method extraVars
     $content .= '    /**' . PHP_EOL;
     $content .= '     * Return an array containg all extra vars. Those variables you can access in the Twig Templates via {{extras.*}}.' . PHP_EOL;
     $content .= '     */' . PHP_EOL;
     $content .= '    public function extraVars()' . PHP_EOL;
     $content .= '    {' . PHP_EOL;
     $content .= '        return [' . PHP_EOL;
     foreach ($this->extras as $x) {
         $content .= '            ' . $x . PHP_EOL;
     }
     $content .= '        ];' . PHP_EOL;
     $content .= '    }' . PHP_EOL . PHP_EOL;
     // method twigFrontend
     $content .= '    /**' . PHP_EOL;
     $content .= '     * Available twig variables:' . PHP_EOL;
     foreach ($this->phpdoc as $doc) {
         $content .= '     * @param ' . $doc . PHP_EOL;
     }
     $content .= '     */' . PHP_EOL;
     $content .= '    public function twigFrontend()' . PHP_EOL;
     $content .= '    {' . PHP_EOL;
     $content .= '        return \'<p>My Frontend Twig of this Block</p>\';' . PHP_EOL;
     $content .= '    }' . PHP_EOL . PHP_EOL;
     // method twigAdmin
     $content .= '    /**' . PHP_EOL;
     $content .= '     * Available twig variables:' . PHP_EOL;
     foreach ($this->phpdoc as $doc) {
         $content .= '     * @param ' . $doc . PHP_EOL;
     }
     $content .= '     */' . PHP_EOL;
     $content .= '    public function twigAdmin()' . PHP_EOL;
     $content .= '    {' . PHP_EOL;
     $content .= '        return \'<p>My Admin Twig of this Block</p>\';' . PHP_EOL;
     $content .= '    }' . PHP_EOL;
     $content .= '}' . PHP_EOL;
     $dir = $basePath . '/blocks';
     $mkdir = FileHelper::createDirectory($dir);
     $file = $dir . DIRECTORY_SEPARATOR . $blockName . '.php';
     if (file_exists($file)) {
         return $this->outputError("File '{$file}' does already eixsts.");
     }
     $creation = file_put_contents($file, $content);
     if ($creation) {
         return $this->outputSuccess("File '{$file}' created");
     }
     return $this->outputError("Error while creating file '{$file}'");
 }
Example #27
0
 /**
  * Get list of statuses for creating dropdowns
  *
  * @return array
  */
 public static function statusDropdown()
 {
     // get data if needed
     static $dropdown;
     if ($dropdown === null) {
         // create a reflection class to get constants
         $reflClass = new ReflectionClass(get_called_class());
         $constants = $reflClass->getConstants();
         // check for status constants (e.g., STATUS_ACTIVE)
         foreach ($constants as $constantName => $constantValue) {
             // add prettified name to dropdown
             if (strpos($constantName, "STATUS_") === 0) {
                 $prettyName = str_replace("STATUS_", "", $constantName);
                 $prettyName = Inflector::humanize(strtolower($prettyName));
                 $dropdown[$constantValue] = $prettyName;
             }
         }
     }
     return $dropdown;
 }
Example #28
0
 /**
  * Generates code for active field
  * @param string $attribute
  * @return string
  */
 public function generateActiveField($attribute)
 {
     $tableSchema = $this->getTableSchema();
     if ($tableSchema === false || !isset($tableSchema->columns[$attribute])) {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $attribute)) {
             return "\$form->field(\$model, '{$attribute}')->passwordInput()";
         } else {
             return "\$form->field(\$model, '{$attribute}')";
         }
     }
     $column = $tableSchema->columns[$attribute];
     /**
      * Кастомные поля:
      * Список пользователей
      * Состояние записи
      */
     if ($column->name === 'rec_status_id') {
         return "\$form->field(\$model, '{$attribute}')->dropDownList(ArrayHelper::map(\\app\\models\\RecStatus::find()->active()->all(), 'id', 'name'), ['prompt' => ''])";
     } elseif ($column->name === 'user_id') {
         return "\$form->field(\$model, '{$attribute}')->dropDownList(ArrayHelper::map(\\app\\models\\User::find()->active()->all(), 'id', 'name'), ['prompt' => ''])";
     }
     if ($column->phpType === 'boolean') {
         return "\$form->field(\$model, '{$attribute}')->checkbox()";
     } elseif ($column->type === 'text') {
         return "\$form->field(\$model, '{$attribute}')->textarea(['rows' => 6])";
     } else {
         if (preg_match('/^(password|pass|passwd|passcode)$/i', $column->name)) {
             $input = 'passwordInput';
         } else {
             $input = 'textInput';
         }
         if (is_array($column->enumValues) && count($column->enumValues) > 0) {
             $dropDownOptions = [];
             foreach ($column->enumValues as $enumValue) {
                 $dropDownOptions[$enumValue] = Inflector::humanize($enumValue);
             }
             return "\$form->field(\$model, '{$attribute}')->dropDownList(" . preg_replace("/\n\\s*/", ' ', VarDumper::export($dropDownOptions)) . ", ['prompt' => ''])";
         } elseif ($column->phpType !== 'string' || $column->size === null) {
             return "\$form->field(\$model, '{$attribute}')->{$input}()";
         } else {
             return "\$form->field(\$model, '{$attribute}')->{$input}(['maxlength' => true])";
         }
     }
 }
 /**
  * Returns types available
  * @param $type
  * @return array
  */
 public function listTypes($type)
 {
     $data = [];
     // create a reflection class to get constants
     $refl = new ReflectionClass(get_called_class());
     $constants = $refl->getConstants();
     foreach ($constants as $constantName => $constantValue) {
         // add prettified name to dropdown
         if (strpos($constantName, $type) === 0) {
             $prettyName = preg_replace('/' . $type . '/', "", $constantName, 1);
             $prettyName = Inflector::humanize(strtolower($prettyName));
             $data[$constantValue] = trim(ucwords($prettyName));
         }
     }
     return $data;
 }
Example #30
0
 public function getStepLabel($step = null)
 {
     if (is_null($step)) {
         $step = $this->_currentStep;
     }
     $label = $this->_stepLabels[$step];
     if (!is_string($label)) {
         //            $label = ucwords(trim(strtolower(str_replace(array('-', '_', '.'), ' ', preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $step)))));
         $label = Inflector::humanize($step, true);
     }
     $index = array_search($step, array_values($this->_steps)) + 1;
     return Html::tag('span', $index, ['class' => 'badge']) . " " . $label;
 }