Take template and create the tool

@throws \Exception
433986
protected function generateTool()
    {

        $this->data = $this->getMappedArguments();
        $generatorPath = str_replace(DIRECTORY_SEPARATOR, '/', dirname(__DIR__)) . '/studentToolGenerator';
        $targetPath    = $generatorPath . '/generated-code/' . $this->data['client'] . '/' . $this->data['tool-id'];
        $templatePath  = $generatorPath . '/template';

        $objects = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($templatePath), \RecursiveIteratorIterator::SELF_FIRST);

        $patterns = $this -> getPatterns();
        $replacements = $this -> getReplacements();

        foreach($objects as $tplFile => $cursor){
            if(in_array(basename($tplFile), array('.', '..'))) {
                continue;
            }

            $toolFile = str_replace($templatePath, $targetPath, $tplFile);

            if($cursor->isDir() && !is_dir($toolFile)) {
                mkdir($toolFile, 0755, true);
            }
            else if($cursor->isFile()){
                $toolFile = dirname($toolFile) . '/' . str_replace('template', $this->data['tool-base'], basename($toolFile));
                $toolContent = str_replace($patterns, $replacements, file_get_contents($tplFile));
                file_put_contents($toolFile, $toolContent);
            }
        }
        return $targetPath;
    }
1296622
public function create() {
        $migration = $this->getMessages();
        if (!$migration) {
            $this->db()->insert($this->table, array('migration' => get_class($this), 'state' => false));
        } else {
            throw new \Exception('Migration ' .  get_class($this) . ' already created');
        }
    }
1182271
private void initTemplates() throws Exception {
        if (templates != null && templates.length > 0) {
            for (String template : templates) {
                Assert.hasText(template, "Can not read template in ["
                        + template
                        + "]. Check that templates is not empty.");
                createTemplate(client.getLowLevelClient(), classpathRoot, template, forceTemplate);
            }
        }
    }
618913
public function create() {
        switch($this->info[2]) {
            case IMAGETYPE_JPEG:
                $this->resource = imagecreatefromjpeg($this->file);
                break;
            case IMAGETYPE_GIF:
                $this->resource = imagecreatefromgif($this->file);
                break;
            case IMAGETYPE_PNG:
                $this->resource = imagecreatefrompng($this->file);
                break;
            default:
                throw new Exception('Image type is not supported');
                break;
        }
    }
124324
public function findTemplate($template)
    {
        $file = $this->basePath("app/Template/$template");
        if($this->findFile($file)) {
            return $file;
        }
        elseif($this->findFile($file.'.html')) {
            return $file.'.html';
        }
        elseif($this->findFile($file.'.php')) {
            return $file.'.php';
        }
        else {
            throw new Exception($file." Template file is missing.");
            exit;
        }
    }
