public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->get('routing_key');
     $method = 'read' . Inflector::camelize($routingKey);
     $interpreter = isset($this->interpreters[$this->exchange]) ? $this->interpreters[$this->exchange] : (isset($this->interpreters['*']) ? $this->interpreters['*'] : null);
     if ($interpreter === null) {
         $interpreter = $this;
     } else {
         if (class_exists($interpreter)) {
             $interpreter = new $interpreter();
             if (!$interpreter instanceof AmqpInterpreter) {
                 throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $interpreter));
             }
         } else {
             throw new Exception(sprintf("Interpreter class '%s' was not found.", $interpreter));
         }
     }
     if (method_exists($interpreter, $method) || is_callable([$interpreter, $method])) {
         $info = ['exchange' => $this->exchange, 'routing_key' => $routingKey, 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null, 'delivery_tag' => $msg->get('delivery_tag')];
         try {
             $body = Json::decode($msg->body, true);
         } catch (\Exception $e) {
             $body = $msg->body;
         }
         $interpreter->{$method}($body, $info, $this->amqp->channel);
     } else {
         if (!$interpreter instanceof AmqpInterpreter) {
             $interpreter = new AmqpInterpreter();
         }
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
 public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->delivery_info['routing_key'];
     $method = 'read' . Inflector::camelize($routingKey);
     if (!isset($this->interpreters[$this->exchange])) {
         $interpreter = $this;
     } elseif (class_exists($this->interpreters[$this->exchange])) {
         $interpreter = new $this->interpreters[$this->exchange]();
         if (!$interpreter instanceof AmqpInterpreter) {
             throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->exchange]));
         }
     } else {
         throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->exchange]));
     }
     if (method_exists($interpreter, $method)) {
         $info = ['exchange' => $msg->get('exchange'), 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null];
         $interpreter->{$method}(Json::decode($msg->body, true), $info);
     } else {
         if (!isset($this->interpreters[$this->exchange])) {
             $interpreter = new AmqpInterpreter();
         }
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->exchange), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
Example #3
0
 /**
  * This command echoes what you have entered as the message.
  *
  * @param string $message the message to be echoed.
  */
 public function actionIndex()
 {
     echo "Running batch...\n";
     $config = $this->getYiiConfiguration();
     $config['id'] = 'temp';
     // create models
     foreach ($this->tables as $table) {
         #var_dump($this->tableNameMap, $table);exit;
         $params = ['interactive' => $this->interactive, 'template' => 'default', 'ns' => $this->modelNamespace, 'db' => $this->modelDb, 'tableName' => $table, 'tablePrefix' => $this->tablePrefix, 'generateModelClass' => $this->extendedModels, 'modelClass' => isset($this->tableNameMap[$table]) ? $this->tableNameMap[$table] : Inflector::camelize($table), 'baseClass' => $this->modelBaseClass, 'tableNameMap' => $this->tableNameMap];
         $route = 'gii/giix-model';
         $app = \Yii::$app;
         $temp = new \yii\console\Application($config);
         $temp->runAction(ltrim($route, '/'), $params);
         unset($temp);
         \Yii::$app = $app;
     }
     // create CRUDs
     $providers = ArrayHelper::merge($this->crudProviders, Generator::getCoreProviders());
     foreach ($this->tables as $table) {
         $table = str_replace($this->tablePrefix, '', $table);
         $name = isset($this->tableNameMap[$table]) ? $this->tableNameMap[$table] : Inflector::camelize($table);
         $params = ['interactive' => $this->interactive, 'overwrite' => $this->overwrite, 'template' => 'default', 'modelClass' => $this->modelNamespace . '\\' . $name, 'searchModelClass' => $this->modelNamespace . '\\search\\' . $name . 'Search', 'controllerClass' => $this->crudControllerNamespace . '\\' . $name . 'Controller', 'viewPath' => $this->crudViewPath, 'pathPrefix' => $this->crudPathPrefix, 'actionButtonClass' => 'yii\\grid\\ActionColumn', 'baseControllerClass' => $this->crudBaseControllerClass, 'providerList' => implode(',', $providers)];
         $route = 'gii/giix-crud';
         $app = \Yii::$app;
         $temp = new \yii\console\Application($config);
         $temp->runAction(ltrim($route, '/'), $params);
         unset($temp);
         \Yii::$app = $app;
     }
 }
 /**
  * @return array
  */
 function getLabel()
 {
     $res = [];
     $get = $this->get;
     $attr = $this->attribute;
     $label = $this->label;
     if ($get[$attr] || $get[$attr] == '0') {
         $label = $label ? $label : $this->model->getAttributeLabel($attr) . ':';
         if ($this->getRelationName === true) {
             if (is_array($get[$attr])) {
                 $val = implode(', ', $get[$attr]);
             } else {
                 $strMod = substr(Inflector::camelize($attr), 0, -2);
                 $val = $this->model->{lcfirst($strMod)}->name;
             }
         } elseif ($this->value instanceof Closure) {
             $val = $this->renderDataCell($this->model, $get[$attr]);
         } elseif (!$this->value instanceof Closure && $this->value) {
             $val = $this->value;
         } else {
             if (is_array($get[$attr])) {
                 $val = implode(', ', $get[$attr]);
             } else {
                 $val = $get[$attr];
             }
         }
         $res = ['attr' => $attr, 'label' => $label, 'value' => $val];
     }
     return $res;
 }
