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
|
|
|
} |