@@ -70,7 +70,7 @@ protected function execute(InputInterface $input, OutputInterface $output)
7070 $ template .= fread (STDIN , 1024 );
7171 }
7272
73- return $ twig -> parse ($ twig-> tokenize ( $ template) );
73+ return $ this -> validateTemplate ($ twig, $ output , $ template );
7474 }
7575
7676 if (0 !== strpos ($ filename , '@ ' ) && !is_readable ($ filename )) {
@@ -87,26 +87,39 @@ protected function execute(InputInterface $input, OutputInterface $output)
8787 $ files = Finder::create ()->files ()->in ($ dir )->name ('*.twig ' );
8888 }
8989
90- $ error = false ;
90+ $ errors = 0 ;
9191 foreach ($ files as $ file ) {
92- try {
93- $ twig ->parse ($ twig ->tokenize (file_get_contents ($ file ), (string ) $ file ));
94- $ output ->writeln (sprintf ("<info>OK</info> in %s " , $ file ));
95- } catch (\Twig_Error $ e ) {
96- $ this ->renderException ($ output , $ file , $ e );
97- $ error = true ;
98- }
92+ $ errors += $ this ->validateTemplate ($ twig , $ output , file_get_contents ($ file ), $ file );
93+ }
94+
95+ return $ errors > 0 ? 1 : 0 ;
96+ }
97+
98+ protected function validateTemplate (\Twig_Environment $ twig , OutputInterface $ output , $ template , $ file = null )
99+ {
100+ try {
101+ $ twig ->parse ($ twig ->tokenize ($ template , $ file ? (string ) $ file : null ));
102+ $ output ->writeln ('<info>OK</info> ' .($ file ? sprintf (' in %s ' , $ file ) : '' ));
103+ } catch (\Twig_Error $ e ) {
104+ $ this ->renderException ($ output , $ template , $ e , $ file );
105+
106+ return 1 ;
99107 }
100108
101- return $ error ? 1 : 0 ;
109+ return 0 ;
102110 }
103111
104- protected function renderException (OutputInterface $ output , $ file , \Twig_Error $ exception )
112+ protected function renderException (OutputInterface $ output , $ template , \Twig_Error $ exception, $ file = null )
105113 {
106114 $ line = $ exception ->getTemplateLine ();
107- $ lines = $ this ->getContext ($ file , $ line );
115+ $ lines = $ this ->getContext ($ template , $ line );
116+
117+ if ($ file ) {
118+ $ output ->writeln (sprintf ("<error>KO</error> in %s (line %s) " , $ file , $ line ));
119+ } else {
120+ $ output ->writeln (sprintf ("<error>KO</error> (line %s) " , $ line ));
121+ }
108122
109- $ output ->writeln (sprintf ("<error>KO</error> in %s (line %s) " , $ file , $ line ));
110123 foreach ($ lines as $ no => $ code ) {
111124 $ output ->writeln (sprintf (
112125 "%s %-6s %s " ,
@@ -120,10 +133,9 @@ protected function renderException(OutputInterface $output, $file, \Twig_Error $
120133 }
121134 }
122135
123- protected function getContext ($ file , $ line , $ context = 3 )
136+ protected function getContext ($ template , $ line , $ context = 3 )
124137 {
125- $ fileContent = file_get_contents ($ file );
126- $ lines = explode ("\n" , $ fileContent );
138+ $ lines = explode ("\n" , $ template );
127139
128140 $ position = max (0 , $ line - $ context );
129141 $ max = min (count ($ lines ), $ line - 1 + $ context );
0 commit comments