Passed
Branch master (c65ffc)
by Dāvis
03:08
created

TranslationExtension   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
c 6
b 1
f 0
dl 0
loc 44
rs 10
wmc 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
A getFilters() 0 7 1
A getName() 0 3 1
B getVar() 0 15 6
1
<?php
2
3
namespace Sludio\HelperBundle\Translatable\Twig;
4
5
use Sludio\HelperBundle\Script\Twig\TwigTrait;
6
7
class TranslationExtension extends \Twig_Extension
8
{
9
    use TwigTrait;
10
11
    protected $request;
12
    protected $defaultLocale;
13
    protected $shortFunctions;
14
15
    public function __construct($requestStack, $default, $container)
16
    {
17
        $this->request = $requestStack->getCurrentRequest();
18
        $this->defaultLocale = $default;
19
        $this->shortFunctions = $container->hasParameter('sludio_helper.script.short_functions') && $container->getParameter('sludio_helper.script.short_functions');
20
    }
21
22
    public function getName()
23
    {
24
        return 'sludio_helper.twig.translate_extension';
25
    }
26
27
    public function getFilters()
28
    {
29
        $input = [
30
            'var' => 'getVar',
31
        ];
32
33
        return $this->makeArray($input);
34
    }
35
36
    public function getVar($type, $object, $original = false, $locale = null)
37
    {
38
        if ($object && is_object($object)) {
39
            $lang = $this->request ? $this->request->cookies->get('hl') : $this->defaultLocale;
40
41
            $new_locale = $locale;
42
            if (!$locale) {
43
                $new_locale = $this->request ? $this->request->get('_locale') : $lang;
44
            }
45
46
            $trans = $object->getVariableByLocale($type, $new_locale, $original);
47
48
            return $trans;
49
        } else {
50
            return $type;
51
        }
52
    }
53
}
54