1032791
public function run()
    {
        $this->_checkTemplateLanguage();

        $tpl = new Template("/templates/html/index_".$this->_indexname.".html");

        $tpl->set("template", $this->_template);
        $tpl->set("templates", $this->_templates);
        $tpl->set("bootstraptemplate", $this->_bootstrap_template);
        $tpl->set("bootstraptemplates", $this->_bootstrap_templates);
        $tpl->set("picktemplate", $this->_pick_template);
        $tpl->set("language", $this->_language);
        $tpl->set("languages", $this->_languages);
        $tpl->set("picklanguage", $this->_pick_language);
        $tpl->set("showCPUListExpanded", defined('PSI_SHOW_CPULIST_EXPANDED') ? (PSI_SHOW_CPULIST_EXPANDED ? 'true' : 'false') : 'true');
        $tpl->set("showCPUInfoExpanded", defined('PSI_SHOW_CPUINFO_EXPANDED') ? (PSI_SHOW_CPUINFO_EXPANDED ? 'true' : 'false') : 'false');
        $tpl->set("showNetworkInfosExpanded", defined('PSI_SHOW_NETWORK_INFOS_EXPANDED') ? (PSI_SHOW_NETWORK_INFOS_EXPANDED ? 'true' : 'false') : 'false');
        $tpl->set("showMemoryInfosExpanded", defined('PSI_SHOW_MEMORY_INFOS_EXPANDED') ? (PSI_SHOW_MEMORY_INFOS_EXPANDED ? 'true' : 'false') : 'false');
        $tpl->set("showNetworkActiveSpeed", defined('PSI_SHOW_NETWORK_ACTIVE_SPEED') ? (PSI_SHOW_NETWORK_ACTIVE_SPEED ? ((strtolower(PSI_SHOW_NETWORK_ACTIVE_SPEED) === 'bps') ? 'bps' :'true') : 'false') : 'false');
        $tpl->set("showCPULoadCompact", defined('PSI_LOAD_BAR') ? ((strtolower(PSI_LOAD_BAR) === 'compact') ? 'true' :'false') : 'false');
        $tpl->set("hideBootstrapLoader", defined('PSI_HIDE_BOOTSTRAP_LOADER') ? (PSI_HIDE_BOOTSTRAP_LOADER ? 'true' : 'false') : 'false');
        if (defined('PSI_BLOCKS')) {
            if (is_string(PSI_BLOCKS)) {
                if (preg_match(ARRAY_EXP, PSI_BLOCKS)) {
                    $blocks = eval(strtolower(PSI_BLOCKS));
                } else {
                    $blocks = array(strtolower(PSI_BLOCKS));
                }
                $blocklist = '';
                $validblocks = array('vitals','hardware','memory','filesystem','network','voltage','current','temperature','fans','power','other','ups');
                foreach ($blocks as $block) {
                    if (in_array($block, $validblocks)) {
                        if (empty($blocklist)) {
                            $blocklist = $block;
                        } else {
                            $blocklist .= ','.$block;
                        }
                    }
                }
                if (!empty($blocklist)) {
                    $tpl->set("blocks", $blocklist);
                }
            } elseif (PSI_BLOCKS) {
                $tpl->set("blocks", 'true');
            }
        } else {
            $tpl->set("blocks", 'true');
        }

        echo $tpl->fetch();
    }
1009281
public function render()
	{
		$this->_path = $this->getPath();

		if (! is_readable($this->_path)) {
			Request::setHttpHeader(Request::HEADER_404);
			$this->setFile(static::ERROR_404);
			$this->_path = $this->getPath();

			if (! is_readable($this->_path)) {
				throw new Exception("View file '" . $this->_path . "' doesn't exists");
			}
		}

		$template = self::getTemplateConfig();
		if (! is_array($template) or ! isset($template['type'])) {
			throw new Exception("A template and a template type are required to render the view");
		}

		$this->_type = $template['type'];

		if (isset($template['file'])) {
			$template = APP_PATH
				        . Agl::APP_TEMPLATE_DIR
				        . $template['file']
				        . Agl::PHP_EXT;

			require($template);
		} else {
			require($this->_path);
		}

		$buffer = ob_get_clean();

		Observer::dispatch(Observer::EVENT_VIEW_RENDER_BUFFER_BEFORE, array(
			'view'   => $this,
			'buffer' => &$buffer
		));

		return $this->_prepareRender($buffer);
	}
402313
protected function compile(): void
    {
        $metaModel = $this->factory->translateIdToMetaModelName($this->metamodel);

        try {
            $this->Template->editor = $this->editor->editFor($metaModel, 'create');
        } catch (NotEditableException $exception) {
            throw new AccessDeniedException($exception->getMessage());
        } catch (NotCreatableException $exception) {
            throw new AccessDeniedException($exception->getMessage());
        }
    }
397161
public function createAction()
    {
        if ($this->enableScreens) {
            $edit = false;
            $org  = $this->getRespondent()->getOrganization();
            if (! $org) {
                $org = $this->currentOrganization;
            }

            if ($org) {
                $edit = $org->getRespondentEditScreen();
            }

            if (! $edit) {
                $group = $this->currentUser->getGroup();
                if ($group) {
                    $edit = $group->getRespondentEditScreen();
                }
            }

            if ($edit ) {
                if ($edit instanceof ProcessModelInterface) {
                    $edit->processModel($this->getModel());
                }

                // All are arrays, so easy to set
                $this->createParameters = $edit->getCreateParameters() + $this->createParameters;
                $editSnippets = $edit->getSnippets();
                if (false !== $editSnippets) {
                    $this->createEditSnippets = $editSnippets;
                }
            }
        }

        parent::createAction();
    }
