Completed
Push — master ( 13f2f6...228141 )
by Mārtiņš
01:55
created

MessageBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Printful\GettextCms;
4
5
use Gettext\Generators\Mo;
6
use Printful\GettextCms\Exceptions\InvalidPathException;
7
use Printful\GettextCms\Interfaces\MessageConfigInterface;
8
9
/**
10
 * Class allows to export translations from repository to a generated .mo file which is used with gettext
11
 */
12
class MessageBuilder
13
{
14
    /** @var MessageConfigInterface */
15
    private $config;
16
17
    /** @var MessageStorage */
18
    private $storage;
19
20 2
    public function __construct(
21
        MessageConfigInterface $config,
22
        MessageStorage $storage
23
    ) {
24 2
        $this->config = $config;
25 2
        $this->storage = $storage;
26 2
    }
27
28
    /**
29
     * @param string $locale
30
     * @param string $domain
31
     * @return bool
32
     * @throws InvalidPathException
33
     */
34 2
    public function export(string $locale, string $domain)
35
    {
36 2
        $translations = $this->storage->getAll($locale, $domain);
37
38 2
        $pathname = $this->getMoPathname($locale, $domain);
39
40 1
        return Mo::toFile($translations, $pathname);
41
    }
42
43
    /**
44
     * @param string $locale
45
     * @param string $domain
46
     * @return string
47
     * @throws InvalidPathException
48
     */
49 2
    private function getMoPathname(string $locale, string $domain)
50
    {
51 2
        return $this->ensureDirectory($locale) . '/' . $domain . '.mo';
52
    }
53
54
    /**
55
     * @param string $locale
56
     * @return string
57
     * @throws InvalidPathException
58
     */
59 2
    private function ensureDirectory(string $locale)
60
    {
61 2
        $dirPath = rtrim($this->config->getMoDirectory(), '/');
62
63 2
        if (!is_dir($dirPath)) {
64 1
            throw new InvalidPathException("Directory '$dirPath' does not exist");
65
        }
66
67 1
        $path = $dirPath . '/' . $locale . '/LC_MESSAGES';
68
69 1
        if (!is_dir($path)) {
70 1
            mkdir($path, 0777, true);
71
        }
72
73 1
        return $path;
74
    }
75
}