/
XliffService.php
245 lines (214 loc) · 7.98 KB
/
XliffService.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
<?php
namespace Neos\Neos\Service;
/*
* This file is part of the Neos.Neos package.
*
* (c) Contributors of the Neos Project - www.neos.io
*
* This package is Open Source Software. For the full copyright and license
* information, please view the LICENSE file which was distributed with this
* source code.
*/
use Neos\Flow\Annotations as Flow;
use Neos\Cache\Frontend\VariableFrontend;
use Neos\Flow\I18n\Xliff\Service\XliffFileProvider;
use Neos\Flow\I18n\Xliff\Service\XliffReader;
use Neos\Flow\Package\PackageInterface;
use Neos\Flow\Package\PackageManager;
use Neos\Utility\Files;
use Neos\Flow\I18n\Locale;
use Neos\Flow\I18n\Service as LocalizationService;
use Neos\Utility\Unicode\Functions as UnicodeFunctions;
/**
* The XLIFF service provides methods to find XLIFF files and parse them to json
*
* @Flow\Scope("singleton")
*/
class XliffService
{
/**
* A relative path for translations inside the package resources.
*
* @var string
*/
protected $xliffBasePath = 'Private/Translations/';
/**
* @Flow\Inject
* @var XliffReader
*/
protected $xliffReader;
/**
* @Flow\Inject
* @var LocalizationService
*/
protected $localizationService;
/**
* @Flow\Inject
* @var VariableFrontend
*/
protected $xliffToJsonTranslationsCache;
/**
* @Flow\InjectConfiguration(path="userInterface.scrambleTranslatedLabels", package="Neos.Neos")
* @var boolean
*/
protected $scrambleTranslatedLabels = false;
/**
* @Flow\InjectConfiguration(path="userInterface.translation.autoInclude", package="Neos.Neos")
* @var array
*/
protected $packagesRegisteredForAutoInclusion = [];
/**
* @Flow\Inject
* @var XliffFileProvider
*/
protected $xliffFileProvider;
/**
* @Flow\Inject
* @var PackageManager
*/
protected $packageManager;
/**
* Return the json array for a given locale, sourceCatalog, xliffPath and package.
* The json will be cached.
*
* @param Locale $locale The locale
* @return string
* @throws \Neos\Cache\Exception
* @throws \Neos\Flow\Package\Exception\UnknownPackageException
*/
public function getCachedJson(Locale $locale): string
{
$cacheIdentifier = md5($locale);
if ($this->xliffToJsonTranslationsCache->has($cacheIdentifier)) {
$json = $this->xliffToJsonTranslationsCache->get($cacheIdentifier);
} else {
$labels = [];
foreach ($this->packagesRegisteredForAutoInclusion as $packageKey => $sourcesToBeIncluded) {
if (!is_array($sourcesToBeIncluded)) {
continue;
}
$package = $this->packageManager->getPackage($packageKey);
$sources = $this->collectPackageSources($package, $sourcesToBeIncluded);
//get the xliff files for those sources
foreach ($sources as $sourceName) {
$fileId = $packageKey . ':' . $sourceName;
$file = $this->xliffFileProvider->getFile($fileId, $locale);
foreach ($file->getTranslationUnits() as $key => $value) {
$valueToStore = $this->getTranslationUnitValue($value);
$valueToStore = count($valueToStore) > 1 ? $valueToStore : array_shift($valueToStore);
$this->setArrayDataValue($labels, str_replace('.', '_', $packageKey) . '.' . str_replace('/', '_', $sourceName) . '.' . str_replace('.', '_', $key), $valueToStore);
}
}
}
$json = json_encode($labels);
$this->xliffToJsonTranslationsCache->set($cacheIdentifier, $json);
}
return $json;
}
/**
* @param array $labelValue
* @return array
*/
protected function getTranslationUnitValue(array $labelValue)
{
$xliffValue = [];
foreach ($labelValue as $key => $value) {
$valueToStore = !empty($value['target']) ? $value['target'] : $value['source'];
if ($this->scrambleTranslatedLabels) {
$valueToStore = str_repeat('#', UnicodeFunctions::strlen($valueToStore));
}
$xliffValue[$key] = $valueToStore;
}
return $xliffValue;
}
/**
* @return string The current cache version identifier
* @throws \Neos\Cache\Exception
*/
public function getCacheVersion(): string
{
$version = $this->xliffToJsonTranslationsCache->get('ConfigurationVersion');
if ($version === false) {
$version = time();
$this->xliffToJsonTranslationsCache->set('ConfigurationVersion', (string)$version);
}
return (string) $version;
}
/**
* Collect all sources found in the given package as array (key = source, value = true)
* If sourcesToBeIncluded is an array, only those sources are returned what match the wildcard-patterns in the
* array-values
*
* @param PackageInterface $package
* @param array $sourcesToBeIncluded optional array of wildcard-patterns to filter the sources
* @return array
*/
protected function collectPackageSources(PackageInterface $package, $sourcesToBeIncluded = null): array
{
$packageKey = $package->getPackageKey();
$sources = [];
$translationPath = $package->getResourcesPath() . $this->xliffBasePath;
if (!is_dir($translationPath)) {
return [];
}
foreach (Files::readDirectoryRecursively($translationPath, '.xlf') as $filePath) {
//remove translation path from path
$source = trim(str_replace($translationPath, '', $filePath), '/');
//remove language part from path
$source = trim(substr($source, strpos($source, '/')), '/');
//remove file extension
$source = substr($source, 0, strrpos($source, '.'));
$this->xliffReader->readFiles(
$filePath,
function (\XMLReader $file, $offset, $version) use ($packageKey, &$sources, $source, $sourcesToBeIncluded) {
$targetPackageKey = $packageKey;
if ($version === '1.2') {
//in xliff v1.2 the packageKey or source can be overwritten via attributes
$targetPackageKey = $file->getAttribute('product-name') ?: $packageKey;
$source = $file->getAttribute('original') ?: $source;
}
if ($packageKey !== $targetPackageKey) {
return;
}
if (is_array($sourcesToBeIncluded)) {
$addSource = false;
foreach ($sourcesToBeIncluded as $sourcePattern) {
if (fnmatch($sourcePattern, $source)) {
$addSource = true;
break;
}
}
if (!$addSource) {
return;
}
}
$sources[$source] = true;
}
);
}
return array_keys($sources);
}
/**
* Helper method to create the needed json array from a dotted xliff id
*
* @param array $arrayPointer
* @param string $key
* @param string|array $value
* @return void
*/
protected function setArrayDataValue(array &$arrayPointer, $key, $value)
{
$keys = explode('.', $key);
// Extract the last key
$lastKey = array_pop($keys);
// Walk/build the array to the specified key
while ($arrayKey = array_shift($keys)) {
if (!array_key_exists($arrayKey, $arrayPointer)) {
$arrayPointer[$arrayKey] = [];
}
$arrayPointer = &$arrayPointer[$arrayKey];
}
// Set the final key
$arrayPointer[$lastKey] = $value;
}
}