LintCommand.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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\Input\InputArgument;
  13. use Symfony\Component\Console\Input\InputInterface;
  14. use Symfony\Component\Console\Input\InputOption;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. use Symfony\Component\Console\Style\SymfonyStyle;
  17. use Symfony\Component\Finder\Finder;
  18. use Twig\Environment;
  19. use Twig\Error\Error;
  20. use Twig\Loader\ArrayLoader;
  21. use Twig\Source;
  22. /**
  23. * Command that will validate your template syntax and output encountered errors.
  24. *
  25. * @author Marc Weistroff <marc.weistroff@sensiolabs.com>
  26. * @author Jérôme Tamarelle <jerome@tamarelle.net>
  27. */
  28. class LintCommand extends Command
  29. {
  30. private $twig;
  31. /**
  32. * {@inheritdoc}
  33. */
  34. public function __construct($name = 'lint:twig')
  35. {
  36. parent::__construct($name);
  37. }
  38. public function setTwigEnvironment(Environment $twig)
  39. {
  40. $this->twig = $twig;
  41. }
  42. /**
  43. * @return Environment $twig
  44. */
  45. protected function getTwigEnvironment()
  46. {
  47. return $this->twig;
  48. }
  49. protected function configure()
  50. {
  51. $this
  52. ->setDescription('Lints a template and outputs encountered errors')
  53. ->addOption('format', null, InputOption::VALUE_REQUIRED, 'The output format', 'txt')
  54. ->addArgument('filename', InputArgument::IS_ARRAY)
  55. ->setHelp(<<<'EOF'
  56. The <info>%command.name%</info> command lints a template and outputs to STDOUT
  57. the first encountered syntax error.
  58. You can validate the syntax of contents passed from STDIN:
  59. <info>cat filename | php %command.full_name%</info>
  60. Or the syntax of a file:
  61. <info>php %command.full_name% filename</info>
  62. Or of a whole directory:
  63. <info>php %command.full_name% dirname</info>
  64. <info>php %command.full_name% dirname --format=json</info>
  65. EOF
  66. )
  67. ;
  68. }
  69. protected function execute(InputInterface $input, OutputInterface $output)
  70. {
  71. $io = new SymfonyStyle($input, $output);
  72. if (null === $twig = $this->getTwigEnvironment()) {
  73. throw new \RuntimeException('The Twig environment needs to be set.');
  74. }
  75. $filenames = $input->getArgument('filename');
  76. if (0 === count($filenames)) {
  77. if (0 !== ftell(STDIN)) {
  78. throw new \RuntimeException('Please provide a filename or pipe template content to STDIN.');
  79. }
  80. $template = '';
  81. while (!feof(STDIN)) {
  82. $template .= fread(STDIN, 1024);
  83. }
  84. return $this->display($input, $output, $io, array($this->validate($twig, $template, uniqid('sf_', true))));
  85. }
  86. $filesInfo = $this->getFilesInfo($twig, $filenames);
  87. return $this->display($input, $output, $io, $filesInfo);
  88. }
  89. private function getFilesInfo(Environment $twig, array $filenames)
  90. {
  91. $filesInfo = array();
  92. foreach ($filenames as $filename) {
  93. foreach ($this->findFiles($filename) as $file) {
  94. $filesInfo[] = $this->validate($twig, file_get_contents($file), $file);
  95. }
  96. }
  97. return $filesInfo;
  98. }
  99. protected function findFiles($filename)
  100. {
  101. if (is_file($filename)) {
  102. return array($filename);
  103. } elseif (is_dir($filename)) {
  104. return Finder::create()->files()->in($filename)->name('*.twig');
  105. }
  106. throw new \RuntimeException(sprintf('File or directory "%s" is not readable', $filename));
  107. }
  108. private function validate(Environment $twig, $template, $file)
  109. {
  110. $realLoader = $twig->getLoader();
  111. try {
  112. $temporaryLoader = new ArrayLoader(array((string) $file => $template));
  113. $twig->setLoader($temporaryLoader);
  114. $nodeTree = $twig->parse($twig->tokenize(new Source($template, (string) $file)));
  115. $twig->compile($nodeTree);
  116. $twig->setLoader($realLoader);
  117. } catch (Error $e) {
  118. $twig->setLoader($realLoader);
  119. return array('template' => $template, 'file' => $file, 'valid' => false, 'exception' => $e);
  120. }
  121. return array('template' => $template, 'file' => $file, 'valid' => true);
  122. }
  123. private function display(InputInterface $input, OutputInterface $output, SymfonyStyle $io, $files)
  124. {
  125. switch ($input->getOption('format')) {
  126. case 'txt':
  127. return $this->displayTxt($output, $io, $files);
  128. case 'json':
  129. return $this->displayJson($output, $files);
  130. default:
  131. throw new \InvalidArgumentException(sprintf('The format "%s" is not supported.', $input->getOption('format')));
  132. }
  133. }
  134. private function displayTxt(OutputInterface $output, SymfonyStyle $io, $filesInfo)
  135. {
  136. $errors = 0;
  137. foreach ($filesInfo as $info) {
  138. if ($info['valid'] && $output->isVerbose()) {
  139. $io->comment('<info>OK</info>'.($info['file'] ? sprintf(' in %s', $info['file']) : ''));
  140. } elseif (!$info['valid']) {
  141. ++$errors;
  142. $this->renderException($io, $info['template'], $info['exception'], $info['file']);
  143. }
  144. }
  145. if ($errors === 0) {
  146. $io->success(sprintf('All %d Twig files contain valid syntax.', count($filesInfo)));
  147. } else {
  148. $io->warning(sprintf('%d Twig files have valid syntax and %d contain errors.', count($filesInfo) - $errors, $errors));
  149. }
  150. return min($errors, 1);
  151. }
  152. private function displayJson(OutputInterface $output, $filesInfo)
  153. {
  154. $errors = 0;
  155. array_walk($filesInfo, function (&$v) use (&$errors) {
  156. $v['file'] = (string) $v['file'];
  157. unset($v['template']);
  158. if (!$v['valid']) {
  159. $v['message'] = $v['exception']->getMessage();
  160. unset($v['exception']);
  161. ++$errors;
  162. }
  163. });
  164. $output->writeln(json_encode($filesInfo, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  165. return min($errors, 1);
  166. }
  167. private function renderException(OutputInterface $output, $template, Error $exception, $file = null)
  168. {
  169. $line = $exception->getTemplateLine();
  170. if ($file) {
  171. $output->text(sprintf('<error> ERROR </error> in %s (line %s)', $file, $line));
  172. } else {
  173. $output->text(sprintf('<error> ERROR </error> (line %s)', $line));
  174. }
  175. foreach ($this->getContext($template, $line) as $lineNumber => $code) {
  176. $output->text(sprintf(
  177. '%s %-6s %s',
  178. $lineNumber === $line ? '<error> >> </error>' : ' ',
  179. $lineNumber,
  180. $code
  181. ));
  182. if ($lineNumber === $line) {
  183. $output->text(sprintf('<error> >> %s</error> ', $exception->getRawMessage()));
  184. }
  185. }
  186. }
  187. private function getContext($template, $line, $context = 3)
  188. {
  189. $lines = explode("\n", $template);
  190. $position = max(0, $line - $context);
  191. $max = min(count($lines), $line - 1 + $context);
  192. $result = array();
  193. while ($position < $max) {
  194. $result[$position + 1] = $lines[$position];
  195. ++$position;
  196. }
  197. return $result;
  198. }
  199. }