|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Printful\GettextCms; |
|
4
|
|
|
|
|
5
|
|
|
use Gettext\Translation; |
|
6
|
|
|
use Printful\GettextCms\Exceptions\MissingMessagesException; |
|
7
|
|
|
use Printful\GettextCms\Interfaces\MessageConfigInterface; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Class allows adding dynamically generated translations which are not present in files. |
|
11
|
|
|
* For example, add messages from database fields which you still want to use gettext with. |
|
12
|
|
|
*/ |
|
13
|
|
|
class DynamicMessageImporter |
|
14
|
|
|
{ |
|
15
|
|
|
/** @var MessageConfigInterface */ |
|
16
|
|
|
private $config; |
|
17
|
|
|
|
|
18
|
|
|
/** @var MessageStorage */ |
|
19
|
|
|
private $storage; |
|
20
|
|
|
|
|
21
|
|
|
/** @var array [context => [message, ..], ..] */ |
|
22
|
|
|
private $messages = []; |
|
23
|
|
|
|
|
24
|
3 |
|
public function __construct(MessageConfigInterface $config, MessageStorage $storage) |
|
25
|
|
|
{ |
|
26
|
3 |
|
$this->config = $config; |
|
27
|
3 |
|
$this->storage = $storage; |
|
28
|
3 |
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Add message to the message queue to be saved. |
|
32
|
|
|
* Save has to be called to save all the translations to the repository |
|
33
|
|
|
* |
|
34
|
|
|
* @see \Printful\GettextCms\Structures\DynamicMessageImporter::saveAndDisabledPrevious |
|
35
|
|
|
* |
|
36
|
|
|
* @param string $original |
|
37
|
|
|
* @param string $context |
|
38
|
|
|
* @return DynamicMessageImporter |
|
39
|
|
|
*/ |
|
40
|
2 |
|
public function add(string $original, string $context = ''): DynamicMessageImporter |
|
41
|
|
|
{ |
|
42
|
2 |
|
$this->messages += [$context => []]; |
|
43
|
2 |
|
$this->messages[$context][$original] = $original; |
|
44
|
|
|
|
|
45
|
2 |
|
return $this; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
/** |
|
49
|
|
|
* Save given messages to domain |
|
50
|
|
|
* All old messages will be disabled |
|
51
|
|
|
* |
|
52
|
|
|
* @param string $domain |
|
53
|
|
|
* @throws MissingMessagesException |
|
54
|
|
|
*/ |
|
55
|
3 |
|
public function saveAndDisabledPrevious(string $domain) |
|
56
|
|
|
{ |
|
57
|
3 |
|
if (empty($this->messages)) { |
|
58
|
1 |
|
throw new MissingMessagesException('Tried to save but no messages were given'); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
2 |
|
$locales = $this->config->getLocales(); |
|
62
|
|
|
|
|
63
|
2 |
|
foreach ($locales as $locale) { |
|
64
|
2 |
|
$this->storage->disableAll($locale, $domain); |
|
65
|
|
|
|
|
66
|
2 |
|
foreach ($this->messages as $context => $messages) { |
|
67
|
2 |
|
foreach ($messages as $message) { |
|
68
|
2 |
|
$this->storage->createOrUpdateSingle( |
|
69
|
2 |
|
$locale, |
|
70
|
2 |
|
$domain, |
|
71
|
2 |
|
new Translation($context, $message) |
|
72
|
|
|
); |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
// Clear the queue of messages to be saved so on repeated |
|
78
|
2 |
|
$this->messages = []; |
|
79
|
|
|
} |
|
80
|
|
|
} |