Passed
Push — master ( 0bf476...883135 )
by Def
02:20
created

MessageSource::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Translator\Message\Gettext;
6
7
use Yiisoft\Translator\MessageReaderInterface;
8
9
final class MessageSource implements MessageReaderInterface
10
{
11
    private string $path;
12
    private array $boundDomains = [];
13
14 30
    public function __construct(string $path)
15
    {
16 30
        if (!is_dir($path)) {
17 1
            throw new \RuntimeException(sprintf('Directory "%s" does not exist.', $path));
18
        }
19 29
        $this->path = $path;
20 29
    }
21
22
    /**
23
     * {@inheritdoc}
24
     *
25
     * We use first parameter as `$n` for plurals if its value type is int.
26
     */
27 29
    public function getMessage(string $id, string $category, string $locale, array $parameters = []): ?string
28
    {
29 29
        $this->bindDomain($category);
30 29
        $this->setLocale($locale);
31 28
        $n = current($parameters);
32 28
        if (is_int($n) === false) {
33 8
            return dgettext($category, $id);
34
        }
35 20
        return dngettext($category, $id, $id, $n);
36
    }
37
38 29
    private function bindDomain(string $category): void
39
    {
40 29
        if (!isset($this->boundDomains[$category])) {
41 29
            bindtextdomain($category, $this->path);
42
        }
43 29
    }
44
45 29
    private function setLocale(string $locale): void
46
    {
47 29
        if (!setlocale(LC_ALL, $locale)) {
48 1
            throw new \RuntimeException(sprintf('Locale "%s" cannot be set.', $locale));
49
        }
50 28
    }
51
}
52