-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
67 lines (57 loc) · 2.14 KB
/
index.js
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
// @ts-check
'use strict';
/**
* Generates the command that is necessary to parse the given file.
*
* @param {string} file PHP configuration file path (relative or absolute).
*/
exports.command = function (file) {
file = file.replace(/(["\s'$`\\])/g, '\\$1');
return `$(which php) -d display_errors=0 -r \'echo @json_encode(@include(__DIR__ . DIRECTORY_SEPARATOR . "${file}"));\'`
};
/**
* Parses the given file asynchronously, passing the result to the callback
* function. In case of failure, it triggers the optional onError callback
* to handle the error.
*
* @param {string} file PHP configuration file path (relative or absolute).
* @param {function(object, Error=, string=, string=)} callback Function that will be triggered upon parsing the file.
* @param {function(string)=} onError Function that will be triggered upon an error during the parsing of the file.
*/
exports.parse = function (file, callback, onError = (error) => {}) {
let sh = require('child_process');
sh.exec(this.command(file), function (err, stdout, stderr) {
try {
let result = JSON.parse(stdout.trim());
if (result) {
return callback(result, err, stdout, stderr);
}
throw new Error('Failed to parse the given file because: ' + result);
} catch (error) {
onError(error);
}
});
};
/**
* Parses the given file synchronously, returning the result.
* In case of failure, it triggers the optional onError callback to handle the error.
*
* @param {string} file PHP configuration file path (relative or absolute).
* @param {function(*)=} onError Function that will be triggered upon an error during the parsing of the file.
*/
exports.parseSync = function (file, onError = (error) => {}) {
let sh = require('child_process');
try {
let result = JSON.parse(
sh.execSync(
this.command(file)
).toString().trim()
);
if (result) {
return result;
}
throw new Error('Failed to parse the given file because: ' + result);
} catch (error) {
return onError(error);
}
}