|
| 1 | +// @ts-check |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Generates the command that is necessary to parse the given file. |
| 6 | + * |
| 7 | + * @param {string} file PHP configuration file path (relative or absolute). |
| 8 | + */ |
| 9 | +exports.command = function (file) { |
| 10 | + file = file.replace(/(["\s'$`\\])/g, '\\$1'); |
| 11 | + |
| 12 | + return `$(which php) -n -d display_errors=0 -r \'echo json_encode(include("${file}"));\'` |
| 13 | +}; |
| 14 | + |
| 15 | +/** |
| 16 | + * Parses the given file asynchronously, passing the result to the callback |
| 17 | + * function. In case of failure, it triggers the optional onError callback |
| 18 | + * to handle the error. |
| 19 | + * |
| 20 | + * @param {string} file PHP configuration file path (relative or absolute). |
| 21 | + * @param {function(object, Error=, string=, string=)} callback Function that will be triggered upon parsing the file. |
| 22 | + * @param {function(string)=} onError Function that will be triggered upon an error during the parsing of the file. |
| 23 | + */ |
| 24 | +exports.parse = function (file, callback, onError = (error) => {}) { |
| 25 | + let sh = require('child_process'); |
| 26 | + |
| 27 | + sh.exec(this.command(file), function (err, stdout, stderr) { |
| 28 | + try { |
| 29 | + let result = JSON.parse(stdout.trim()); |
| 30 | + |
| 31 | + if (result) { |
| 32 | + return callback(result, err, stdout, stderr); |
| 33 | + } |
| 34 | + |
| 35 | + throw new Error('Failed to parse the given file because: ' + result); |
| 36 | + } catch (error) { |
| 37 | + onError(error); |
| 38 | + } |
| 39 | + }); |
| 40 | +}; |
| 41 | + |
| 42 | +/** |
| 43 | + * Parses the given file synchronously, returning the result. |
| 44 | + * In case of failure, it triggers the optional onError callback to handle the error. |
| 45 | + * |
| 46 | + * @param {string} file PHP configuration file path (relative or absolute). |
| 47 | + * @param {function(*)=} onError Function that will be triggered upon an error during the parsing of the file. |
| 48 | + */ |
| 49 | +exports.parseSync = function (file, onError = (error) => {}) { |
| 50 | + let sh = require('child_process'); |
| 51 | + |
| 52 | + try { |
| 53 | + let result = JSON.parse( |
| 54 | + sh.execSync( |
| 55 | + this.command(file) |
| 56 | + ).toString().trim() |
| 57 | + ); |
| 58 | + |
| 59 | + if (result) { |
| 60 | + return result; |
| 61 | + } |
| 62 | + |
| 63 | + throw new Error('Failed to parse the given file because: ' + result); |
| 64 | + } catch (error) { |
| 65 | + return onError(error); |
| 66 | + } |
| 67 | +} |
0 commit comments