Completed
Push — develop ( 45216f...b85a0a )
by Jens
02:57
created

TranslationHelper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 11
ccs 0
cts 6
cp 0
rs 9.4285
cc 1
eloc 9
nc 1
nop 4
crap 2
1
<?php
2
/**
3
 * @author @jayS-de <[email protected]>
4
 */
5
6
namespace JaySDe\HandlebarsBundle\Helper;
7
8
use LightnCandy\SafeString;
9
use Symfony\Component\Translation\TranslatorInterface;
10
11
class TranslationHelper implements HelperInterface
12
{
13
    /**
14
     * @var TranslatorInterface
15
     */
16
    private $translator;
17
    /**
18
     * @var string
19
     */
20
    private $defaultNamespace = null;
21
22
    /**
23
     * @var string
24
     */
25
    private $interpolationPrefix = '__';
26
27
    /**
28
     * @var string
29
     */
30
    private $interpolationSuffix = '__';
31
32
    public function __construct(
33
        TranslatorInterface $translator = null,
34
        $defaultNamespace = null,
35
        $interpolationPrefix = '__',
36
        $interpolationSuffix = '__'
37
    ) {
38
        $this->translator = $translator;
39
        $this->defaultNamespace = $defaultNamespace;
40
        $this->interpolationPrefix = $interpolationPrefix;
41
        $this->interpolationSuffix = $interpolationSuffix;
42
    }
43
44
    public function handle($context, $options)
45
    {
46
        $options = isset($options['hash']) ? $options['hash'] : [];
47
        if (strstr($context, ':')) {
48
            list($bundle, $context) = explode(':', $context, 2);
49
            $options['bundle'] = $bundle;
50
        }
51
52
        $bundle = $this->getOptionValue($options, 'bundle', $this->defaultNamespace);
53
        $locale = $this->getOptionValue($options, 'locale');
54
        $count = $this->getOptionValue($options, 'count');
55
56
        $args = $this->transformOptions($options);
57
58
        return new SafeString($this->trans($context, $args, $count, $bundle, $locale));
59
    }
60
61
    private function trans($context, $args, $count, $bundle, $locale)
62
    {
63
        if (is_null($count)) {
64
            $trans = $this->translator->trans($context, $args, $bundle, $locale);
65
        } else {
66
            $trans = $this->translator->transChoice($context, $count, $args, $bundle, $locale);
67
        }
68
69
        return $trans;
70
    }
71
72
    private function transformOptions($options)
73
    {
74
        $args = [];
75
        foreach ($options as $key => $value) {
76
            $key = $this->interpolationPrefix . $key . $this->interpolationSuffix;
77
            $args[$key] = $value;
78
        }
79
        return $args;
80
    }
81
82
    private function getOptionValue($options, $key, $default = null)
83
    {
84
        return isset($options[$key]) ? $options[$key]: $default;
85
    }
86
}
87