writeFile() public static method

Basic helper method to write files with exception capture. The fileName will auto wrapped trough the Yii::getAlias function.
public static writeFile ( string $fileName, string $content ) : boolean
$fileName string The path to the file with file name
$content string The content to store in this File
return boolean
Ejemplo n.º 1
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->renderWindowClassView($className, $module->getNamespace() . '\\aws', $moduleId);
     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}'.");
 }
Ejemplo n.º 2
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}'.");
 }
Ejemplo n.º 3
0
 /**
  * Wizzard to create a new CMS block.
  *
  * @return number
  */
 public function actionCreate()
 {
     if (empty($this->type)) {
         Console::clearScreenBeforeCursor();
         $this->type = $this->select('Do you want to create an app or module Block?', [self::TYPE_APP => 'Creates a project block inside your @app Namespace (casual).', self::TYPE_MODULE => 'Creating a block inside a later specified Module.']);
     }
     if ($this->type == self::TYPE_MODULE && count($this->getModuleProposal()) === 0) {
         return $this->outputError('Your project does not have Project-Modules registered!');
     }
     if (empty($this->moduleName) && $this->type == self::TYPE_MODULE) {
         $this->moduleName = $this->select('Choose a module to create the block inside:', $this->getModuleProposal());
     }
     if (empty($this->blockName)) {
         $this->blockName = $this->prompt('Insert a name for your Block (e.g. HeadTeaser):', ['required' => true]);
     }
     if ($this->isContainer === null) {
         $this->isContainer = $this->confirm("Do you want to add placeholders to your block that serve as a container for nested blocks?", false);
     }
     if ($this->cacheEnabled === null) {
         $this->cacheEnabled = $this->confirm("Do you want to enable the caching for this block or not?", true);
     }
     if ($this->config === null) {
         $this->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'] . '}}';
                 $this->viewFileDoc[] = '$this->varValue(\'' . $item['var'] . '\');';
                 $this->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'] . '}}';
                 $this->viewFileDoc[] = '$this->cfgValue(\'' . $item['var'] . '\');';
                 $this->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'] . '}}';
                 $this->viewFileDoc[] = '$this->placeholderValue(\'' . $item['var'] . '\');';
                 $this->config['placeholders'][] = $item;
                 $doPlaceholders = $this->confirm('Add one more?', false);
                 ++$i;
             }
         }
     }
     $folder = $this->getFileBasePath() . DIRECTORY_SEPARATOR . 'blocks';
     $filePath = $folder . DIRECTORY_SEPARATOR . $this->blockName . '.php';
     sort($this->phpdoc);
     $content = $this->view->render('@luya/console/commands/views/block/create_block.php', ['namespace' => $this->getFileNamespace(), 'className' => $this->blockName, 'name' => Inflector::camel2words($this->blockName), 'type' => $this->type, 'module' => $this->moduleName, 'isContainer' => $this->isContainer, 'cacheEnabled' => $this->cacheEnabled, 'config' => $this->config, 'phpdoc' => $this->phpdoc, 'extras' => $this->extras, 'luyaText' => $this->getGeneratorText('block/create')]);
     if ($this->dryRun) {
         return $content;
     }
     if (FileHelper::createDirectory($folder) && FileHelper::writeFile($filePath, $content)) {
         // generate view file based on block object view context
         $object = Yii::createObject(['class' => $this->getFileNamespace() . '\\' . $this->blockName]);
         $viewsFolder = Yii::getAlias($object->getViewPath());
         $viewFilePath = $viewsFolder . DIRECTORY_SEPARATOR . $object->getViewFileName('php');
         if (FileHelper::createDirectory($viewsFolder) && FileHelper::writeFile($viewFilePath, $this->generateViewFile($this->blockName))) {
             $this->outputInfo('View file for the block has been created: ' . $viewFilePath);
         }
         return $this->outputSuccess("Block {$this->blockName} has been created: " . $filePath);
     }
     return $this->outputError("Error while creating block '{$filePath}'");
 }