Example #5
0
 /**
  * Setter method for $blockName, ensure the correct block name.
  *
  * @param string $name The name of the block.
  */
 public function setBlockName($name)
 {
     if (!StringHelper::endsWith($name, 'Block')) {
         $name .= 'Block';
     }
     $this->_blockName = Inflector::camelize($name);
 }
Example #6
0
 /**
  * Generates a class name with camelcase style and specific suffix, if not already provided
  *
  * @param string $string The name of the class, e.g.: hello_word would
  * @param string $suffix The suffix to append on the class name if not eixsts, e.g.: MySuffix
  * @return string The class name e.g. HelloWorldMySuffix
  * @since 1.0.0-beta4
  */
 public function createClassName($string, $suffix = false)
 {
     $name = Inflector::camelize($string);
     if ($suffix && StringHelper::endsWith($name, $suffix, false)) {
         $name = substr($name, 0, -strlen($suffix));
     }
     return $name . $suffix;
 }
 /**
  * get link parameters for menu access
  *
  * @param String $name
  * @param Array $options
  * @return Array
  */
 static function params($name = '', $options = ['url' => '#'])
 {
     $method = 'params' . Inflector::camelize($name);
     if (method_exists(static::className(), $method)) {
         return ArrayHelper::merge(static::$method(), $options);
     }
     return $options;
 }
 /**
  *
  * @param string $value The name/value of the button to display for the user.
  * @param string $callback The id of the callback if the callback method s name is `callbackSayHello` the callback id would be `say-hello`.
  * @param array $options Define behavior of the button, options are name-value pairs. The following options are available:
  *
  * - params: array, Add additional parameters which will be sent to the callback. ['foo' => 'bar']
  * - closeOnSuccess: boolean, if enabled, the active window will close after successfully sendSuccess() response from callback.
  * - reloadListOnSuccess: boolean, if enabled, the active window will reload the ngrest crud list after success response from callback via sendSuccess().
  * - reloadWindowOnSuccess: boolena, if enabled the active window will reload itself after success (when successResponse is returnd).
  * - class: string, html class fur the button
  * @return string
  */
 public function callbackButton($value, $callback, array $options = [])
 {
     // do we have option params for the button
     $params = array_key_exists('params', $options) ? $options['params'] : [];
     // create the angular controller name
     $controller = 'Controller' . Inflector::camelize($value) . Inflector::camelize($callback);
     // render and return the view with the specific params
     return $this->render('@admin/views/aws/base/_callbackButton', ['angularCrudControllerName' => $controller, 'callbackName' => $this->callbackConvert($callback), 'callbackArgumentsJson' => Json::encode($params), 'buttonNameValue' => $value, 'closeOnSuccess' => isset($options['closeOnSuccess']) ? '$scope.crud.closeActiveWindow();' : null, 'reloadListOnSuccess' => isset($options['reloadListOnSuccess']) ? '$scope.crud.loadList();' : null, 'reloadWindowOnSuccess' => isset($options['reloadWindowOnSuccess']) ? '$scope.$parent.activeWindowReload();' : null, 'buttonClass' => isset($options['class']) ? $options['class'] : 'btn']);
 }
