diff --git a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php index 89f7e59869..d898f540cb 100644 --- a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php +++ b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php @@ -87,10 +87,53 @@ EOF $files = Finder::create()->files()->in($dir)->name('*.twig'); } + $error = false; foreach ($files as $file) { - $twig->parse($twig->tokenize(file_get_contents($file), (string) $file)); + try { + $twig->parse($twig->tokenize(file_get_contents($file), (string) $file)); + $output->writeln(sprintf("OK in %s", $file)); + } catch (\Twig_Error $e) { + $this->renderException($output, $file, $e); + $error = true; + } } - $output->writeln('No syntax error detected.'); + return $error ? 1 : 0; + } + + protected function renderException(OutputInterface $output, $file, \Twig_Error $exception) + { + $line = $exception->getTemplateLine(); + $lines = $this->getContext($file, $line); + + $output->writeln(sprintf("KO in %s (line %s)", $file, $line)); + foreach ($lines as $no => $code) { + $output->writeln(sprintf( + "%s %-6s %s", + $no == $line ? '>>' : ' ', + $no, + $code + )); + if ($no == $line) { + $output->writeln(sprintf('>> %s ', $exception->getRawMessage())); + } + } + } + + protected function getContext($file, $line, $context = 3) + { + $fileContent = file_get_contents($file); + $lines = explode("\n", $fileContent); + + $position = max(0, $line - $context); + $max = min(count($lines), $line - 1 + $context); + + $result = array(); + while ($position < $max) { + $result[$position + 1] = $lines[$position]; + $position++; + } + + return $result; } }