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

TranslatorTrait::say()   B

Complexity

Conditions 5
Paths 4

Size

Total Lines 26
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.439
cc 5
eloc 9
nc 4
nop 2
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
}