Example #9
0
 /**
  * @inheritdoc
  */
 public function validateAttribute($model, $attribute)
 {
     $this->model = $this->model ?: $model;
     $method = Inflector::camelize(str_replace('_id', '', $attribute) . 'List');
     $list = $this->list === null ? array_keys($this->model->{$method}()) : $this->list;
     $result = is_array($model->{$attribute}) ? !array_diff($model->{$attribute}, $list) : in_array($model->{$attribute}, $list);
     if (!$result) {
         $this->addError($model, $attribute, $this->message ?: \Yii::t('app', 'Forbidden value'));
     }
 }
Example #10
0
 public function validateName($attribute)
 {
     $name = Inflector::camelize(Inflector::slug($this->{$attribute}));
     $label = $this->getAttributeLabel($attribute);
     if (empty($name)) {
         $this->addError($attribute, "'{$label}' должно состоять только из букв и цифр");
     } else {
         $this->{$attribute} = $name;
     }
 }
 public function webhook($data)
 {
     if (!empty($data['event'])) {
         $method = lcfirst(Inflector::camelize($data['event']));
         if (method_exists($this, $method)) {
             return $this->{$method}($data);
         }
     }
     return false;
 }
Example #12
0
 /**
  * Checks whether action with specified ID exists in owner controller.
  * @param string $id action ID.
  * @return boolean whether action exists or not.
  */
 public function actionExists($id)
 {
     $inlineActionMethodName = 'action' . Inflector::camelize($id);
     if (method_exists($this->controller, $inlineActionMethodName)) {
         return true;
     }
     if (array_key_exists($id, $this->controller->actions())) {
         return true;
     }
     return false;
 }
 /**
  * Processing Stripe's callback and making membership updates according to payment data
  *
  * @return void|Response
  */
 public function actionHandleWebhook()
 {
     $payload = json_decode(Yii::$app->request->getRawBody(), true);
     if (!$this->eventExistsOnStripe($payload['id'])) {
         return;
     }
     $method = 'handle' . Inflector::camelize(str_replace('.', '_', $payload['type']));
     if (method_exists($this, $method)) {
         return $this->{$method}($payload);
     } else {
         return $this->missingMethod();
     }
 }
 /**
  * Verify that the action requested is actually an action on the controller
  * @param string $action
  * @return bool
  */
 protected function actionExists($action)
 {
     try {
         $reflection = new \ReflectionClass($this->controller);
         if ($reflection->getMethod('action' . Inflector::camelize($action))) {
             return true;
         }
     } catch (\ReflectionException $e) {
         //method does not exist
         return false;
     }
     return false;
 }
