-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgenerate-examples.php
More file actions
executable file
·273 lines (234 loc) · 7.81 KB
/
generate-examples.php
File metadata and controls
executable file
·273 lines (234 loc) · 7.81 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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env php
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
set_error_handler(function ($level, $msg) {
echo "Error: {$msg}";
exit(1);
});
/**
* Read code samples and unescaped descriptions from OAS file and injects the
* data into Markdown documentation.
*
* When openapi-generator generates the SDK code, all markdown documentation
* files will contain escaped descriptions for method parameters. This is due
* to parameter documentation existing within markdown tables, surrounded by
* pipes `|`. Markdown table rows must contain all data in a single line, but
* unescaped descriptions will often contain linebreaks, list items, etc, that
* cannot correctly be displayed in markdown tables.
*
* This tool replaces linebreaks with `<br>`, fixes list items, fixes broken
* anchor links for specific parameter definitions.
*/
class GenerateExamples
{
/**
* @var Array<string, string>
*/
protected array $codeSamples = [];
/**
* openapi-generator considers array of array of object to be a primitive
* type so it does not create a link to the doc file.
*
* Array<string, string>
*/
protected array $extraReplace = [];
/**
* Languages of the code samples we are looking for. Usually will be a single
* language, ["PHP"], but the javascript SDK can generate both typescript and
* javascript.
*
* @var string[]
*/
protected array $languages = [];
/**
* Our OAS in array form
*
* @var array
*/
protected array $openapi;
/**
* Search and replace all files in these directories
*
* @var string[]
*/
protected array $replaceInDirectories = [];
/**
* Target specific files for search and replace
*
* @var string[]
*/
protected array $replaceInFiles = [];
protected bool $useSnakeCase = false;
public function __construct(
array $openapi,
array $languages,
array $replaceInDirectories,
array $replaceInFiles,
array $extraReplace = []
) {
$this->openapi = $openapi;
$this->languages = $languages;
$this->replaceInDirectories = $replaceInDirectories;
$this->replaceInFiles = $replaceInFiles;
$this->extraReplace = $extraReplace;
}
public function setUseSnakeCase(bool $flag): void
{
$this->useSnakeCase = $flag;
}
public function run(): void
{
$this->getCodeSamples();
foreach ($this->replaceInDirectories as $directory) {
$this->replaceInDirectory($directory);
}
foreach ($this->replaceInFiles as $file) {
$this->replaceInFile($file);
}
}
/**
* Reads OAS file and grabs code samples related to chosen languages,
* defined in Redocly's custom `x-codeSamples` spec extension:
*
* x-codeSamples:
-
lang: PHP
label: PHP
source:
$ref: examples/AccountCreate.php
*
* @return void
* @see https://redoc.ly/docs/api-reference-docs/specification-extensions/x-code-samples/
*/
protected function getCodeSamples(): void
{
foreach ($this->openapi['paths'] as $paths) {
foreach ($paths as $action) {
if (empty($action['x-codeSamples'])) {
continue;
}
foreach ($action['x-codeSamples'] as $sample) {
if (!in_array($sample['lang'], $this->languages, true)) {
continue;
}
$id = $action['operationId'];
if (empty($this->codeSamples[$id])) {
$this->codeSamples[$id] = [];
}
$contents = file_get_contents(
__DIR__ . "/../{$sample['source']['$ref']}"
);
$this->codeSamples[$id][$sample['lang']] = $contents;
}
}
}
}
/**
* Scans provided directories for markdown (.md) files to inject code
* samples and documentation into
*
* @param string $directory
* @return void
*/
protected function replaceInDirectory(string $directory): void
{
/** @var DirectoryIterator $fileInfo */
foreach (new DirectoryIterator($directory) as $fileInfo) {
if (
$fileInfo->isDir()
|| $fileInfo->isDot()
|| $fileInfo->getExtension() !== 'md'
) {
continue;
}
$this->replaceInFile($fileInfo->getPathname());
}
}
/**
* Injects code samples into provided files. Not limited to markdown (.md)
* files, can be anything. But usually markdown files.
*
* @param string $filepath
* @return void
*/
protected function replaceInFile(string $filepath): void
{
$fileContents = file_get_contents($filepath);
$fileContents = $this->replaceCodeSample($fileContents);
$fileContents = $this->replaceDocumentation($fileContents);
file_put_contents($filepath, $fileContents);
}
protected function replaceCodeSample(string $fileContents): string
{
foreach ($this->codeSamples as $operationId => $codeSamples) {
foreach ($codeSamples as $language => $codeSample) {
$toReplace = $this->getReplaceCodeString($operationId, $language);
$fileContents = str_replace(
$toReplace,
$codeSample,
$fileContents,
);
}
}
return $fileContents;
}
public function replaceDocumentation(string $fileContents): string
{
$search = "/(REPLACE_ME_WITH_DESCRIPTION_BEGIN)([\s\S][^|]*)(REPLACE_ME_WITH_DESCRIPTION_END)/";
$fileContents = preg_replace_callback(
$search,
function ($matches) {
$edited = str_replace("\n\n", '<br><br>', $matches[2]);
// Handles bullet lists
$edited = str_replace("\n*", '<br>*', $edited);
$edited = str_replace("\n", ' ', $edited);
return $edited;
},
$fileContents,
);
$fileContents = str_replace('`', '`', $fileContents);
foreach ($this->extraReplace as $k => $v) {
$fileContents = str_replace($k, $v, $fileContents, );
}
return $fileContents;
}
/**
* Our templates initially generate markdown documentation files with
* REPLACE_ME_WITH_EXAMPLE_FOR__{{{operationId}}}_{language}_CODE
* in place of the actual auto-generated examples that openapi-generator
* would usually generate.
*
* We simply search for this string and replace with associated code sample.
*
* Ex: REPLACE_ME_WITH_EXAMPLE_FOR__accountCreate_PHP_CODE
*
* @param string $operationId
* @param string $language
* @return string
*/
protected function getReplaceCodeString(
string $operationId,
string $language
): string {
$operationId = $this->useSnakeCase
? strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $operationId))
: $operationId;
return "REPLACE_ME_WITH_EXAMPLE_FOR__{$operationId}_{$language}_CODE";
}
}
$generate = new GenerateExamples(
Yaml::parse(file_get_contents(__DIR__ . '/../openapi-sdk.yaml')),
['Python'],
[__DIR__ . '/../docs'],
[__DIR__ . '/../README.md'],
[
'```[[SubFormFieldsPerDocumentBase]]```'
=> '[```[[SubFormFieldsPerDocumentBase]]```](SubFormFieldsPerDocumentBase.md)',
]
);
$generate->setUseSnakeCase(true);
$generate->run();