setName('template:render') ->setDescription('Render template content') ->setHelp('This command allows you to render the content of a template') ->addOption('name', null, InputOption::VALUE_REQUIRED, 'Template name') ->addOption('filename', null, InputOption::VALUE_OPTIONAL, 'Template output file') ->addOption( 'parameter', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Array with template parameters. e.g., --parameter=key1:value1 --parameter=key2:value2' ) ->addOption( 'dump', 'd', InputOption::VALUE_NONE, 'Dump template content' ) ->addOption('engine', null, InputOption::VALUE_OPTIONAL, 'Render engine. e.g. twig|dwoo', 'twig') ; } /** * @param InputInterface $input * @param OutputInterface $output */ protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getOption('name'); if (is_null($name)) { $output->writeln('Name option is required'); return; } $parameters = $this->getParameters($input, $output); try { /* @var $templateService TemplateService */ $templateService = $this->getContainer()->get('template.template_service'); $filename = $templateService->renderTemplate($name, $parameters, $input->getOption('filename'), $input->getOption('engine')); if (!is_null($filename)) { $output->writeln("Template successfully generated! File: {$filename}"); if ($input->getOption('dump')) { $output->writeln(file_get_contents($filename)); } } else { $output->writeln('Template not found'); } } catch (\Exception $ex) { $output->writeln(sprintf('%s', $ex->getMessage())); } } /** * @param InputInterface $input * @param OutputInterface $output * * @return array */ public function getParameters(InputInterface $input, OutputInterface $output) { $parameters = array(); $inputParameters = $input->getOption('parameter'); if (empty($inputParameters)) { $output->writeln('Enter the template parameters:'); $output->writeln('Enter the name and value of parameter. e.g., \'name1:value1\'. Press Enter to finish'); while ($param = fgets(STDIN)) { if ($param === PHP_EOL) { break; } $inputParameters[] = $param; $output->writeln('Enter the name and value of parameter. e.g., \'name1:value1\'. Press Enter to finish'); } } foreach ($inputParameters as $param) { $pieces = explode(':', $param, 2); if (isset($pieces[0]) && isset($pieces[1])) { $parameters[trim($pieces[0])] = trim($pieces[1]); } } return $parameters; } }