Example #15
0
 /**
  * 
  * @param string $value The name/value of the button to display for the user.
  * @param string $callback The id of the callback if the callback method s name is `callbackSayHello` the callback id would be `say-hello`.
  * @param array $params Additional json parameters to send to the callback.
  * @param array $options Define behavior of the button, optionas are name-value pairs. The following options are available:
  * 
  * - closeOnSuccess: boolean, if enabled, the active window will close after successfully sendSuccess() response from callback.
  * - reloadListOnSuccess: boolean, if enabled, the active window will reload the ngrest crud list after success response from callback via sendSuccess().
  * 
  * @return string
  */
 public function callbackButton($value, $callback, array $params = [], array $options = [])
 {
     $json = Json::encode($params);
     $controller = 'Controller' . Inflector::camelize($value) . Inflector::camelize($callback);
     $callback = $this->callbackConvert($callback);
     $closeOnSuccess = null;
     if (isset($options['closeOnSuccess'])) {
         $closeOnSuccess .= '$scope.crud.closeActiveWindow();';
     }
     $reloadListOnSuccess = null;
     if (isset($options['reloadListOnSuccess'])) {
         $reloadListOnSuccess = '$scope.crud.loadList();';
     }
     $return = '<script>
     zaa.bootstrap.register(\'' . $controller . '\', function($scope, $controller) {
         $scope.crud = $scope.$parent;
         $scope.params = ' . $json . ';
         $scope.sendButton = function(callback) {
             $scope.crud.sendActiveWindowCallback(callback, $scope.params).then(function(success) {
                 var data = success.data;
                 var errorType = null;
                 var message = false;
             
                 if ("error" in data) {
                     errorType = data.error;
                 }
             
                 if ("message" in data) {
                     message = data.message;
                 }
             
                 if (errorType !== null) {
                     if (errorType == true) {
                         $scope.crud.toast.error(message, 8000);
                     } else {
                         $scope.crud.toast.success(message, 8000);
                         ' . $closeOnSuccess . $reloadListOnSuccess . '
                     }
                 }
             
 			}, function(error) {
 				$scope.crud.toast.error(error.data.message, 8000);
 			});
         };
     });
     </script>
     <div ng-controller="' . $controller . '">
         <button ng-click="sendButton(\'' . $callback . '\')" class="btn" type="button">' . $value . '</button>
     </div>';
     return $return;
 }
 /**
  * Инициализация проекта.
  */
 public function actionInit()
 {
     $rawProjectName = pathinfo(Yii::getAlias('@app'), PATHINFO_FILENAME);
     $rawProjectName = Inflector::camelize($rawProjectName);
     $projectId = Inflector::camel2id($rawProjectName);
     $projectId = Console::prompt('Project id', ['default' => $projectId]);
     $projectName = Inflector::titleize($projectId);
     $projectName = Console::prompt('Project name', ['default' => $projectName]);
     $vagrantIp = '192.168.33.' . rand(100, 254);
     $vagrantIp = Console::prompt('Vagrant IP', ['default' => $vagrantIp]);
     $values = ['PROJECT-ID' => $projectId, 'PROJECT-NAME' => $projectName, 'VAGRANT-IP' => $vagrantIp];
     $files = ['@app/build.xml' => ['PROJECT-ID'], '@app/Vagrantfile' => ['VAGRANT-IP', 'PROJECT-ID'], '@app/config/web.php' => ['PROJECT-NAME'], '@app/config/console.php' => ['PROJECT-NAME'], '@app/config/env/vagrant.php' => ['VAGRANT-IP', 'PROJECT-ID']];
     $this->replaceInFiles($files, $values);
 }
 /**
  * Handle a Braintree webhook call.
  *
  * @return mixed|void
  */
 public function actionHandleWebhook()
 {
     try {
         $webhook = $this->parseBraintreeNotification();
     } catch (Exception $e) {
         return;
     }
     $method = 'handle' . Inflector::camelize(str_replace('.', '_', $webhook->kind));
     if (method_exists($this, $method)) {
         return $this->{$method}($webhook);
     } else {
         return $this->missingMethod();
     }
 }
Example #18
0
 protected function renderDataCellContent($model, $key, $index)
 {
     return preg_replace_callback('/\\{([\\w\\-\\/]+)\\}/', function ($matches) use($model, $key, $index) {
         $action = $matches[1];
         $name = Inflector::camelize(strtr($matches[1], ['/' => '_', '\\' => '_']));
         if (isset($this->buttons[$name]) && $this->buttonIsVisible($name, $model, $key, $index)) {
             $url = $this->createUrl($action, $model, $key, $index);
             if (!$this->checkUrlAccess || RoleManager::checkAccessByUrl($url)) {
                 return call_user_func($this->buttons[$name], $url, $model, $key);
             } else {
                 return '';
             }
         } else {
             return '';
         }
     }, $this->template);
 }