Ejemplo n.º 4
0
 /**
  * Prepare a temp file to
  * @todo added very basic csv support, must be stored as class, just a temp solution
  * @return array
  */
 public function actionExport()
 {
     $tempData = null;
     // first row
     $header = [];
     $i = 0;
     foreach ($this->model->find()->all() as $key => $value) {
         $row = [];
         $attrs = $value->getAttributes();
         foreach ($value->extraFields() as $field) {
             $attrs[$field] = $value->{$field};
         }
         foreach ($attrs as $k => $v) {
             if (is_object($v)) {
                 if ($v instanceof Arrayable) {
                     $v = $v->toArray();
                 } else {
                     continue;
                 }
             }
             if ($i === 0) {
                 $header[] = $this->model->getAttributeLabel($k);
             }
             if (is_array($v)) {
                 $tv = [];
                 foreach ($v as $kk => $vv) {
                     if (is_object($vv)) {
                         if ($vv instanceof Arrayable) {
                             $tv[] = implode(" | ", $vv->toArray());
                         } else {
                             continue;
                         }
                     } elseif (is_array($vv)) {
                         $tv[] = implode(" | ", $vv);
                     } else {
                         $tv[] = $vv;
                     }
                 }
                 $v = implode(" - ", $tv);
             }
             $row[] = '"' . str_replace('"', '\\"', $v) . '"';
         }
         if ($i === 0) {
             $tempData .= implode(",", $header) . "\n";
         }
         $tempData .= implode(",", $row) . "\n";
         $i++;
     }
     $key = uniqid('ngre', true);
     $store = FileHelper::writeFile('@runtime/' . $key . '.tmp', $tempData);
     if ($store) {
         Yii::$app->session->set('tempNgRestFileName', Inflector::slug($this->model->tableName()));
         Yii::$app->session->set('tempNgRestKey', $key);
         return ['url' => Url::toRoute(['/admin/ngrest/export-download', 'key' => base64_encode($key)])];
     }
     throw new ErrorException("Unable to write the temporary file for the csv export. Make sure the runtime folder is writeable.");
 }
