@rightcapital/php-parser
Version:
TypeScript types for PHP Parser JSON representation
65 lines (64 loc) • 3.12 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CliHelpers = void 0;
const node_child_process_1 = require("node:child_process");
const fs = require("node:fs");
const node_os_1 = require("node:os");
const path = require("node:path");
const constants_1 = require("../../constants");
const defaultPhpParserBinaryPath = path.resolve(constants_1.PROJECT_ROOT, 'vendor', 'bin', 'php-parse');
const PHP_PARSER_BINARY = process.env.PHP_PARSER_BINARY_PATH || defaultPhpParserBinaryPath;
const MAX_BUFFER_SIZE_FOR_PHP_BINARY_OUTPUT = 10 * 1024 * 1024;
class CliHelpers {
static parsePhpFileToAst(phpFilePath) {
const parserOutputString = (0, node_child_process_1.execSync)(`${PHP_PARSER_BINARY} ${phpFilePath} -j`, {
encoding: 'utf8',
maxBuffer: MAX_BUFFER_SIZE_FOR_PHP_BINARY_OUTPUT,
stdio: ['pipe', 'pipe', 'ignore'],
});
return JSON.parse(parserOutputString);
}
static parsePhpFileToAstAsync(phpFilePath) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
(0, node_child_process_1.execFile)(PHP_PARSER_BINARY, [phpFilePath, '-j'], {
encoding: 'utf8',
maxBuffer: MAX_BUFFER_SIZE_FOR_PHP_BINARY_OUTPUT,
}, (error, stdout) => {
if (error) {
reject(new Error(`Failed to parse PHP file: ${error.message}`));
return;
}
try {
const result = JSON.parse(stdout);
resolve(result);
}
catch (parseError) {
reject(new Error(`Failed to parse JSON output: ${parseError instanceof Error ? parseError.message : String(parseError)}`));
}
});
});
});
}
static parsePhpCodeStringToAst(code) {
const currentDate = new Date();
const temporaryFilename = path.resolve((0, node_os_1.tmpdir)(), `${currentDate.getTime()}.${currentDate.getMilliseconds()}.tmp`);
fs.writeFileSync(temporaryFilename, code, 'utf8');
try {
return CliHelpers.parsePhpFileToAst(temporaryFilename);
}
finally {
fs.rmSync(temporaryFilename);
}
}
}
exports.CliHelpers = CliHelpers;