PageRenderTime 45ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Bridge/Twig/Command/LintCommand.php

http://github.com/fabpot/symfony
PHP | 268 lines | 203 code | 49 blank | 16 comment | 20 complexity | a769cf86800fd1c27e905f338050ee6a MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\Command;
  11. use Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\Console\Exception\InvalidArgumentException;
  13. use Symfony\Component\Console\Exception\RuntimeException;
  14. use Symfony\Component\Console\Input\InputArgument;
  15. use Symfony\Component\Console\Input\InputInterface;
  16. use Symfony\Component\Console\Input\InputOption;
  17. use Symfony\Component\Console\Output\OutputInterface;
  18. use Symfony\Component\Console\Style\SymfonyStyle;
  19. use Symfony\Component\Finder\Finder;
  20. use Twig\Environment;
  21. use Twig\Error\Error;
  22. use Twig\Loader\ArrayLoader;
  23. use Twig\Loader\FilesystemLoader;
  24. use Twig\Source;
  25. /**
  26. * Command that will validate your template syntax and output encountered errors.
  27. *
  28. * @author Marc Weistroff <marc.weistroff@sensiolabs.com>
  29. * @author Jérôme Tamarelle <jerome@tamarelle.net>
  30. */
  31. class LintCommand extends Command
  32. {
  33. protected static $defaultName = 'lint:twig';
  34. private $twig;
  35. public function __construct(Environment $twig)
  36. {
  37. parent::__construct();
  38. $this->twig = $twig;
  39. }
  40. protected function configure()
  41. {
  42. $this
  43. ->setDescription('Lints a template and outputs encountered errors')
  44. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
  45. ->addOption('show-deprecations', null, InputOption::VALUE_NONE, 'Show deprecations as errors')
  46. ->addArgument('filename', InputArgument::IS_ARRAY, 'A file, a directory or "-" for reading from STDIN')
  47. ->setHelp(<<<'EOF'
  48. The <info>%command.name%</info> command lints a template and outputs to STDOUT
  49. the first encountered syntax error.
  50. You can validate the syntax of contents passed from STDIN:
  51. <info>cat filename | php %command.full_name% -</info>
  52. Or the syntax of a file:
  53. <info>php %command.full_name% filename</info>
  54. Or of a whole directory:
  55. <info>php %command.full_name% dirname</info>
  56. <info>php %command.full_name% dirname --format=json</info>
  57. EOF
  58. )
  59. ;
  60. }
  61. protected function execute(InputInterface $input, OutputInterface $output)
  62. {
  63. $io = new SymfonyStyle($input, $output);
  64. $filenames = $input->getArgument('filename');
  65. $showDeprecations = $input->getOption('show-deprecations');
  66. if (['-'] === $filenames) {
  67. return $this->display($input, $output, $io, [$this->validate(file_get_contents('php://stdin'), uniqid('sf_', true))]);
  68. }
  69. if (!$filenames) {
  70. $loader = $this->twig->getLoader();
  71. if ($loader instanceof FilesystemLoader) {
  72. $paths = [];
  73. foreach ($loader->getNamespaces() as $namespace) {
  74. $paths[] = $loader->getPaths($namespace);
  75. }
  76. $filenames = array_merge(...$paths);
  77. }
  78. if (!$filenames) {
  79. throw new RuntimeException('Please provide a filename or pipe template content to STDIN.');
  80. }
  81. }
  82. if ($showDeprecations) {
  83. $prevErrorHandler = set_error_handler(static function ($level, $message, $file, $line) use (&$prevErrorHandler) {
  84. if (E_USER_DEPRECATED === $level) {
  85. $templateLine = 0;
  86. if (preg_match('/ at line (\d+)[ .]/', $message, $matches)) {
  87. $templateLine = $matches[1];
  88. }
  89. throw new Error($message, $templateLine);
  90. }
  91. return $prevErrorHandler ? $prevErrorHandler($level, $message, $file, $line) : false;
  92. });
  93. }
  94. try {
  95. $filesInfo = $this->getFilesInfo($filenames);
  96. } finally {
  97. if ($showDeprecations) {
  98. restore_error_handler();
  99. }
  100. }
  101. return $this->display($input, $output, $io, $filesInfo);
  102. }
  103. private function getFilesInfo(array $filenames): array
  104. {
  105. $filesInfo = [];
  106. foreach ($filenames as $filename) {
  107. foreach ($this->findFiles($filename) as $file) {
  108. $filesInfo[] = $this->validate(file_get_contents($file), $file);
  109. }
  110. }
  111. return $filesInfo;
  112. }
  113. protected function findFiles(string $filename)
  114. {
  115. if (is_file($filename)) {
  116. return [$filename];
  117. } elseif (is_dir($filename)) {
  118. return Finder::create()->files()->in($filename)->name('*.twig');
  119. }
  120. throw new RuntimeException(sprintf('File or directory "%s" is not readable.', $filename));
  121. }
  122. private function validate(string $template, string $file): array
  123. {
  124. $realLoader = $this->twig->getLoader();
  125. try {
  126. $temporaryLoader = new ArrayLoader([$file => $template]);
  127. $this->twig->setLoader($temporaryLoader);
  128. $nodeTree = $this->twig->parse($this->twig->tokenize(new Source($template, $file)));
  129. $this->twig->compile($nodeTree);
  130. $this->twig->setLoader($realLoader);
  131. } catch (Error $e) {
  132. $this->twig->setLoader($realLoader);
  133. return ['template' => $template, 'file' => $file, 'line' => $e->getTemplateLine(), 'valid' => false, 'exception' => $e];
  134. }
  135. return ['template' => $template, 'file' => $file, 'valid' => true];
  136. }
  137. private function display(InputInterface $input, OutputInterface $output, SymfonyStyle $io, array $files)
  138. {
  139. switch ($input->getOption('format')) {
  140. case 'txt':
  141. return $this->displayTxt($output, $io, $files);
  142. case 'json':
  143. return $this->displayJson($output, $files);
  144. default:
  145. throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $input->getOption('format')));
  146. }
  147. }
  148. private function displayTxt(OutputInterface $output, SymfonyStyle $io, array $filesInfo)
  149. {
  150. $errors = 0;
  151. foreach ($filesInfo as $info) {
  152. if ($info['valid'] && $output->isVerbose()) {
  153. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  154. } elseif (!$info['valid']) {
  155. ++$errors;
  156. $this->renderException($io, $info['template'], $info['exception'], $info['file']);
  157. }
  158. }
  159. if (0 === $errors) {
  160. $io->success(sprintf('All %d Twig files contain valid syntax.', \count($filesInfo)));
  161. } else {
  162. $io->warning(sprintf('%d Twig files have valid syntax and %d contain errors.', \count($filesInfo) - $errors, $errors));
  163. }
  164. return min($errors, 1);
  165. }
  166. private function displayJson(OutputInterface $output, array $filesInfo)
  167. {
  168. $errors = 0;
  169. array_walk($filesInfo, function (&$v) use (&$errors) {
  170. $v['file'] = (string) $v['file'];
  171. unset($v['template']);
  172. if (!$v['valid']) {
  173. $v['message'] = $v['exception']->getMessage();
  174. unset($v['exception']);
  175. ++$errors;
  176. }
  177. });
  178. $output->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  179. return min($errors, 1);
  180. }
  181. private function renderException(OutputInterface $output, string $template, Error $exception, string $file = null)
  182. {
  183. $line = $exception->getTemplateLine();
  184. if ($file) {
  185. $output->text(sprintf('<error> ERROR </error> in %s (line %s)', $file, $line));
  186. } else {
  187. $output->text(sprintf('<error> ERROR </error> (line %s)', $line));
  188. }
  189. // If the line is not known (this might happen for deprecations if we fail at detecting the line for instance),
  190. // we render the message without context, to ensure the message is displayed.
  191. if ($line <= 0) {
  192. $output->text(sprintf('<error> >> %s</error> ', $exception->getRawMessage()));
  193. return;
  194. }
  195. foreach ($this->getContext($template, $line) as $lineNumber => $code) {
  196. $output->text(sprintf(
  197. '%s %-6s %s',
  198. $lineNumber === $line ? '<error> >> </error>' : ' ',
  199. $lineNumber,
  200. $code
  201. ));
  202. if ($lineNumber === $line) {
  203. $output->text(sprintf('<error> >> %s</error> ', $exception->getRawMessage()));
  204. }
  205. }
  206. }
  207. private function getContext(string $template, int $line, int $context = 3)
  208. {
  209. $lines = explode("\n", $template);
  210. $position = max(0, $line - $context);
  211. $max = min(\count($lines), $line - 1 + $context);
  212. $result = [];
  213. while ($position < $max) {
  214. $result[$position + 1] = $lines[$position];
  215. ++$position;
  216. }
  217. return $result;
  218. }
  219. }