Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 | 26x 1x 1x 20x 1x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 42x 42x 1x 1x 1x 1x 20x 20x 20x 20x 20x 20x 21x 20x 1x 4x 4x 1x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 23x 13x 13x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 20x 2x 20x 13x 13x 13x 13x 3x 13x 13x 1x 12x 12x 7x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 3x 1x 1x 1x 3x 9x 4x 2x 3x 109x 55x 54x 1x 1x 1x 9x 9x 9x 1x 8x 4x 4x 1x 1x 1x 19x 18x 15x 3x 3x 1x | // src/parser/PhpParser.ts
import * as fs from 'fs';
import type {
PhpClass,
PhpMethod,
PhpProperty,
PhpConstant,
PhpParameter,
} from '../types';
// We import glayzzle/php-parser dynamically to keep type coupling loose
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type PhpEngine = any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type AstNode = any;
// ─── Singleton Engine ─────────────────────────────────────────────────────
let _engine: PhpEngine | null = null;
function getEngine(): PhpEngine {
if (!_engine) {
// Lazy-load to keep extension activation instant
// eslint-disable-next-line @typescript-eslint/no-var-requires
const Engine = require('php-parser');
_engine = new Engine({
parser: {
extractDoc: true,
php7: true,
suppressErrors: true, // collect, don't throw
},
ast: {
withPositions: true,
withSource: false,
},
lexer: {
all_tokens: false,
comment_tokens: true,
},
});
}
return _engine;
}
// ─── Parse Result ─────────────────────────────────────────────────────────
export interface ParseResult {
classes: PhpClass[];
parseErrors: number;
namespace: string;
}
// ─── PhpParser ────────────────────────────────────────────────────────────
export class PhpParser {
/**
* Parse a PHP file on disk and extract structural metadata.
* Returns an empty result on failure rather than throwing.
*/
static parseFile(filePath: string): ParseResult {
try {
const source = fs.readFileSync(filePath, 'utf8');
return PhpParser.parseSource(source, filePath);
} catch {
return { classes: [], parseErrors: 1, namespace: '' };
}
}
/**
* Parse PHP source string directly (for virtual / unsaved files).
*/
static parseSource(source: string, filePath: string): ParseResult {
const engine = getEngine();
let ast: AstNode;
try {
ast = engine.parseCode(source, filePath);
} catch {
return { classes: [], parseErrors: 1, namespace: '' };
}
return PhpParser.extractFromAst(ast, filePath);
}
// ─── AST Traversal ────────────────────────────────────────────────────
private static extractFromAst(ast: AstNode, filePath: string): ParseResult {
const classes: PhpClass[] = [];
let namespace = '';
let parseErrors = 0;
const walk = (node: AstNode, currentNs: string): void => {
Iif (!node || typeof node !== 'object') { return; }
switch (node.kind) {
case 'namespace':
currentNs = PhpParser.resolveName(node.name);
for (const child of node.children ?? []) {
walk(child, currentNs);
}
break;
case 'class':
case 'interface':
case 'trait':
case 'enum':
try {
const cls = PhpParser.extractClass(node, currentNs, filePath);
classes.push(cls);
} catch {
parseErrors++;
}
break;
case 'program':
namespace = currentNs;
for (const child of node.children ?? []) {
walk(child, currentNs);
}
break;
default:
// recurse into arrays of children
for (const key of Object.keys(node)) {
const child = node[key];
Iif (Array.isArray(child)) {
for (const item of child) {
walk(item, currentNs);
}
}
}
break;
}
};
walk(ast, '');
return { classes, parseErrors, namespace };
}
// ─── Class Extraction ─────────────────────────────────────────────────
private static extractClass(node: AstNode, ns: string, filePath: string): PhpClass {
const name: string = PhpParser.resolveName(node.name);
const fqn = ns ? `${ns}\\${name}` : name;
const methods: PhpMethod[] = [];
const properties: PhpProperty[] = [];
const constants: PhpConstant[] = [];
const traits: string[] = [];
const implementsList: string[] = [];
for (const item of node.body ?? []) {
switch (item.kind) {
case 'method':
try { methods.push(PhpParser.extractMethod(item)); } catch { /* skip */ }
break;
case 'property':
case 'propertystatement':
try {
for (const prop of item.properties ?? [item]) {
properties.push(PhpParser.extractProperty(item, prop));
}
} catch { /* skip */ }
break;
case 'classconstant':
try {
for (const c of item.constants ?? []) {
constants.push(PhpParser.extractConstant(item, c));
}
} catch { /* skip */ }
break;
case 'traituse':
for (const trait of item.traits ?? []) {
traits.push(PhpParser.resolveName(trait));
}
break;
}
}
for (const impl of node.implements ?? []) {
implementsList.push(PhpParser.resolveName(impl));
}
return {
name,
namespace: ns,
fullyQualifiedName: fqn,
filePath,
lineNumber: node.loc?.start?.line ?? 0,
extends: node.extends ? PhpParser.resolveName(node.extends) : undefined,
implements: implementsList,
methods,
properties,
constants,
attributes: [],
docComment: node.leadingComments?.[0]?.value,
isAbstract: !!node.isAbstract,
isFinal: !!node.isFinal,
traits,
};
}
// ─── Method Extraction ────────────────────────────────────────────────
private static extractMethod(node: AstNode): PhpMethod {
const visibility = node.visibility ?? 'public';
const relation = PhpParser.detectRelationship(node.body);
const method: PhpMethod = {
name: PhpParser.resolveName(node.name),
visibility: this.normalizeVisibility(visibility),
isStatic: !!node.isStatic,
returnType: node.type ? PhpParser.resolveType(node.type) : undefined,
parameters: (node.arguments ?? []).map(PhpParser.extractParameter),
lineNumber: node.loc?.start?.line ?? 0,
attributes: [],
docComment: node.leadingComments?.[0]?.value,
isAbstract: !!node.isAbstract,
};
if (relation) {
method.relation = {
...relation,
name: method.name,
};
}
return method;
}
private static detectRelationship(bodyNode: AstNode): Omit<import('../types').RelationshipDefinition, 'name'> | undefined {
if (!bodyNode || bodyNode.kind !== 'block' || !Array.isArray(bodyNode.children)) {
return undefined;
}
const RELATION_METHODS = new Set([
'hasOne', 'hasMany', 'belongsTo', 'belongsToMany',
'hasManyThrough', 'hasOneThrough',
'morphTo', 'morphMany', 'morphOne', 'morphToMany'
]);
for (const stmt of bodyNode.children) {
if (stmt.kind === 'return' && stmt.expr && stmt.expr.kind === 'call') {
const call = stmt.expr;
Eif (call.what && call.what.kind === 'propertylookup') {
const prop = call.what;
Eif (prop.what && prop.what.kind === 'variable' && prop.what.name === 'this') {
const relType = prop.offset && prop.offset.name;
Eif (relType && RELATION_METHODS.has(relType)) {
let relatedModel = 'unknown';
Eif (call.arguments && call.arguments.length > 0) {
const firstArg = call.arguments[0];
if (firstArg.kind === 'staticlookup' && firstArg.what && firstArg.offset && firstArg.offset.name === 'class') {
const parts = firstArg.what.parts || [firstArg.what.name];
relatedModel = parts.filter(Boolean).join('\\') || 'unknown';
E} else if (firstArg.kind === 'classconstant' && firstArg.what) {
const parts = firstArg.what.parts || [firstArg.what.name];
relatedModel = parts.filter(Boolean).join('\\') || 'unknown';
} else if (firstArg.kind === 'string') {
relatedModel = firstArg.value || 'unknown';
}
}
let foreignKey: string | undefined = undefined;
let localKey: string | undefined = undefined;
if (call.arguments && call.arguments.length > 1) {
const secondArg = call.arguments[1];
Eif (secondArg.kind === 'string') {
foreignKey = secondArg.value;
}
}
if (call.arguments && call.arguments.length > 2) {
const thirdArg = call.arguments[2];
Eif (thirdArg.kind === 'string') {
localKey = thirdArg.value;
}
}
return {
type: relType as import('../types').RelationType,
relatedModel,
foreignKey,
localKey
};
}
}
}
}
}
return undefined;
}
// ─── Property Extraction ──────────────────────────────────────────────
private static extractProperty(stmt: AstNode, prop: AstNode): PhpProperty {
return {
name: PhpParser.resolveName(prop.name),
visibility: PhpParser.normalizeVisibility(stmt.visibility ?? 'public'),
isStatic: !!stmt.isStatic,
type: stmt.type ? PhpParser.resolveType(stmt.type) : undefined,
defaultValue: prop.value ? PhpParser.literalToString(prop.value) : undefined,
lineNumber: prop.loc?.start?.line ?? 0,
docComment: stmt.leadingComments?.[0]?.value,
};
}
// ─── Constant Extraction ──────────────────────────────────────────────
private static extractConstant(stmt: AstNode, c: AstNode): PhpConstant {
return {
name: PhpParser.resolveName(c.name),
value: c.value ? PhpParser.literalToString(c.value) : undefined,
visibility: PhpParser.normalizeVisibility(stmt.visibility ?? 'public'),
lineNumber: c.loc?.start?.line ?? 0,
};
}
// ─── Parameter Extraction ─────────────────────────────────────────────
private static extractParameter(param: AstNode): PhpParameter {
return {
name: PhpParser.resolveName(param.name),
type: param.type ? PhpParser.resolveType(param.type) : undefined,
defaultValue: param.value ? PhpParser.literalToString(param.value) : undefined,
isVariadic: !!param.variadic,
isNullable: !!param.nullable,
};
}
// ─── Helpers ──────────────────────────────────────────────────────────
private static resolveName(name: AstNode | string): string {
if (typeof name === 'string') { return name; }
if (!name) { return ''; }
if (name.name) { return PhpParser.resolveName(name.name); }
Iif (Array.isArray(name.resolution)) { return name.resolution.join('\\'); }
Iif (name.parts) { return name.parts.join('\\'); }
return String(name);
}
private static resolveType(typeNode: AstNode | string): string {
Iif (typeof typeNode === 'string') { return typeNode; }
Iif (!typeNode) { return 'mixed'; }
switch (typeNode.kind) {
case 'uniontype':
return (typeNode.types ?? []).map(PhpParser.resolveType).join('|');
case 'intersectiontype':
return (typeNode.types ?? []).map(PhpParser.resolveType).join('&');
case 'nullabletype':
return `?${PhpParser.resolveType(typeNode.type)}`;
default:
return PhpParser.resolveName(typeNode);
}
}
private static literalToString(node: AstNode): string {
Iif (!node) { return ''; }
if (node.kind === 'string') { return node.value ?? ''; }
Iif (node.kind === 'number') { return String(node.value); }
Iif (node.kind === 'boolean') { return node.raw ?? String(node.value); }
Eif (node.kind === 'nullkeyword') { return 'null'; }
if (node.kind === 'array') { return '[]'; }
return '';
}
private static normalizeVisibility(v: string): 'public' | 'protected' | 'private' {
if (v === 'private') { return 'private'; }
if (v === 'protected') { return 'protected'; }
return 'public';
}
// ─── Utility: Extract fillable/guarded arrays from class source ───────
static extractArrayProperty(cls: PhpClass, propName: string): string[] {
const prop = cls.properties.find((p) => p.name === propName);
if (!prop?.defaultValue) { return []; }
// The default value is already stringified to "[]"; for real values
// the RuntimeExtractor provides actual data. Return empty here as fallback.
return [];
}
}
|