Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

feat(graph): PHP use App\… → resolved file→class-file import edges (breadth tier)

Shrish Dwivedife1a5374d371
diff --git a/src/graph/generic.ts b/src/graph/generic.ts
index 34606db2..7bd435b9 100644
--- a/src/graph/generic.ts
+++ b/src/graph/generic.ts
@@ -220,9 +220,43 @@ export function extractGeneric(rel: string, source: string, langName: string): E
// `use crate::…` is an in-crate module dependency.
if (langName === "c" || langName === "cpp") extractIncludes(tree.rootNode as TsNode, rel, rawEdges);
else if (langName === "rust") extractUses(tree.rootNode as TsNode, rel, rawEdges);
+ else if (langName === "php") extractPhpUses(tree.rootNode as TsNode, rel, rawEdges);
return { nodes, rawEdges };
}
+/** PHP `use App\Models\User;` → a file→class-file `imports` raw edge, one per imported
+ * name (a `{ … }` group expands to several). `use function`/`use const` are skipped —
+ * those name a symbol, not a PSR-4 class file. resolve.ts settles the fully-qualified
+ * name to the in-repo file by namespace suffix, and drops it when it can't. */
+function extractPhpUses(root: TsNode, rel: string, rawEdges: RawEdge[]): void {
+ const visit = (n: TsNode): void => {
+ if (n.type === "namespace_use_declaration") {
+ for (const fqn of phpUseNames(n.text)) rawEdges.push({ source: rel, relation: "imports", specifier: fqn, file: rel });
+ }
+ for (let i = 0; i < (n.namedChildCount ?? 0); i++) {
+ const c = n.namedChild?.(i);
+ if (c) visit(c);
+ }
+ };
+ visit(root);
+}
+
+/** The fully-qualified class names a PHP `use` declaration imports. Handles a plain
+ * `use A\B\C;`, a comma list `use A\B, C\D;`, a group `use A\B\{C, D};`, and `as` aliases;
+ * returns [] for `use function`/`use const` (symbol imports, not class files). */
+function phpUseNames(text: string): string[] {
+ let s = text.replace(/^\s*use\s+/, "").replace(/;\s*$/, "").trim();
+ if (/^(function|const)\b/.test(s)) return [];
+ const brace = s.indexOf("{");
+ if (brace >= 0) {
+ const prefix = s.slice(0, brace).replace(/\\\s*$/, "");
+ const inner = s.slice(brace + 1, s.lastIndexOf("}"));
+ return inner.split(",").map((m) => m.trim().replace(/\s+as\s+\w+$/i, "").trim()).filter(Boolean)
+ .map((m) => `${prefix}\\${m}`);
+ }
+ return s.split(",").map((c) => c.trim().replace(/\s+as\s+\w+$/i, "").trim()).filter(Boolean);
+}
+
/** Rust `use crate::a::b::Item` → a file→module `imports` raw edge whose specifier is the
* crate-relative module path (`a/b`). Only in-crate imports are captured; `std::`,
* `super::`, `self::`, external crates, and globs are skipped — resolve.ts settles the
diff --git a/src/graph/resolve.ts b/src/graph/resolve.ts
index b58cdcbc..a67eb2a1 100644
--- a/src/graph/resolve.ts
+++ b/src/graph/resolve.ts
@@ -62,6 +62,10 @@ export function resolveEdges(
// resolves to `<crate root>/a/b.rs` (or `.../a/b/mod.rs`), relative to the crate the
// importing file belongs to — so a workspace with several crates stays unambiguous.
const rustCrateRoots: string[] = [];
+ // PHP class resolution: a file's path-suffix (`Models/User.php`, `User.php`) → its file
+ // node ids. A `use App\Models\User` names a PSR-4 class whose file mirrors the namespace
+ // tail under some (unknown) source root, so the suffix is the portable key.
+ const phpFilesBySuffix = new Map<string, string[]>();
const hasGoModules = !!opts.goModules?.length;
for (const n of nodes) {
if (n.kind === "file") {
@@ -80,6 +84,10 @@ export function resolveEdges(
const parts = toPosixPath(n.path).split("/");
for (let i = 0; i < parts.length; i++) push(cFilesBySuffix, parts.slice(i).join("/"), n.id);
}
+ if (n.path.endsWith(".php")) {
+ const parts = toPosixPath(n.path).split("/");
+ for (let i = 0; i < parts.length; i++) push(phpFilesBySuffix, parts.slice(i).join("/"), n.id);
+ }
{
const p = toPosixPath(n.path);
if (p === "lib.rs" || p === "main.rs") rustCrateRoots.push("");
@@ -132,7 +140,9 @@ export function resolveEdges(
? resolveCInclude(e.specifier, e.file, byId, cFilesBySuffix)
: e.file.endsWith(".rs")
? resolveRustUse(e.specifier, e.file, byId, rustCrateRoots)
- : resolveImport(e.specifier, e.file, byId);
+ : e.file.endsWith(".php")
+ ? resolvePhpUse(e.specifier, phpFilesBySuffix)
+ : resolveImport(e.specifier, e.file, byId);
add(e.source, target, "imports", "extracted");
} else if (e.relation === "extends" || e.relation === "implements") {
const kinds: Kind[] = e.relation === "implements" ? ["interface"] : ["class", "interface"];
@@ -366,6 +376,25 @@ function resolveCInclude(
return spec; // system/out-of-repo/ambiguous — keep the string, do not guess
}
+/**
+ * Resolve a PHP `use` fully-qualified name (`App\Models\User`) to the in-repo class file.
+ * PSR-4 maps the namespace to a directory under some (unknown) source root and the class
+ * to a `<Class>.php` file, so we match the longest namespace-tail suffix that names exactly
+ * one file: `App/Models/User.php`, then `Models/User.php`, then `User.php`. The longest
+ * unique match wins; an ambiguous tail or a vendor/out-of-repo class stays the raw name.
+ */
+function resolvePhpUse(fqn: string, bySuffix: Map<string, string[]>): string {
+ const parts = fqn.split("\\").filter(Boolean);
+ if (parts.length === 0) return fqn;
+ for (let i = 0; i < parts.length; i++) {
+ const suffix = `${parts.slice(i).join("/")}.php`;
+ const hits = bySuffix.get(suffix);
+ if (hits && hits.length === 1) return hits[0];
+ if (hits && hits.length > 1) break; // ambiguous at the most specific level — do not guess
+ }
+ return fqn;
+}
+
/**
* Resolve a Rust `crate`-relative module path (`crate/a/b`, from `use crate::a::b::Item`)
* to the in-repo module file — `<crate root>/a/b.rs` or `<crate root>/a/b/mod.rs`, where
diff --git a/test/generic-extract.test.ts b/test/generic-extract.test.ts
index f3402fb0..f77c1f40 100644
--- a/test/generic-extract.test.ts
+++ b/test/generic-extract.test.ts
@@ -228,6 +228,43 @@ test("breadth tier: Rust use crate::… resolves to the in-repo module (longest-
assert.deepEqual(fromTest.map((e) => e.target), ["crate::error::Error"], "test-binary crate:: never resolves into the lib");
});
+// PHP `use App\Models\User` → a file→class-file import, resolved to the in-repo class by
+// the longest namespace-tail suffix (PSR-4 root is unknown). Groups expand; `use function`
+// is skipped; a vendor/unknown class or an ambiguous tail stays a string, never guessed.
+test("breadth tier: PHP use resolves to the class file (namespace-suffix, groups, drop-rather-than-guess)", async () => {
+ await warmGenericGrammars(["php"]);
+ const files: Record<string, string> = {
+ "src/Models/User.php": "<?php\nnamespace App\\Models;\nclass User {}\n",
+ "src/Http/Request.php": "<?php\nnamespace App\\Http;\nclass Request {}\n",
+ "src/Http/Response.php": "<?php\nnamespace App\\Http;\nclass Response {}\n",
+ "a/Dup.php": "<?php\nclass Dup {}\n",
+ "b/Dup.php": "<?php\nclass Dup {}\n",
+ "src/App.php":
+ "<?php\nnamespace App;\n" +
+ "use App\\Models\\User;\n" + // → src/Models/User.php
+ "use App\\Http\\{Request, Response};\n" + // group → both Http files
+ "use App\\Support\\Str as S;\n" + // in-namespace but no file → string
+ "use function App\\helpers\\tap;\n" + // function import → skipped, no edge
+ "use Psr\\Log\\LoggerInterface;\n" + // external vendor → string
+ "use Whatever\\Dup;\n" + // ambiguous basename → drop
+ "class App {}\n",
+ };
+ const nodes = [], raw = [];
+ for (const [rel, src] of Object.entries(files)) {
+ const r = extractGeneric(rel, src, "php");
+ nodes.push(...r.nodes); raw.push(...r.rawEdges);
+ }
+ const imports = resolveEdges(nodes, raw).filter((e) => e.relation === "imports" && e.source === "src/App.php");
+ const targets = imports.map((e) => e.target).sort();
+
+ assert.ok(targets.includes("src/Models/User.php"), "use App\\Models\\User → Models/User.php");
+ assert.ok(targets.includes("src/Http/Request.php") && targets.includes("src/Http/Response.php"), "group expands to both");
+ assert.ok(targets.includes("App\\Support\\Str"), "in-namespace but fileless → kept as string");
+ assert.ok(targets.includes("Psr\\Log\\LoggerInterface"), "external vendor class → kept as string");
+ assert.ok(targets.includes("Whatever\\Dup"), "ambiguous basename → kept as string, never guessed");
+ assert.ok(!targets.some((t) => /tap|helpers/.test(t)), "use function … is skipped (symbol import, not a class file)");
+});
+
test("buildGraph + checkGraph handle a breadth-tier (.rs) repo end-to-end", async () => {
const dir = mkdtempSync(join(tmpdir(), "graft-rust-"));
mkdirSync(join(dir, "src"), { recursive: true });