Example #19
0
 public function actionExport($object, array $ids = [], array $attributes = [])
 {
     $class = 'app\\models\\export\\' . Inflector::camelize($object);
     if (!class_exists($class)) {
         throw new NotFoundHttpException('The requested page does not exist.');
     }
     $model = new $class();
     $model->ids = $ids;
     if ($attributes) {
         // Extra params
         $model->setAttributes($attributes, false);
     }
     if ($post = Yii::$app->request->post()) {
         $model->load($post);
         $model->export();
     }
     return $this->render('export', ['model' => $model, 'formatters' => $this->getFormatters()]);
 }
 /**
  * This command echoes what you have entered as the message.
  *
  * @param string $message the message to be echoed.
  */
 public function actionIndex()
 {
     echo "Running batch...\n";
     \Yii::setAlias('schmunk42/sakila', '@vendor/schmunk42/yii2-sakila-module');
     $baseNamespace = 'schmunk42\\sakila\\';
     $tables = ['actor', 'address', 'category', 'city', 'country', 'film_actor', 'film', 'customer', 'staff', 'store', 'film_category', 'language', 'inventory', 'payment', 'rental'];
     // works nice with IDE autocompleteion
     $providers = [CallbackProvider::className(), EditorProvider::className(), SelectProvider::className(), DateTimeProvider::className(), RangeProvider::className(), RelationProvider::className()];
     foreach ($tables as $table) {
         $params = ['generate' => $this->generate, 'template' => 'default', 'ns' => 'schmunk42\\sakila\\models', 'tableName' => $table, 'modelClass' => Inflector::camelize($table)];
         $route = 'giic/giiant-model';
         \Yii::$app->runAction(ltrim($route, '/'), $params);
     }
     foreach ($tables as $table) {
         $params = ['generate' => $this->generate, 'template' => 'default', 'moduleID' => 'sakila', 'modelClass' => $baseNamespace . 'models\\' . Inflector::camelize($table), 'searchModelClass' => $baseNamespace . 'models\\' . Inflector::camelize($table) . 'Search', 'controllerClass' => $baseNamespace . 'controllers\\' . Inflector::camelize($table) . 'Controller', 'providerList' => implode(',', $providers)];
         $route = 'giic/giiant-crud';
         \Yii::$app->runAction(ltrim($route, '/'), $params);
     }
 }
 /**
  * 
  * @param type $insert
  * @param type $changedAttributes
  * @return type
  */
 public function afterSave($insert, $changedAttributes)
 {
     //Touch timestamps
     $this->touch('updated_at');
     $this->page->touch('updated_at');
     if (!isset($this->attr['id'])) {
         $this->attr['id'] = $this->id;
     }
     $class = "\\humanized\\contenttoolspage\\models\\containers\\" . \yii\helpers\Inflector::camelize($this->type->name) . "Container";
     echo "\n" . $class . "\n";
     $child = $insert ? new $class() : $class::findOne($this->id);
     $child->setAttributes($this->attr);
     if (!$child->save()) {
         var_dump($child->errors);
         $this->delete();
         return false;
     }
     return parent::afterSave($insert, $changedAttributes);
 }