158493
public function create()
    {
        try {
            $schema = explode(';', str_replace(PHP_EOL, '', $this->getSchema()));
            array_pop($schema);

            # db structure
            $sql = array_shift($schema);
            $this->db->query($sql . ';');

            # indecies
            foreach($schema as $sql) {
                $this->db->query($sql . ';');
            }
        } catch(Exception $e) {
            throw new Exception($e->getMessage(), 1);
        }
    }
563139
def new(template, target=None, name=None):
    
    if template not in TEMPLATES:
        raise ValueError("Template argument must be one of the followings: {}"
                         .format(", ".join(TEMPLATES)))
    if target is not None and target not in TARGETS.keys():
        raise ValueError("Target argument must be one of the followings: {}"
                         .format(TARGETS.keys()))
    name = name or template
    if NAME_REGEX.match(name) is None:
        raise ValueError("Invalid {} name".format(template))
    with open("{}.py".format(name), 'w') as f:
        target_imp = "" if target is None else "from {} import {}\n" \
                                               .format(*target.split('.'))
        main = MAIN.format(base=TARGETS.get(target) or "")
        if template == "script":
            f.write(SHEBANG + IMPORTS.format(target=target_imp) + "\n\n" + main)
        elif template == "tool":
            f.write(SHEBANG + TOOL_METADATA + TOOL_SECTIONS \
                    .format(imports=IMPORTS.format(target=target_imp)) + main)
235190
public function Start()
    {
        if(!$this->definitions_path)
        {
            throw new \Exception(
                t("Your are trying to export definitions without setting a path first.")
            );
        }
        elseif(!file_exists($this->definitions_path))
        {
            FileSystem::MakeDir(
                $this->definitions_path, 
                0755, 
                true
            );
        }
        
        $this->definitions_path = rtrim($this->definitions_path, "\\/") . "/";
        
        $this->SendMessage(
            sprintf(
                t("Starting export of definitions to %s format."),
                $this->export_type
            )
        );
        
        if($this->export_type == Type::JSON)
        {
            $this->SaveToJSON($this->definitions_path);
        }
        else
        {
            $this->SaveToPHP($this->definitions_path);
        }
        
        $this->SendMessage(t("Export completed."));
    }
1349173
public function getTemplate()
    {
        if (is_null($this->_template)) {
            Template::appendPath(dirname(__FILE__).'/Views');
            $temp = new Template();
            $this->_template = $temp->initialize();
        }
        return $this->_template;
    }
