Repository navigation
Expand file tree
/
Copy pathParser.php
More file actions
345 lines (288 loc) · 9.21 KB
/
Copy pathParser.php
File metadata and controls
345 lines (288 loc) · 9.21 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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<?php
declare(strict_types=1);
namespace Bfabio\PublicCodeParser;
use Bfabio\PublicCodeParser\Exception\ParserException;
use Bfabio\PublicCodeParser\Exception\ValidationException;
use FFI;
class Parser
{
private ParserConfig $config;
private FFI $ffi;
private static ?FFI $ffiInstance = null;
private int $handle;
public function __construct(?ParserConfig $config = null)
{
$this->config = $config ?? new ParserConfig();
$this->ffi = $this->getFFI();
/** @phpstan-ignore-next-line */
$this->handle = $this->ffi->NewParser(
$this->config->isNetworkDisabled(),
$this->config->areExternalChecksDisabled(),
$this->config->getBranch(),
$this->config->getBaseURL(),
$this->config->getHTTPTimeout() * 1_000_000_000,
);
if ($this->handle == 0) {
throw new ParserException('Failed to create parser');
}
}
public function __destruct()
{
if ($this->handle != 0) {
/** @phpstan-ignore-next-line */
$this->ffi->FreeParser($this->handle);
$this->handle = 0;
}
}
/**
* Parse publiccode.yml content
*
* @param string $content YAML content
* @return PublicCodeV0
* @throws ParserException
* @throws ValidationException
*/
public function parse(string $content): PublicCodeV0
{
/** @phpstan-ignore-next-line */
$result = $this->ffi->ParseString($this->handle, $content);
if ($result === null) {
throw new ParserException('Failed to parse publiccode.yml content');
}
return $this->processResult($result);
}
/**
* Parse a publiccode.yml file
*
* @param string $filePath Path to publiccode.yml
* @return PublicCodeV0
* @throws ParserException
* @throws ValidationException
*/
public function parseFile(string $filePath): PublicCodeV0
{
/** @phpstan-ignore-next-line */
$result = $this->ffi->ParseFile($this->handle, $filePath);
if ($result === null) {
throw new ParserException("Failed to parse $filePath");
}
return $this->processResult($result);
}
/**
* Helper function to validate publiccode.yml file, with no error details
*
* @param string $filePath
* @return bool
*/
public function isValid(string $filePath): bool
{
try {
$this->parseFile($filePath);
return true;
} catch (ParserException | ValidationException $e) {
return false;
}
}
/**
* Get or create FFI instance
*
* @return FFI
* @throws ParserException
*/
private function getFFI(): FFI
{
if (self::$ffiInstance !== null) {
return self::$ffiInstance;
}
$libraryPath = $this->findLibrary();
$cdef = <<<'CDEF'
typedef struct {
char* Data;
char* Error;
int ErrorCount;
char** Errors;
int WarningCount;
char** Warnings;
} ParseResult;
typedef uintptr_t ParserHandle;
ParserHandle NewParser(bool disableNetwork, bool disableExternalChecks, const char* branch, const char* baseURL, int64_t httpTimeout);
ParseResult* ParseString(ParserHandle handle, const char* content);
ParseResult* ParseFile(ParserHandle handle, const char* uri);
void FreeResult(ParseResult* result);
void FreeParser(ParserHandle handle);
CDEF;
try {
self::$ffiInstance = FFI::cdef($cdef, $libraryPath);
return self::$ffiInstance;
} catch (\FFI\Exception $e) {
throw new ParserException(
'Failed to load publiccode-parser library: ' . $e->getMessage(),
0,
$e,
);
}
}
/**
* Find the publiccode-parser shared library
*
* @return string
* @throws ParserException
*/
private function findLibrary(): string
{
$os = $this->detectOS();
$arch = $this->detectArchitecture();
$ext = $os === 'darwin' ? 'dylib' : 'so';
$libraryName = "libpubliccode-parser-{$os}-{$arch}.{$ext}";
$possiblePaths = [
__DIR__ . '/',
__DIR__ . '/../lib/',
__DIR__ . '/../vendor/lib/',
'/usr/local/lib/',
'/usr/lib/',
];
foreach ($possiblePaths as $path) {
$filePath = $path . $libraryName;
if (file_exists($filePath)) {
return $filePath;
}
}
throw new ParserException(
"libpubliccode-parser library not found for platform: {$os}-{$arch}. " .
"Searched for: {$libraryName}",
);
}
/**
* Detect operating system
*
* @return 'linux'|'darwin'
* @throws ParserException
*/
private function detectOS(): string
{
$osFamily = PHP_OS_FAMILY;
if ($osFamily === 'Linux') {
return 'linux';
}
if ($osFamily === 'Darwin') {
return 'darwin';
}
throw new ParserException("Unsupported operating system: {$osFamily}");
}
/**
* Detect CPU architecture
*
* @return 'amd64'|'arm64'
* @throws ParserException
*/
private function detectArchitecture(): string
{
$machine = php_uname('m');
if (in_array($machine, ['x86_64', 'amd64', 'AMD64'], true)) {
return 'amd64';
}
if (in_array($machine, ['arm64', 'aarch64', 'ARM64'], true)) {
return 'arm64';
}
throw new ParserException("Unsupported architecture: {$machine}");
}
/**
* Process FFI result and convert to PublicCode object
*
* @param mixed $result FFI ParseResult pointer
* @return PublicCodeV0
* @throws ValidationException
* @throws ParserException
*/
private function processResult($result): PublicCodeV0
{
[$warnings, $validationWarnings] = $this->parseValidationWarnings(
$result->Warnings,
$result->WarningCount,
);
if ($result->ErrorCount > 0) {
[$errors, $validationErrors] = $this->parseValidationErrors(
$result->Errors,
$result->ErrorCount,
);
/** @phpstan-ignore-next-line */
$this->ffi->FreeResult($result);
throw new ValidationException(
message: implode("\n", $errors),
errors: $errors,
validationErrors: $validationErrors,
warnings: $warnings,
validationWarnings: $validationWarnings,
);
}
if ($result->Error !== null) {
$message = FFI::string($result->Error);
/** @phpstan-ignore-next-line */
$this->ffi->FreeResult($result);
throw new ParserException($message);
}
if ($result->Data === null) {
/** @phpstan-ignore-next-line */
$this->ffi->FreeResult($result);
throw new ParserException('No data returned from parser');
}
$jsonData = FFI::string($result->Data);
/** @phpstan-ignore-next-line */
$this->ffi->FreeResult($result);
$data = json_decode($jsonData, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new ParserException('Failed to decode JSON data: ' . json_last_error_msg());
}
return new PublicCodeV0($data, $warnings, $validationWarnings);
}
/**
* @param mixed $cArray FFI pointer to char** (may be null)
* @return array{list<string>, list<ValidationError>}
*/
private function parseValidationErrors($cArray, int $count): array
{
$messages = [];
$errors = [];
if ($cArray === null || $count === 0) {
return [$messages, $errors];
}
for ($i = 0; $i < $count; $i++) {
$payload = FFI::string($cArray[$i]);
$data = json_decode($payload, true);
if (is_array($data)) {
$error = ValidationError::fromArray($data);
$messages[] = (string) $error;
} else {
$error = ValidationError::fromString($payload);
$messages[] = $payload;
}
$errors[] = $error;
}
return [$messages, $errors];
}
/**
* @param mixed $cArray FFI pointer to char** (may be null)
* @return array{list<string>, list<ValidationWarning>}
*/
private function parseValidationWarnings($cArray, int $count): array
{
$messages = [];
$warnings = [];
if ($cArray === null || $count === 0) {
return [$messages, $warnings];
}
for ($i = 0; $i < $count; $i++) {
$payload = FFI::string($cArray[$i]);
$data = json_decode($payload, true);
if (is_array($data)) {
$warning = ValidationWarning::fromArray($data);
$messages[] = (string) $warning;
} else {
$warning = ValidationWarning::fromString($payload);
$messages[] = $payload;
}
$warnings[] = $warning;
}
return [$messages, $warnings];
}
}