Example #22
0
 public function init()
 {
     parent::init();
     $lockName = 'TaskLock' . \yii\helpers\Inflector::camelize(self::className());
     \yii\base\Event::on(self::className(), self::EVENT_BEFORE_RUN, function ($event) use($lockName) {
         /* @var $event TaskEvent */
         $db = \Yii::$app->db;
         $result = $db->createCommand("GET_LOCK(:lockname, 1)", [':lockname' => $lockName])->queryScalar();
         if (!$result) {
             // we didn't get the lock which means the task is still running
             $event->cancel = true;
         }
     });
     \yii\base\Event::on(self::className(), self::EVENT_AFTER_RUN, function ($event) use($lockName) {
         // release the lock
         /* @var $event TaskEvent */
         $db = \Yii::$app->db;
         $db->createCommand("RELEASE_LOCK(:lockname, 1)", [':lockname' => $lockName])->queryScalar();
     });
 }
 public function callback(AMQPMessage $msg)
 {
     $routingKey = $msg->delivery_info['routing_key'];
     $method = 'read' . Inflector::camelize($routingKey);
     if (!isset($this->interpreters[$this->queue])) {
         $interpreter = $this;
     } elseif (class_exists($this->interpreters[$this->queue])) {
         $interpreter = new $this->interpreters[$this->queue]();
         if (!$interpreter instanceof AmqpInterpreter) {
             throw new Exception(sprintf("Class '%s' is not correct interpreter class.", $this->interpreters[$this->queue]));
         }
     } else {
         throw new Exception(sprintf("Interpreter class '%s' was not found.", $this->interpreters[$this->queue]));
     }
     if (method_exists($interpreter, $method)) {
         $info = ['exchange' => $msg->get('exchange'), 'queue' => $this->queue, 'routing_key' => $msg->get('routing_key'), 'reply_to' => $msg->has('reply_to') ? $msg->get('reply_to') : null];
         try {
             $interpreter->{$method}(Json::decode($msg->body, true), $info);
         } catch (\Exception $exc) {
             $error_info = "consumer fail:" . $exc->getMessage() . PHP_EOL . "info:" . print_r($info, true) . PHP_EOL . "body:" . PHP_EOL . print_r($msg->body, true) . PHP_EOL . $exc->getTraceAsString();
             \Yii::warning($error_info, __METHOD__);
             $format = [Console::FG_RED];
             Console::stdout(Console::ansiFormat($error_info . PHP_EOL, $format));
             Console::stdout(Console::ansiFormat($exc->getTraceAsString() . PHP_EOL, $format));
         }
     } else {
         if (!isset($this->interpreters[$this->queue])) {
             $interpreter = new AmqpInterpreter();
         }
         $error_info = "Unknown routing key '{$routingKey}' for exchange '{$this->queue}'.";
         $error_info .= PHP_EOL . $msg->body;
         \Yii::warning($error_info, __METHOD__);
         $interpreter->log(sprintf("Unknown routing key '%s' for exchange '%s'.", $routingKey, $this->queue), $interpreter::MESSAGE_ERROR);
         // debug the message
         $interpreter->log(print_r(Json::decode($msg->body, true), true), $interpreter::MESSAGE_INFO);
     }
 }
Example #24
0
 public function getField($field, $owner = null)
 {
     $fields = $this->fields;
     if (isset($fields[$field])) {
         return $fields[$field];
     } else {
         $functionName = 'get' . Inflector::camelize($field) . 'Field';
         if (method_exists($this, $functionName)) {
             return $this->{$functionName}();
         } elseif (isset($this->{$field})) {
             // create artificial field
             return $this->createArtificialField($field, $this->{$field}, $owner);
         }
     }
     return;
 }
Example #25
0
 protected function applyTemplate($name, &$config)
 {
     $view = $this->getView();
     if (isset($config['js'])) {
         $injection = end($this->_injections);
         if ($injection === false) {
             $injection = $this->injection;
         }
         if (empty($config['controller'])) {
             $config['controller'] = Inflector::camelize($name) . 'Controller';
         }
         $this->_controller = $config['controller'];
         $injection = array_unique(array_merge($injection, ArrayHelper::remove($config, 'injection', [])));
         $this->_controllers[$this->_controller]['injection'] = $injection;
         $this->_controllers[$this->_controller]['js'][] = Helper::parseBlockJs($view->render($config['js'], ['widget' => $this]));
         unset($config['js']);
     } elseif (isset($config['controller'])) {
         $this->_controller = $config['controller'];
     }
     if (isset($config['view'])) {
         $config['template'] = $view->render($config['view'], ['widget' => $this]);
         unset($config['view']);
     }
     if (isset($config['resolve'])) {
         if (is_string($config['resolve']) && strncmp($config['resolve'], 'js:', 3) === 0) {
             $config['resolve'] = new JsExpression(substr($config['resolve'], 3));
         } elseif (is_array($config['resolve'])) {
             foreach ($config['resolve'] as $key => $value) {
                 if (is_string($value) && strncmp($value, 'js:', 3) === 0) {
                     $config['resolve'][$key] = new JsExpression(substr($value, 3));
                 }
             }
         }
     }
     $this->_controller = null;
 }
