Passed
Pull Request — master (#24)
by Def
07:37
created

MessageSource   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 17
dl 0
loc 45
ccs 21
cts 21
cp 1
rs 10
c 1
b 0
f 0
wmc 9

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getMessage() 0 9 2
A __construct() 0 6 2
A getMessages() 0 3 1
A bindDomain() 0 4 2
A setLocale() 0 4 2
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 31
    public function __construct(string $path)
15
    {
16 31
        if (!is_dir($path)) {
17 1
            throw new \RuntimeException(sprintf('Directory "%s" does not exist.', $path));
18
        }
19 30
        $this->path = $path;
20 30
    }
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 1
    public function getMessages(string $category, string $locale): array
39
    {
40 1
        throw new \RuntimeException('Function not allowed for this package.');
41
    }
42
43 29
    private function bindDomain(string $category): void
44
    {
45 29
        if (!isset($this->boundDomains[$category])) {
46 29
            bindtextdomain($category, $this->path);
47
        }
48 29
    }
49
50 29
    private function setLocale(string $locale): void
51
    {
52 29
        if (!setlocale(LC_ALL, $locale)) {
53 1
            throw new \RuntimeException(sprintf('Locale "%s" cannot be set.', $locale));
54
        }
55 28
    }
56
}
57