Completed
Push — master ( ec8354...8f0854 )
by Mārtiņš
02:29
created

MessageBuilder::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 3
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
    /** @var MessageRevisions */
21
    private $revisions;
22
23 5
    public function __construct(
24
        MessageConfigInterface $config,
25
        MessageStorage $storage,
26
        MessageRevisions $revisions
27
    ) {
28 5
        $this->config = $config;
29 5
        $this->storage = $storage;
30 5
        $this->revisions = $revisions;
31 5
    }
32
33
    /**
34
     * @param string $locale
35
     * @param string $domain
36
     * @return bool
37
     * @throws InvalidPathException
38
     */
39 5
    public function export(string $locale, string $domain): bool
40
    {
41 5
        $translations = $this->storage->getAll($locale, $domain);
42
43 5
        $revisionedDomain = null;
44 5
        if ($this->config->useRevisions()) {
45
            $revisionedDomain = $this->revisions->generateRevisionedDomain($domain, $translations);
46
        }
47
48 5
        $pathname = $this->getMoPathname($locale, $revisionedDomain ?: $domain);
49
50 4
        $wasSaved = Mo::toFile($translations, $pathname);
51
52 4
        if($wasSaved && $revisionedDomain){
53
            $this->revisions->saveRevision($locale, $domain, $revisionedDomain);
54
        }
55
56 4
        return $wasSaved;
57
    }
58
59
    /**
60
     * @param string $locale
61
     * @param string $domain
62
     * @return string
63
     * @throws InvalidPathException
64
     */
65 5
    private function getMoPathname(string $locale, string $domain): string
66
    {
67 5
        return $this->ensureDirectory($locale) . '/' . $domain . '.mo';
68
    }
69
70
    /**
71
     * @param string $locale
72
     * @return string
73
     * @throws InvalidPathException
74
     */
75 5
    private function ensureDirectory(string $locale): string
76
    {
77 5
        $dirPath = rtrim($this->config->getMoDirectory(), '/');
78
79 5
        if (!is_dir($dirPath)) {
80 1
            throw new InvalidPathException("Directory '$dirPath' does not exist");
81
        }
82
83 4
        $path = $dirPath . '/' . $locale . '/LC_MESSAGES';
84
85 4
        if (!is_dir($path)) {
86 4
            mkdir($path, 0777, true);
87
        }
88
89 4
        return $path;
90
    }
91
}