Example #26
0
 /**
  * Run batch process to generate models all given tables
  * @throws \yii\console\Exception
  */
 public function actionModels()
 {
     // create models
     foreach ($this->tables as $table) {
         #var_dump($this->tableNameMap, $table);exit;
         $params = ['interactive' => $this->interactive, 'overwrite' => $this->overwrite, 'template' => $this->template, 'ns' => $this->modelNamespace, 'db' => $this->modelDb, 'tableName' => $table, 'tablePrefix' => $this->tablePrefix, 'enableI18N' => $this->enableI18N, 'singularEntities' => $this->singularEntities, 'messageCategory' => $this->messageCategory, 'generateModelClass' => $this->extendedModels, 'baseClassSuffix' => $this->modelBaseClassSuffix, 'modelClass' => isset($this->tableNameMap[$table]) ? $this->tableNameMap[$table] : Inflector::camelize($table), 'baseClass' => $this->modelBaseClass, 'baseTraits' => $this->modelBaseTraits, 'removeDuplicateRelations' => $this->modelRemoveDuplicateRelations, 'tableNameMap' => $this->tableNameMap, 'generateQuery' => $this->modelGenerateQuery, 'queryNs' => $this->modelQueryNamespace, 'queryBaseClass' => $this->modelQueryBaseClass, 'generateLabelsFromComments' => $this->modelGenerateLabelsFromComments, 'generateHintsFromComments' => $this->modelGenerateHintsFromComments];
         $route = 'gii/giiant-model';
         $app = \Yii::$app;
         $temp = new \yii\console\Application($this->appConfig);
         $temp->runAction(ltrim($route, '/'), $params);
         unset($temp);
         \Yii::$app = $app;
         \Yii::$app->log->logger->flush(true);
     }
 }
Example #27
0
 private function getSanitizedId()
 {
     return Inflector::camelize($this->options['id']);
 }
 /**
  * Returns the foreign key name of the Location model for city_id. You can 
  * override this method in order to provide a custom foreign key name.
  * 
  * @return string
  */
 protected function getForeignKeyLocCity()
 {
     return 'FK_' . Inflector::camelize($this->getLocationTableName()) . '_CityId';
 }
Example #29
0
         }
     }
 } else {
     foreach ($tableSchema->columns as $column) {
         $format = $generator->generateColumnFormat($column);
         if (++$count < 6) {
             $pos = strpos($column->name, 'password');
             /* 
              * Remove Prefix Tabel 
              * tbl_ ref_ tb_		 
              */
             $names = explode('_', $column->name);
             if (count($names > 0) and in_array($names[0], ['tbl', 'tb', 'ref'])) {
                 $new_name = substr($column->name, strlen($names[0]), strlen($column->name));
                 $new_name = substr($new_name, 0, strlen($new_name) - 3);
                 $new_name = \yii\helpers\Inflector::camelize($new_name);
                 $new_name = lcfirst($new_name);
                 echo "            /*\n\t\t\t\t[\n\t\t\t\t\t'attribute' => '" . $column->name . "',\n\t\t\t\t\t'value' => function (\$data) {\n\t\t\t\t\t\treturn \$data->" . $new_name . "->name;\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\t*/\n";
             } else {
                 if ($pos !== false) {
                     echo "            // '" . $column->name . "',\n";
                     $count = $count - 1;
                 } else {
                     if ($column->name == 'id') {
                         echo "            // '" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
                         $count = $count - 1;
                     } else {
                         if (in_array($column->name, ['created', 'created_by', 'modified', 'modified_by'])) {
                             echo "            // '" . $column->name . ($format === 'text' ? "" : ":" . $format) . "',\n";
                             $count = $count - 1;
                         } else {
Example #30
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}'");
 }