543647
public function execute()
    {
        if (!file_exists($this->location)) {
            mkdir($this->location);
        }
        if (!is_writable($this->location)) {
            throw new \Exception(sprintf('The location %s is not writable or does not exist.', $this->location));
        }

        $pdepend = $this->phpci->findBinary('pdepend');

        $cmd = $pdepend . ' --summary-xml="%s" --jdepend-chart="%s" --overview-pyramid="%s" %s "%s"';

        $this->removeBuildArtifacts();

        // If we need to ignore directories
        if (count($this->phpci->ignore)) {
            $ignore = ' --ignore=' . implode(',', $this->phpci->ignore);
        } else {
            $ignore = '';
        }

        $success = $this->phpci->executeCommand(
            $cmd,
            $this->location . DIRECTORY_SEPARATOR . $this->summary,
            $this->location . DIRECTORY_SEPARATOR . $this->chart,
            $this->location . DIRECTORY_SEPARATOR . $this->pyramid,
            $ignore,
            $this->directory
        );

        $config = $this->phpci->getSystemConfig('phpci');

        if ($success) {
            $this->phpci->logSuccess(
                sprintf(
                    "Pdepend successful. You can use %s\n, ![Chart](%s \"Pdepend Chart\")\n
                    and ![Pyramid](%s \"Pdepend Pyramid\")\n
                    for inclusion in the readme.md file",
                    $config['url'] . '/build/pdepend/' . $this->summary,
                    $config['url'] . '/build/pdepend/' . $this->chart,
                    $config['url'] . '/build/pdepend/' . $this->pyramid
                )
            );
        }

        return $success;
    }
304910
public function renderToolTemplatesModalEditHandlerAction()
    {
        $melisKey = $this->params()->fromRoute('melisKey', '');

        // declare the Tool service that we will be using to completely create our tool.
        $melisTool = $this->getServiceLocator()->get('MelisCoreTool');

        // tell the Tool what configuration in the app.tool.php that will be used.
        $melisTool->setMelisToolKey('meliscms', 'meliscms_tool_templates');

        $view = new ViewModel();
        $view->editModalHandler = $melisTool->getModal('meliscms_tool_template_edit_modal');
        $view->melisKey = $melisKey;

        return $view;
    }
679910
public function getToolTemplateDataAction()
    {
        // get the service for Templates Model & Table
        $templatesModel = $this->getServiceLocator()->get('MelisEngineTableTemplate');

        // declare the Tool service that we will be using to completely create our tool.
        $melisTool = $this->getServiceLocator()->get('MelisCoreTool');

        // tell the Tool what configuration in the app.tool.php that will be used.
        $melisTool->setMelisToolKey('meliscms', 'meliscms_tool_templates');

        // Site Table
        $tableSite = $this->getServiceLocator()->get('MelisEngineTableSite');


        $colId = array();
        $dataCount = 0;
        $draw = 0;
        $tableData = array();

        // make sure that the request is an AJAX call
        if($this->getRequest()->isPost()) {

            $siteId = $this->getRequest()->getPost('tpl_site_id');
            $siteId = !empty($siteId)? $siteId : null;

            $colId = array_keys($melisTool->getColumns());

            $sortOrder = $this->getRequest()->getPost('order');
            $sortOrder = $sortOrder[0]['dir'];

            $selCol = $this->getRequest()->getPost('order');
            $selCol = $colId[$selCol[0]['column']];

            $draw = $this->getRequest()->getPost('draw');

            $start = $this->getRequest()->getPost('start');
            $length =  $this->getRequest()->getPost('length');

            $search = $this->getRequest()->getPost('search');
            $search = $search['value'];

            $dataCount = $templatesModel->getTotalData();

            $getData = $templatesModel->getData($search, $siteId, $melisTool->getSearchableColumns(), $selCol, $sortOrder, $start, $length);
            $tableData = $getData->toArray();

            for($ctr = 0; $ctr < count($tableData); $ctr++)
            {
                // apply text limits
                foreach($tableData[$ctr] as $vKey => $vValue)
                {
                    $tableData[$ctr][$vKey] = $melisTool->limitedText($vValue);
                }

                $tableData[$ctr]['DT_RowId'] = $tableData[$ctr]['tpl_id'];

                // Append Template status: Green Circle = Active || Red Circle = Inctive
                try {
                    $tpl = [
                        'module'        => $tableData[$ctr]['tpl_zf2_website_folder'],
                        'controller'    => $tableData[$ctr]['tpl_zf2_controller'],
                        'action'        => $tableData[$ctr]['tpl_zf2_action']
                    ];
                    $tpl_status                     = $this->getTemplateStatus($tpl);
                    $tableData[$ctr]['tpl_status']  = '<span class="text-'.($tpl_status? 'success' : 'danger').'"><i class="fa fa-fw fa-circle"></i></span>';
                } catch (\Exception $e) {
                    // Place handling here
                }

                // display controller and action in Controller Column
                $tableData[$ctr]['tpl_zf2_controller'] = !empty($tableData[$ctr]['tpl_zf2_action']) ? $tableData[$ctr]['tpl_zf2_controller'] . '/' . $tableData[$ctr]['tpl_zf2_action'] : $tableData[$ctr]['tpl_zf2_controller'];
            }
        }

        return new JsonModel(array(
            'draw' => (int) $draw,
            'recordsTotal' => $dataCount,
            'recordsFiltered' => $templatesModel->getTotalFiltered(),
            'data' => $tableData,
        ));
    }
403603
def generate
      template = Template.new
      template.add('timestamp', Time.now.to_s)
      template.add('lib_dir', @lib_dir)
      template.add('bin_dir', @bin_dir)
      template.parse(TEMPLATE)
    end