-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathRawFile.php
More file actions
253 lines (215 loc) · 7.56 KB
/
Copy pathRawFile.php
File metadata and controls
253 lines (215 loc) · 7.56 KB
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
246
247
248
249
250
251
252
253
<?php
declare(strict_types=1);
namespace Hello\OpenApi;
use Exception;
use Symfony\Component\Yaml\Yaml;
class RawFile
{
/**
* We expect translation key strings to look like
* "_t__AccountCreate::SUMMARY"
*/
private const TRANSLATE_PREPEND = '_t__';
/**
* We expect markdown key strings to look like
* "_md__OpenApi::TAG"
*/
private const MARKDOWN_PREPEND = '_md__';
/**
* Custom key to determine a surface on which a spec
* is to be shown.
*
* e.g.
* x-hideOn: 'sdk'
* x-hideOn: 'doc'
* x-hideOn:
* - sdk
* - doc
*/
private const HIDE_ON = 'x-hideOn';
private const PREPENDS = [
self::TRANSLATE_PREPEND,
self::MARKDOWN_PREPEND,
];
/**
* Contains the OpenAPI spec, in array form
*/
private array $openapi;
private array $translations = [];
private array $fallback_translations = [];
/**
* Keep track of which strings have been translated using the chosen
* language, which needed to fallback to default language, and which ones
* did not get translated at all
*/
private array $logs = [
'translated' => [],
'fallback' => [],
'untranslated' => [],
];
public function __construct(string $filename)
{
$this->openapi = Yaml::parse(file_get_contents($filename));
}
public function translate(
string $surface_id,
string $translation_file,
string $fallback_file
): void {
$this->loadTranslations($translation_file, $fallback_file);
$result = $this->recurse($this->openapi, $surface_id);
$this->logs['translated'] = array_unique($this->logs['translated']);
$this->logs['fallback'] = array_unique($this->logs['fallback']);
$this->logs['untranslated'] = array_unique($this->logs['untranslated']);
$this->openapi = $result->getData();
}
public function getData(): array
{
return $this->openapi;
}
public function setData(array $data): void
{
$this->openapi = $data;
}
/**
* Provides information of which strings have been translated using the
* chosen language, which needed to fallback to default language, and which
* ones did not get translated at all
*/
public function getLogs(): array
{
return $this->logs;
}
public function saveFile(string $targetFile): void
{
foreach ($this->openapi['paths'] as $path => $path_item) {
foreach ($path_item as $method => $operation) {
if (empty($operation['responses'])) {
continue;
}
foreach ($operation['responses'] as $code => $response) {
unset($this->openapi['paths'][$path][$method]['responses'][$code]);
$new_code = "{$code}_response_code_remove_me";
$this->openapi['paths'][$path][$method]['responses'][$new_code] = $response;
}
}
}
$yaml = Yaml::dump(
$this->openapi,
10,
2,
Yaml::DUMP_OBJECT_AS_MAP
^ Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE
^ Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK
);
// An empty JSON response of `{}` can't be represented as a PHP array
$yaml = str_replace('value: []', 'value: {}', $yaml);
$yaml = str_replace('metadata: []', 'metadata: {}', $yaml);
$yaml = str_replace('additionalProperties: []', 'additionalProperties: {}', $yaml);
$yaml = str_replace('application/json: []', 'application/json: {}', $yaml);
$yaml = preg_replace('/([0-9x]+)_response_code_remove_me:/i', '\'${1}\':', $yaml);
file_put_contents($targetFile, $yaml);
}
/**
* Load both chosen language and fallback translations
*/
private function loadTranslations(string $file, string $fallback): void
{
if (!file_exists($file)) {
throw new Exception(
"No translation file found: {$file}"
);
}
if (!file_exists($fallback)) {
throw new Exception(
"Fallback translation file not found at {$fallback}"
);
}
$this->translations = Yaml::parse(file_get_contents($file));
$this->fallback_translations = Yaml::parse(file_get_contents($fallback));
}
/**
* Recursive function that iterates through all keys in the OpenAPI spec,
* searching for strings prepended with TRANSLATE_PREPEND and attempting
* to translate them.
*/
private function recurse(array $data, string $surface_id): TranslationResult
{
$empty_by_hiding = false;
foreach ($data as $k => $v) {
if (is_iterable($v)) {
if (isset($v[self::HIDE_ON]) && $this->shouldHide($v[self::HIDE_ON], $surface_id)) {
unset($data[$k]);
$empty_by_hiding = empty($data);
} else {
unset($v[self::HIDE_ON]);
$result = $this->recurse($v, $surface_id);
if ($result->isAllHidden()) {
unset($data[$k]);
} else {
$data[$k] = $result->getData();
}
}
continue;
}
$translationString = '';
foreach (self::PREPENDS as $prepend) {
if (!is_string($v) || strpos($v, $prepend) !== 0) {
continue;
}
$translationString = str_replace($prepend, '', $v);
if (array_key_exists($translationString, $this->translations)) {
$data[$k] = $this->getTranslation(
$prepend,
$translationString,
$this->translations
);
$this->logs['translated'][] = $translationString;
// We found translation, move on to next data
continue 2;
}
if (array_key_exists($translationString, $this->fallback_translations)) {
$data[$k] = $this->getTranslation(
$prepend,
$translationString,
$this->fallback_translations
);
$this->logs['fallback'][] = $translationString;
// We found fallback translation, move on to next data
continue 2;
}
}
if (!empty($translationString)) {
$this->logs['untranslated'][] = $translationString;
}
}
return new TranslationResult($data, $empty_by_hiding);
}
private function shouldHide($hideOn, string $surface_id): bool
{
if (is_array($hideOn)) {
return in_array($surface_id, $hideOn, true);
}
return $hideOn === $surface_id;
}
/**
* @return array|mixed|void
*/
private function getTranslation(
string $prepend,
string $translationString,
array $translations
) {
switch ($prepend) {
case self::MARKDOWN_PREPEND:
// Using $ref property to embed markdown
return [
'$ref' => $translations[$translationString],
];
case self::TRANSLATE_PREPEND:
return $translations[$translationString];
default:
return $translationString;
}
}
}