Passed
Push — master ( b38da1...a59646 )
by Dāvis
04:33
created

TranslationExtension   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 5
Bugs 2 Features 0
Metric Value
dl 0
loc 37
rs 10
c 5
b 2
f 0
wmc 8

3 Methods

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