-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeParser.php
More file actions
102 lines (86 loc) · 3.17 KB
/
CodeParser.php
File metadata and controls
102 lines (86 loc) · 3.17 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
<?php
namespace PhpParser;
use PhpParser\Node;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
use PhpParser\ParserFactory;
use PhpParser\Error;
/**
* CodeParser class for parsing PHP code
*
* This class uses nikic/php-parser to parse PHP code and generate
* a structured response according to the required format.
*/
class CodeParser
{
/**
* Parse PHP code and extract structured data
*
* @param string $code The PHP code to parse
* @param string $modifiedLines String representation of modified line ranges
* @param string $fileType The file type (expected to be 'php')
* @return array The structured data representing the parsed code
* @throws \Exception If there's an error parsing the code
*/
public function parseCode(string $code, string $modifiedLines, string $fileType): array
{
if ($fileType !== 'php') {
throw new \Exception("Unsupported file type: {$fileType}. Only PHP files are supported.");
}
// Parse the modified lines into a format we can work with
$modifiedLineRanges = $this->parseModifiedLines($modifiedLines);
// Create parser
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
try {
// Parse code
$ast = $parser->parse($code);
if ($ast === null) {
throw new \Exception("Failed to parse PHP code");
}
// Extract structured data from AST
$visitor = new CodeVisitor($code, $modifiedLineRanges);
$traverser = new NodeTraverser();
$traverser->addVisitor($visitor);
$traverser->traverse($ast);
// Format output according to required structure
$result = [
'methods' => $visitor->getMethods(),
'classes' => $visitor->getClasses(),
'imports' => $visitor->getImports()
];
// Clean up visitor to free memory for large files
$visitor->cleanup();
return $result;
} catch (Error $e) {
throw new \Exception("Parse error: {$e->getMessage()}");
}
}
/**
* Parse modified lines string into array of ranges
*
* @param string $modifiedLines String representing modified line ranges (e.g. "1-5,10-15")
* @return array Array of arrays with 'start' and 'end' keys
*/
private function parseModifiedLines(string $modifiedLines): array
{
$ranges = [];
$parts = explode(',', $modifiedLines);
foreach ($parts as $part) {
if (empty($part)) continue;
if (strpos($part, '-') !== false) {
list($start, $end) = explode('-', $part);
$ranges[] = [
'start' => (int) $start,
'end' => (int) $end
];
} else {
$lineNumber = (int) $part;
$ranges[] = [
'start' => $lineNumber,
'end' => $lineNumber
];
}
}
return $ranges;
}
}