Ejemplo n.º 5
0
 /**
  * Create a new frontend/admin module.
  *
  * @return number
  */
 public function actionCreate()
 {
     Console::clearScreenBeforeCursor();
     $moduleName = $this->prompt("Enter the name of the module you like to generate:");
     $newName = preg_replace("/[^a-z]/", "", strtolower($moduleName));
     if ($newName !== $moduleName) {
         if (!$this->confirm("We have changed the name to '{$newName}'. Do you want to proceed with this name?")) {
             return $this->outputError('Abort by user.');
         } else {
             $moduleName = $newName;
         }
     }
     $appModulesFolder = Yii::$app->basePath . DIRECTORY_SEPARATOR . 'modules';
     $moduleFolder = $appModulesFolder . DIRECTORY_SEPARATOR . $moduleName;
     if (file_exists($moduleFolder)) {
         return $this->outputError("The folder " . $moduleFolder . " exists already.");
     }
     $folders = ['basePath' => $moduleFolder, 'adminPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'admin', 'adminPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'admin' . DIRECTORY_SEPARATOR . 'aws', 'frontendPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend', 'blocksPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'blocks', 'blocksPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'controllers', 'blocksPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'frontend' . DIRECTORY_SEPARATOR . 'views', 'modelsPath' => $moduleFolder . DIRECTORY_SEPARATOR . 'models'];
     $ns = 'app\\modules\\' . $moduleName;
     foreach ($folders as $folder) {
         FileHelper::createDirectory($folder);
     }
     $contents = [$moduleFolder . DIRECTORY_SEPARATOR . 'README.md' => $this->renderReadme($folders, $moduleName, $ns), $moduleFolder . DIRECTORY_SEPARATOR . 'admin/Module.php' => $this->renderAdmin($folders, $moduleName, $ns), $moduleFolder . DIRECTORY_SEPARATOR . 'frontend/Module.php' => $this->renderFrontend($folders, $moduleName, $ns)];
     foreach ($contents as $fileName => $content) {
         FileHelper::writeFile($fileName, $content);
     }
     return $this->outputSuccess("Module files has been created successfull. Check the README file to understand how to added the module to your config.");
 }
Ejemplo n.º 6
0
 /**
  * Create Ng-Rest-Model, Controller and Api for an existing Database-Table.
  *
  * @return number
  */
 public function actionCreate()
 {
     if ($this->moduleName === null) {
         Console::clearScreenBeforeCursor();
         $this->moduleName = $this->selectModule(['onlyAdmin' => true, 'hideCore' => true, 'text' => 'Select the Module where the CRUD files should be saved:']);
     }
     if ($this->modelName === null) {
         $modelSelection = true;
         while ($modelSelection) {
             $modelName = $this->prompt('Model Name (e.g. Album):', ['required' => true]);
             $camlizeModelName = Inflector::camelize($modelName);
             if ($modelName !== $camlizeModelName) {
                 if ($this->confirm("We have camlized the model name to '{$camlizeModelName}' do you want to continue with this name?")) {
                     $modelName = $camlizeModelName;
                     $modelSelection = false;
                 }
             } else {
                 $modelSelection = false;
             }
             $this->modelName = $modelName;
         }
     }
     if ($this->apiEndpoint === null) {
         $this->apiEndpoint = $this->prompt('Api Endpoint:', ['required' => true, 'default' => $this->getApiEndpointSuggestion()]);
     }
     if ($this->dbTableName === null) {
         $sqlSelection = true;
         while ($sqlSelection) {
             $sqlTable = $this->prompt('Database Table name for the Model:', ['required' => true, 'default' => $this->getDatabaseNameSuggestion()]);
             if ($sqlTable == '?') {
                 foreach ($this->getSqlTablesArray() as $table) {
                     $this->outputInfo("- " . $table);
                 }
             }
             if (isset($this->getSqlTablesArray()[$sqlTable])) {
                 $this->dbTableName = $sqlTable;
                 $sqlSelection = false;
             } else {
                 $this->outputError("The selected database '{$sqlTable}' does not exists in the list of tables. Type '?' to see all tables.");
             }
         }
     }
     if ($this->enableI18n === null) {
         $this->enableI18n = $this->confirm("Would you like to enable i18n field input for text fields? Only required for multilingual pages.");
     }
     $this->ensureBasePathAndNamespace();
     $files = [];
     // api content
     $files['api'] = ['path' => $this->getBasePath() . DIRECTORY_SEPARATOR . 'apis', 'fileName' => $this->getModelNameCamlized() . 'Controller.php', 'content' => $this->generateApiContent($this->getNamespace() . '\\apis', $this->getModelNameCamlized() . 'Controller', $this->getAbsoluteModelNamespace())];
     // controller
     $files['controller'] = ['path' => $this->getBasePath() . DIRECTORY_SEPARATOR . 'controllers', 'fileName' => $this->getModelNameCamlized() . 'Controller.php', 'content' => $this->generateControllerContent($this->getNamespace() . '\\controllers', $this->getModelNameCamlized() . 'Controller', $this->getAbsoluteModelNamespace())];
     // model
     $files['model'] = ['path' => $this->getModelBasePath() . DIRECTORY_SEPARATOR . 'models', 'fileName' => $this->getModelNameCamlized() . '.php', 'content' => $this->generateModelContent($this->getModelNamespace() . '\\models', $this->getModelNameCamlized(), $this->apiEndpoint, $this->getDbTableShema(), $this->enableI18n)];
     foreach ($files as $file) {
         FileHelper::createDirectory($file['path']);
         if (file_exists($file['path'] . DIRECTORY_SEPARATOR . $file['fileName'])) {
             if (!$this->confirm("The File '{$file['fileName']}' already exists, do you want to override the existing file?")) {
                 continue;
             }
         }
         if (FileHelper::writeFile($file['path'] . DIRECTORY_SEPARATOR . $file['fileName'], $file['content'])) {
             $this->outputSuccess("Wrote file '{$file['fileName']}'.");
         } else {
             $this->outputError("Error while writing file '{$file['fileName']}'.");
         }
     }
     return $this->outputSuccess($this->generateBuildSummery($this->apiEndpoint, $this->getNamespace() . '\\apis\\' . $this->getModelNameCamlized() . 'Controller', $this->getModelNameCamlized(), $this->getSummaryControllerRoute()));
 }