1- import { execSync } from 'node:child_process' ;
1+ import { execFile , execSync } from 'node:child_process' ;
22import * as fs from 'node:fs' ;
33import { tmpdir } from 'node:os' ;
4- import { resolve } from 'node:path' ;
4+ import * as path from 'node:path' ;
55
66import { PROJECT_ROOT } from '../../constants' ;
77import type { NodeTypeInheritingFromNodeAbstract } from '../types/types' ;
88
9- const defaultPhpParserBinaryPath = resolve (
9+ const defaultPhpParserBinaryPath = path . resolve (
1010 PROJECT_ROOT ,
1111 'vendor' ,
1212 'bin' ,
@@ -42,6 +42,46 @@ export class CliHelpers {
4242 ) as NodeTypeInheritingFromNodeAbstract [ ] ;
4343 }
4444
45+ /**
46+ * Using PHP version php phaser to Parse PHP File to AST (Async version)
47+ *
48+ * @param phpFilePath The PHP file path to parse
49+ * @returns Promise resolving to an AST in JSON format from php parser
50+ */
51+ public static async parsePhpFileToAstAsync (
52+ phpFilePath : string ,
53+ ) : Promise < NodeTypeInheritingFromNodeAbstract [ ] > {
54+ return new Promise ( ( resolve , reject ) => {
55+ execFile (
56+ PHP_PARSER_BINARY ,
57+ [ phpFilePath , '-j' ] ,
58+ {
59+ encoding : 'utf8' ,
60+ maxBuffer : MAX_BUFFER_SIZE_FOR_PHP_BINARY_OUTPUT ,
61+ } ,
62+ ( error , stdout ) => {
63+ if ( error ) {
64+ reject ( new Error ( `Failed to parse PHP file: ${ error . message } ` ) ) ;
65+ return ;
66+ }
67+
68+ try {
69+ const result = JSON . parse (
70+ stdout ,
71+ ) as NodeTypeInheritingFromNodeAbstract [ ] ;
72+ resolve ( result ) ;
73+ } catch ( parseError ) {
74+ reject (
75+ new Error (
76+ `Failed to parse JSON output: ${ parseError instanceof Error ? parseError . message : String ( parseError ) } ` ,
77+ ) ,
78+ ) ;
79+ }
80+ } ,
81+ ) ;
82+ } ) ;
83+ }
84+
4585 /**
4686 * Parse a PHP Code string to AST in JSON format
4787 * Because we are invoking PHP parser to parse the string
@@ -56,7 +96,7 @@ export class CliHelpers {
5696 /**
5797 * Temp file like "php-parser-{current time}.tmp" +
5898 */
59- const temporaryFilename = resolve (
99+ const temporaryFilename = path . resolve (
60100 tmpdir ( ) ,
61101 `${ currentDate . getTime ( ) } .${ currentDate . getMilliseconds ( ) } .tmp` ,
62102 ) ;
0 commit comments