1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace SumoCoders\FrameworkCoreBundle\Twig; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\DependencyInjection\ContainerInterface; |
6
|
|
|
|
7
|
|
|
class FrameworkExtension extends \Twig_Extension |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var \Symfony\Component\DependencyInjection\ContainerInterface |
11
|
|
|
*/ |
12
|
|
|
protected $container; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @param ContainerInterface $container |
16
|
|
|
*/ |
17
|
20 |
|
public function __construct(ContainerInterface $container) |
18
|
|
|
{ |
19
|
20 |
|
$this->container = $container; |
20
|
20 |
|
} |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Get the registered functions |
24
|
|
|
* |
25
|
|
|
* @return array |
26
|
|
|
*/ |
27
|
2 |
|
public function getFunctions() |
28
|
|
|
{ |
29
|
|
|
return [ |
30
|
2 |
|
new \Twig_SimpleFunction( |
31
|
2 |
|
'bundleExists', |
32
|
2 |
|
[$this, 'bundleExists'] |
33
|
|
|
), |
34
|
2 |
|
new \Twig_SimpleFunction( |
35
|
2 |
|
'toTranslation', |
36
|
2 |
|
[$this, 'convertToTranslation'] |
37
|
|
|
), |
38
|
|
|
]; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* Check if a bundle exists |
43
|
|
|
* |
44
|
|
|
* @param string $bundle |
45
|
|
|
* @return bool |
46
|
|
|
*/ |
47
|
9 |
|
public function bundleExists($bundle) |
48
|
|
|
{ |
49
|
9 |
|
$bundles = $this->container->getParameter('kernel.bundles'); |
50
|
|
|
|
51
|
9 |
|
return array_key_exists($bundle, $bundles); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* Convert a given string into a string that will/can be used as a id for |
56
|
|
|
* translations |
57
|
|
|
* |
58
|
|
|
* @param string $stringToConvert |
59
|
|
|
* @return string |
60
|
|
|
*/ |
61
|
18 |
|
public function convertToTranslation($stringToConvert) |
62
|
|
|
{ |
63
|
18 |
|
$stringToConvert = trim($stringToConvert); |
64
|
18 |
|
$stringToConvert = str_replace( |
65
|
18 |
|
['_', '-', ' ', 'framework', 'Framework'], |
66
|
18 |
|
'.', |
67
|
18 |
|
$stringToConvert |
68
|
|
|
); |
69
|
|
|
|
70
|
|
|
// the first item will mostly be the prefix of the namespace |
71
|
18 |
|
$stringToConvert = preg_replace('/(.*)\.(.*)bundle/U', '$1$2', $stringToConvert); |
72
|
18 |
|
$stringToConvert = str_replace('bundle', '', $stringToConvert); |
73
|
18 |
|
$stringToConvert = str_replace('Bundle', '', $stringToConvert); |
74
|
|
|
|
75
|
18 |
|
if (strtolower(mb_substr($stringToConvert, 0, 11)) == 'sumocoders.') { |
76
|
2 |
|
$stringToConvert = substr($stringToConvert, 11); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
// remove numbers if they appear at the end or as single items |
80
|
18 |
|
$stringToConvert = preg_replace('/\d+$/', '', $stringToConvert); |
81
|
18 |
|
$stringToConvert = preg_replace('/\.\d*\./', '.', $stringToConvert); |
82
|
|
|
|
83
|
18 |
|
$stringToConvert = preg_replace('/\.+/', '.', $stringToConvert); |
84
|
|
|
|
85
|
18 |
|
return trim($stringToConvert, '.'); |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|