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

MessageBuilder   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
dl 0
loc 62
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A ensureDirectory() 0 15 3
A getMoPathname() 0 3 1
A export() 0 7 1
A __construct() 0 6 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
}