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