Translator::trans()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 2
b 0
f 0
nc 2
nop 4
dl 0
loc 18
rs 10
1
<?php
2
3
namespace Tleckie\Translate;
4
5
use Tleckie\Translate\Bookmark\BookmarkInterface;
6
use Tleckie\Translate\Loader\LoaderInterface;
7
use function sprintf;
8
9
/**
10
 * Class Translator
11
 *
12
 * @package  Tleckie\Translate
13
 * @category Translator
14
 * @author   Teodoro Leckie Westberg <[email protected]>
15
 */
16
class Translator implements TranslatorInterface
17
{
18
    /**
19
     * @var LoaderInterface
20
     */
21
    protected LoaderInterface $loader;
22
23
    /**
24
     * @var string
25
     */
26
    protected string $locale;
27
28
    /**
29
     * @var BookmarkInterface
30
     */
31
    protected BookmarkInterface $bookmark;
32
33
    /**
34
     * Translator constructor.
35
     *
36
     * @param LoaderInterface        $loader
37
     * @param string                 $locale
38
     * @param BookmarkInterface|null $bookmark
39
     */
40
    public function __construct(
41
        LoaderInterface $loader,
42
        string $locale = '',
43
        BookmarkInterface $bookmark = null
44
    ) {
45
        $this->loader = $loader;
46
47
        $this->setLocale($locale);
48
49
        $this->bookmark = $bookmark ?? new Bookmark();
50
51
        $this->bookmark->setLoader($loader);
52
    }
53
54
    /**
55
     * @inheritdoc
56
     */
57
    public function getBookmark(): BookmarkInterface
58
    {
59
        return $this->bookmark;
60
    }
61
62
    /**
63
     * @inheritdoc
64
     */
65
    public function getLoader(): LoaderInterface
66
    {
67
        return $this->loader;
68
    }
69
70
    /**
71
     * @inheritdoc
72
     */
73
    public function getLocale(): string
74
    {
75
        return $this->locale;
76
    }
77
78
    /**
79
     * @inheritdoc
80
     */
81
    public function setLocale(string $locale): TranslatorInterface
82
    {
83
        $this->locale = $locale;
84
85
        return $this;
86
    }
87
88
    /**
89
     * @inheritdoc
90
     */
91
    public function trans(
92
        string $keyToTranslate,
93
        array $arguments = [],
94
        string $fallback = null,
95
        string $locale = null
96
    ): string {
97
        $locale = $locale ?? $this->locale;
98
99
        $replaced = sprintf(
100
            $this->bookmark->getCatalogue($locale)->getByKey($keyToTranslate),
101
            ...$arguments
102
        );
103
104
        if (empty($replaced)) {
105
            return $fallback;
106
        }
107
108
        return $replaced;
109
    }
110
}
111