Skip to content

Commit 5fdeb3b

Browse files
committed
simplified Twig extractor
1 parent b064d78 commit 5fdeb3b

1 file changed

Lines changed: 11 additions & 34 deletions

File tree

src/Extractors/Twig.php

Lines changed: 11 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Gettext\Translations;
66
use Twig_Loader_String;
77
use 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

Comments
 (0)