MessageSource::bindDomain()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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