Completed
Branch dbal-improvement (e43d29)
by Anton
06:02
created

TranslatorTrait   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 6
Bugs 0 Features 0
Metric Value
wmc 5
c 6
b 0
f 0
lcom 0
cbo 2
dl 0
loc 44
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B say() 0 26 5
container() 0 1 ?
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
namespace Spiral\Translator\Traits;
9
10
use Interop\Container\ContainerInterface;
11
use Spiral\Core\Container;
12
use Spiral\Translator\TranslatorInterface;
13
14
/**
15
 * Add bundle specific translation functionality, class name will be used as translation bundle.
16
 * In addition every default string message declared in class using [[]] braces can be indexed by
17
 * spiral application.
18
 */
19
trait TranslatorTrait
20
{
21
    /**
22
     * Translate message using parent class as bundle name. Method will remove string braces ([[ and
23
     * ]]) if specified.
24
     *
25
     * Example: $this->say("User account is invalid.");
26
     *
27
     * @param string $string
28
     * @param array  $options Interpolation options.
29
     * @return string
30
     */
31
    protected function say($string, array $options = [])
32
    {
33
        if (
34
            substr($string, 0, 2) === TranslatorInterface::I18N_PREFIX
35
            && substr($string, -2) === TranslatorInterface::I18N_POSTFIX
36
        ) {
37
            //This string was defined in class attributes
38
            $string = substr($string, 2, -2);
39
        }
40
41
        if (empty($container = $this->container()) || !$container->has(TranslatorInterface::class)) {
42
            //No translator available
43
            return $string;
44
        }
45
46
        /**
47
         * Potentially can be downgraded to Symfony\TranslatorInterface but without domains map
48
         * feature
49
         *
50
         * @var TranslatorInterface $translator
51
         */
52
        $translator = $container->get(TranslatorInterface::class);
53
54
        //Translate class string using automatically resolved message domain
55
        return $translator->trans($string, $options, $translator->resolveDomain(static::class));
56
    }
57
58
    /**
59
     * @return ContainerInterface
60
     */
61
    abstract protected function container();
62
}