55use Gettext \Translations ;
66use Twig_Loader_String ;
77use Twig_Environment ;
8+ use Twig_Extensions_Extension_I18n ;
89
910/**
1011 * Class to get gettext strings from twig files returning arrays.
@@ -16,55 +17,31 @@ class Twig extends Extractor implements ExtractorInterface
1617 *
1718 * @var Twig_Environment
1819 */
19- protected static $ twig ;
20+ private static $ twig ;
2021
2122 /**
2223 * {@inheritdoc}
2324 */
2425 public static function fromString ($ string , Translations $ translations , array $ options = [])
2526 {
26- self ::addExtension ('Twig_Extensions_Extension_I18n ' );
27-
28- $ string = self ::$ twig ->compileSource ($ string );
27+ $ string = self ::getTwig ()->compileSource ($ string );
2928
3029 PhpCode::fromString ($ string , $ translations , $ options );
3130 }
3231
3332 /**
34- * Initialise Twig if it isn't already, and add a given Twig extension.
35- * This must be called before calling fromString().
36- *
37- * @param mixed $extension Already initialised extension to add
38- */
39- public static function addExtension ($ extension )
40- {
41- // initialise twig
42- if (!isset (self ::$ twig )) {
43- $ twigCompiler = new Twig_Loader_String ();
44-
45- self ::$ twig = new Twig_Environment ($ twigCompiler );
46- }
47-
48- if (!self ::checkHasExtensionByClassName ($ extension )) {
49- self ::$ twig ->addExtension (new $ extension ());
50- }
51- }
52-
53- /**
54- * Checks if a given Twig extension is already registered or not.
55- *
56- * @param string Name of Twig extension to check
33+ * Returns a Twig instance.
5734 *
58- * @return bool Whether it has been registered already or not
35+ * @return Twig_Environment
5936 */
60- protected static function checkHasExtensionByClassName ( $ className )
37+ private static function getTwig ( )
6138 {
62- foreach ( self :: $ twig-> getExtensions () as $ extension ) {
63- if ($ className == get_class ( $ extension ) ) {
64- return true ;
65- }
39+ //Initialise twig
40+ if (self :: $ twig === null ) {
41+ self :: $ twig = new Twig_Environment ( new Twig_Loader_String ()) ;
42+ self :: $ twig -> addExtension ( new Twig_Extensions_Extension_I18n ());
6643 }
6744
68- return false ;
45+ return self :: $ twig ;
6946 }
7047}
0 commit comments