Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

fix(php): resolve imports by namespace

Hiro-Chibaea79b11596f3
diff --git a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts b/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
index c7754545..9dd909bb 100644
--- a/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
+++ b/core-ingestion/src/__tests__/patchBuilder.resolution.test.ts
@@ -109,6 +109,32 @@ describe('buildPatchWithResolution', () => {
}));
});
+ it('keeps same-named PHP constructor and function calls distinct', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use Vendor\\Package\\Helper;
+function Helper(): void {}
+function run(): void { new Helper(); Helper(); }
+ `,
+ )!;
+ const provider = parseFile(
+ '/repo/Vendor/Package/Helper.php',
+ '<?php namespace Vendor\\Package; class Helper {}',
+ )!;
+ const resolved = resolveEdges([consumer, provider]);
+ const patch = buildPatchWithResolution(consumer, 'hash', '', resolved);
+ const callEdges = patch.ops.filter(op => op.type === 'UpsertEdge' && op.predicate === 'CALLS');
+
+ expect(callEdges).toHaveLength(2);
+ expect(callEdges).toContainEqual(expect.objectContaining({
+ dst: nodeId('/repo/Vendor/Package/Helper.php', 'Helper'),
+ }));
+ expect(callEdges).toContainEqual(expect.objectContaining({
+ dst: nodeId('/repo/Consumer.php', 'Helper'),
+ }));
+ });
+
it('materialises external stub node for unresolved :: package calls', () => {
const file = '/repo/model.R';
const externalNodeId = nodeId('external://dplyr', 'dplyr::filter');
diff --git a/core-ingestion/src/__tests__/queries.php.test.ts b/core-ingestion/src/__tests__/queries.php.test.ts
index 468b68d4..94fb960b 100644
--- a/core-ingestion/src/__tests__/queries.php.test.ts
+++ b/core-ingestion/src/__tests__/queries.php.test.ts
@@ -22,6 +22,83 @@ use Vendor\\Contracts\\DomainService;
});
});
+ it('records PHP namespace scope for semicolon and braced declarations', () => {
+ const result = parseFile(
+ '/repo/Types.php',
+ `<?php
+namespace First\\Space;
+class FirstType {}
+namespace Second\\Space;
+class SecondType {}
+ `,
+ );
+ const braced = parseFile(
+ '/repo/Braced.php',
+ `<?php
+namespace Vendor\\Package { class User {} }
+namespace { class GlobalThing {} }
+ `,
+ );
+
+ expect(result?.entities.find(entity => entity.name === 'FirstType')?.packageScope).toBe('First\\Space');
+ expect(result?.entities.find(entity => entity.name === 'SecondType')?.packageScope).toBe('Second\\Space');
+ expect(braced?.entities.find(entity => entity.name === 'User')?.packageScope).toBe('Vendor\\Package');
+ expect(braced?.entities.find(entity => entity.name === 'GlobalThing')?.packageScope).toBe('');
+ });
+
+ it('distinguishes function and constant imports from class imports', () => {
+ const result = parseFile(
+ '/repo/Imports.php',
+ `<?php
+use Vendor\\Package\\User;
+use function Vendor\\Package\\helper;
+use const Vendor\\Package\\FLAG;
+ `,
+ );
+
+ expect(result?.relationships.filter(rel => rel.predicate === 'IMPORTS')).toEqual([
+ {
+ srcName: 'Imports.php',
+ dstName: 'User',
+ predicate: 'IMPORTS',
+ importRaw: 'Vendor\\Package\\User',
+ },
+ {
+ srcName: 'Imports.php',
+ dstName: 'helper',
+ predicate: 'IMPORTS',
+ importRaw: 'Vendor\\Package\\helper',
+ importKind: 'function',
+ },
+ {
+ srcName: 'Imports.php',
+ dstName: 'FLAG',
+ predicate: 'IMPORTS',
+ importRaw: 'Vendor\\Package\\FLAG',
+ importKind: 'const',
+ },
+ ]);
+ });
+
+ it('distinguishes PHP constructors from function and member calls', () => {
+ const result = parseFile(
+ '/repo/Calls.php',
+ `<?php
+function run(Service $service): void {
+ new Service();
+ helper();
+ $service->execute();
+}
+ `,
+ );
+
+ expect(result?.relationships.filter(rel => rel.predicate === 'CALLS')).toEqual([
+ { srcName: 'run', dstName: 'Service', predicate: 'CALLS', phpCallKind: 'constructor' },
+ { srcName: 'run', dstName: 'helper', predicate: 'CALLS', phpCallKind: 'function' },
+ { srcName: 'run', dstName: 'Service.execute', predicate: 'CALLS', phpCallKind: 'member' },
+ ]);
+ });
+
it('resolves calls through typed properties and method parameters', () => {
const result = parseFile(
'/repo/UseCase.php',
@@ -62,22 +139,24 @@ final class UseCase
expect(result).not.toBeNull();
expect(result!.relationships).toEqual(
expect.arrayContaining([
- { srcName: 'UseCase.create', dstName: 'DomainService.create', predicate: 'CALLS' },
- { srcName: 'UseCase.create', dstName: 'Repository.create', predicate: 'CALLS' },
- { srcName: 'UseCase.create', dstName: 'AuditLogger.write', predicate: 'CALLS' },
- { srcName: 'UseCase.create', dstName: 'Logger.write', predicate: 'CALLS' },
- { srcName: 'UseCase.create', dstName: 'UseCase.finish', predicate: 'CALLS' },
+ { srcName: 'UseCase.create', dstName: 'DomainService.create', predicate: 'CALLS', phpCallKind: 'member' },
+ { srcName: 'UseCase.create', dstName: 'Repository.create', predicate: 'CALLS', phpCallKind: 'member' },
+ { srcName: 'UseCase.create', dstName: 'AuditLogger.write', predicate: 'CALLS', phpCallKind: 'member' },
+ { srcName: 'UseCase.create', dstName: 'Logger.write', predicate: 'CALLS', phpCallKind: 'member' },
+ { srcName: 'UseCase.create', dstName: 'UseCase.finish', predicate: 'CALLS', phpCallKind: 'member' },
]),
);
expect(result!.relationships).not.toContainEqual({
srcName: 'UseCase.create',
dstName: 'create',
predicate: 'CALLS',
+ phpCallKind: 'member',
});
expect(result!.relationships).not.toContainEqual({
srcName: 'UseCase.create',
dstName: 'UseCase.create',
predicate: 'CALLS',
+ phpCallKind: 'member',
});
});
@@ -97,6 +176,7 @@ function run($service): void
srcName: 'run',
dstName: 'create',
predicate: 'CALLS',
+ phpCallKind: 'member',
});
});
@@ -125,9 +205,9 @@ final class Nullable
expect(result).not.toBeNull();
expect(result!.relationships).toEqual(
expect.arrayContaining([
- { srcName: 'Nullable.run', dstName: 'Service.create', predicate: 'CALLS' },
- { srcName: 'Nullable.run', dstName: 'Repository.find', predicate: 'CALLS' },
- { srcName: 'Nullable.run', dstName: 'Logger.write', predicate: 'CALLS' },
+ { srcName: 'Nullable.run', dstName: 'Service.create', predicate: 'CALLS', phpCallKind: 'member' },
+ { srcName: 'Nullable.run', dstName: 'Repository.find', predicate: 'CALLS', phpCallKind: 'member' },
+ { srcName: 'Nullable.run', dstName: 'Logger.write', predicate: 'CALLS', phpCallKind: 'member' },
]),
);
});
@@ -149,8 +229,8 @@ function run(Service $service, ?Logger $logger): void
expect(result).not.toBeNull();
expect(result!.relationships).toEqual(
expect.arrayContaining([
- { srcName: 'run', dstName: 'Service.create', predicate: 'CALLS' },
- { srcName: 'run', dstName: 'Logger.write', predicate: 'CALLS' },
+ { srcName: 'run', dstName: 'Service.create', predicate: 'CALLS', phpCallKind: 'member' },
+ { srcName: 'run', dstName: 'Logger.write', predicate: 'CALLS', phpCallKind: 'member' },
]),
);
});
@@ -176,6 +256,7 @@ final class Union
srcName: 'Union.run',
dstName: 'create',
predicate: 'CALLS',
+ phpCallKind: 'member',
});
});
});
diff --git a/core-ingestion/src/__tests__/resolveEdges.test.ts b/core-ingestion/src/__tests__/resolveEdges.test.ts
index 1a28b7c5..c4638e3f 100644
--- a/core-ingestion/src/__tests__/resolveEdges.test.ts
+++ b/core-ingestion/src/__tests__/resolveEdges.test.ts
@@ -240,7 +240,7 @@ describe('resolveEdges', () => {
new Map([
[
targetPath,
- '<?php interface DomainService { public function create(): void; }',
+ '<?php namespace App\\Contracts; interface DomainService { public function create(): void; }',
],
]),
);
@@ -256,6 +256,270 @@ describe('resolveEdges', () => {
});
});
+ it('does not resolve an imported PHP class to the same name in another namespace', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use Vendor\\Package\\User;
+function run(User $user): void { new User(); $user->save(); }
+ `,
+ )!;
+ const wrong = parseFile(
+ '/repo/App/User.php',
+ `<?php
+namespace App;
+class User { public function save(): void {} }
+ `,
+ )!;
+
+ expect(resolveEdges([consumer, wrong])).toEqual([]);
+ });
+
+ it('resolves PHP class imports, references, and calls by exact FQCN', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use Vendor\\Package\\User;
+function run(User $user): void { new User(); $user->save(); }
+ `,
+ )!;
+ const intended = parseFile(
+ '/repo/Vendor/Package/User.php',
+ `<?php
+namespace Vendor\\Package;
+class User { public function save(): void {} }
+ `,
+ )!;
+ const wrong = parseFile(
+ '/repo/App/User.php',
+ `<?php
+namespace App;
+class User { public function save(): void {} }
+ `,
+ )!;
+
+ const resolved = resolveEdges([consumer, intended, wrong]);
+ expect(resolved).toContainEqual({
+ srcFilePath: '/repo/Consumer.php',
+ srcName: 'Consumer.php',
+ dstFilePath: '/repo/Vendor/Package/User.php',
+ dstName: 'User',
+ dstQualifiedKey: 'User.php',
+ predicate: 'IMPORTS',
+ confidence: 0.9,
+ });
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/Consumer.php',
+ dstFilePath: '/repo/Vendor/Package/User.php',
+ dstName: 'User',
+ dstQualifiedKey: 'User',
+ predicate: 'REFERENCES',
+ confidence: 0.9,
+ }));
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/Consumer.php',
+ dstFilePath: '/repo/Vendor/Package/User.php',
+ dstName: 'User',
+ dstQualifiedKey: 'User',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ }));
+ expect(resolved).toContainEqual(expect.objectContaining({
+ srcFilePath: '/repo/Consumer.php',
+ dstFilePath: '/repo/Vendor/Package/User.php',
+ dstName: 'User.save',
+ dstQualifiedKey: 'User.save',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ }));
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/App/User.php')).toBe(false);
+ });
+
+ it('resolves PHP class names case-insensitively', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use vendor\\package\\USER;
+function run(user $user): void { new user(); $user->save(); }
+ `,
+ )!;
+ const provider = parseFile(
+ '/repo/Vendor/Package/User.php',
+ `<?php
+namespace Vendor\\Package;
+class User { public function save(): void {} }
+ `,
+ )!;
+
+ const resolved = resolveEdges([consumer, provider]);
+ expect(resolved.filter(edge => edge.dstFilePath === '/repo/Vendor/Package/User.php')).toHaveLength(4);
+ });
+
+ it('keeps PHP function and constant imports on their existing resolution path', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use function Vendor\\Package\\helper;
+use const Vendor\\Package\\FLAG;
+function run(): void { helper(); }
+ `,
+ )!;
+ const helper = parseFile(
+ '/repo/Vendor/Package/helper.php',
+ `<?php
+namespace Vendor\\Package;
+function helper(): void {}
+ `,
+ )!;
+ const flag = parseFile('/repo/Vendor/Package/FLAG.php', '<?php const FLAG = 1;')!;
+
+ const resolved = resolveEdges([consumer, helper, flag]);
+ expect(resolved).toContainEqual(expect.objectContaining({
+ dstFilePath: '/repo/Vendor/Package/helper.php',
+ predicate: 'IMPORTS',
+ confidence: 0.9,
+ }));
+ expect(resolved).toContainEqual(expect.objectContaining({
+ dstFilePath: '/repo/Vendor/Package/helper.php',
+ predicate: 'CALLS',
+ confidence: 0.9,
+ }));
+ expect(resolved).toContainEqual(expect.objectContaining({
+ dstFilePath: '/repo/Vendor/Package/FLAG.php',
+ predicate: 'IMPORTS',
+ confidence: 0.9,
+ }));
+ });
+
+ it('does not treat a namespaced function as an imported class provider', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use Vendor\\Package\\User;
+function run(): void { new User(); }
+ `,
+ )!;
+ const functionOnly = parseFile(
+ '/repo/Vendor/Package/User.php',
+ `<?php
+namespace Vendor\\Package;
+function User(): void {}
+ `,
+ )!;
+
+ expect(resolveEdges([consumer, functionOnly])).toEqual([]);
+ });
+
+ it('does not resolve a same-named PHP function call as an imported constructor', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use Vendor\\Package\\Helper;
+function Helper(): void {}
+function run(): void { Helper(); }
+ `,
+ )!;
+ const provider = parseFile(
+ '/repo/Vendor/Package/Helper.php',
+ '<?php namespace Vendor\\Package; class Helper {}',
+ )!;
+
+ const resolved = resolveEdges([consumer, provider]);
+ expect(resolved.some(edge =>
+ edge.predicate === 'CALLS' && edge.dstFilePath === '/repo/Vendor/Package/Helper.php'
+ )).toBe(false);
+ });
+
+ it('keeps a same-named PHP function import separate from a class import', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+use Vendor\\Package\\Helper;
+use function Other\\helper;
+function run(): void { helper(); }
+ `,
+ )!;
+ const typeProvider = parseFile(
+ '/repo/Vendor/Package/Helper.php',
+ '<?php namespace Vendor\\Package; class Helper {}',
+ )!;
+ const functionProvider = parseFile(
+ '/repo/Other/helper.php',
+ '<?php namespace Other; function helper(): void {}',
+ )!;
+
+ const resolved = resolveEdges([consumer, typeProvider, functionProvider]);
+ expect(resolved.filter(edge => edge.dstFilePath === '/repo/Other/helper.php')).toHaveLength(2);
+ expect(resolved.some(edge =>
+ edge.predicate === 'CALLS' && edge.dstFilePath === '/repo/Vendor/Package/Helper.php'
+ )).toBe(false);
+ });
+
+ it('resolves a PHP import from the global namespace exactly', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+namespace App;
+use GlobalUser;
+function run(GlobalUser $user): void { new GlobalUser(); $user->save(); }
+ `,
+ )!;
+ const intended = parseFile(
+ '/repo/GlobalUser.php',
+ '<?php class GlobalUser { public function save(): void {} }',
+ )!;
+ const wrong = parseFile(
+ '/repo/Other/GlobalUser.php',
+ '<?php namespace Other; class GlobalUser { public function save(): void {} }',
+ )!;
+
+ const resolved = resolveEdges([consumer, intended, wrong]);
+ expect(resolved.filter(edge => edge.dstFilePath === '/repo/GlobalUser.php')).toHaveLength(4);
+ expect(resolved.some(edge => edge.dstFilePath === '/repo/Other/GlobalUser.php')).toBe(false);
+ });
+
+ it('does not exact-resolve duplicate PHP type names within one file', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ '<?php use Vendor\\Package\\User; function run(): void { new User(); }',
+ )!;
+ const provider = parseFile(
+ '/repo/Types.php',
+ `<?php
+namespace Vendor\\Package { class User {} }
+namespace Other { class User {} }
+ `,
+ )!;
+
+ expect(resolveEdges([consumer, provider])).toEqual([]);
+ });
+
+ it('does not exact-resolve conflicting PHP imports scoped to different namespaces', () => {
+ const consumer = parseFile(
+ '/repo/Consumer.php',
+ `<?php
+namespace First {
+ use Vendor\\One\\User;
+ function run(User $user): void { new User(); $user->save(); }
+}
+namespace Second {
+ use Vendor\\Two\\User;
+ function execute(User $user): void { new User(); $user->save(); }
+}
+ `,
+ )!;
+ const first = parseFile(
+ '/repo/Vendor/One/User.php',
+ '<?php namespace Vendor\\One; class User { public function save(): void {} }',
+ )!;
+ const second = parseFile(
+ '/repo/Vendor/Two/User.php',
+ '<?php namespace Vendor\\Two; class User { public function save(): void {} }',
+ )!;
+
+ expect(resolveEdges([consumer, first, second])).toEqual([]);
+ });
+
it('resolves a TypeScript call when the imported definition is outside the parse batch', () => {
const caller = fileResult(
'/repo/consumer.ts',
diff --git a/core-ingestion/src/index.ts b/core-ingestion/src/index.ts
index 006c9c66..217bea9c 100644
--- a/core-ingestion/src/index.ts
+++ b/core-ingestion/src/index.ts
@@ -134,12 +134,9 @@ export interface ParsedEntity {
/** Direct enclosing class/interface/trait, if any (undefined for file-level entities). */
container?: string;
/**
- * Package name for languages that group entities into namespaces (currently
- * Go only). Used by downstream layers to prefix qualifiedName so the symbol
- * table indexes entities under their fully-qualified path. Without this,
- * bare-name resolution at edge-resolver collides between packages (e.g.
- * kubernetes has 191 distinct `addKnownTypes` functions, one per API group)
- * and CALL targets are picked non-deterministically.
+ * Package or namespace name for languages that group entities. Used by
+ * downstream resolution to distinguish identically named declarations and
+ * index entities under their fully-qualified path.
*/
packageScope?: string;
}
@@ -172,6 +169,12 @@ export interface ParsedRelationship {
// that happens to flatten to the same stem ("core"). Absent on non-import rels
// and on dotted/symbol imports where dstName is already the full identifier.
importRaw?: string;
+ /** PHP namespace import category. Absent for all other languages. */
+ importKind?: 'type' | 'function' | 'const';
+ /** PHP aliases need binding metadata before exact FQCN resolution is safe. */
+ importAliased?: boolean;
+ /** PHP call shape used to distinguish constructors from same-named functions. */
+ phpCallKind?: 'constructor' | 'function' | 'member' | 'static';
/**
* JS/TS only: whether this identifier use is lexically bound to its matching
* import. False means a parameter or local declaration shadows that import.
@@ -1983,6 +1986,23 @@ function unwrapRustCfgMacros(source: string): string {
// Main parse function
// ---------------------------------------------------------------------------
+function phpNamespaceForNode(rootNode: any, node: any): string | undefined {
+ for (let current = node.parent; current; current = current.parent) {
+ if (current.type === 'namespace_definition') {
+ return current.childForFieldName?.('name')?.text?.replace(/\s+/g, '') ?? '';
+ }
+ }
+
+ let active: string | undefined;
+ for (let i = 0; i < rootNode.namedChildCount; i++) {
+ const child = rootNode.namedChild(i);
+ if (!child || child.startIndex >= node.startIndex) break;
+ if (child.type !== 'namespace_definition' || child.childForFieldName?.('body')) continue;
+ active = child.childForFieldName?.('name')?.text?.replace(/\s+/g, '') ?? '';
+ }
+ return active;
+}
+
export function parseFile(filePath: string, source: string): FileParseResult | null {
const language = detectLanguageForSource(filePath, source);
if (!language) return null;
@@ -2198,7 +2218,11 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
lineEnd,
language,
container: effectiveContainer,
- packageScope: goPackage,
+ packageScope: goPackage ?? (
+ language === SupportedLanguages.PHP
+ ? phpNamespaceForNode(tree.rootNode, defNode)
+ : undefined
+ ),
});
pendingChunks.push({
@@ -2456,8 +2480,26 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
// Preserve the raw specifier (./core vs @nestjs/core) for the multi-repo
// dependency gate; modName remains the flattened stem used everywhere else.
const importRaw = unwrapImportSpecifier(importSource.node.text);
+ const importNode = match.captures.find((c: any) => c.name === 'import')?.node;
+ const phpImportText = language === SupportedLanguages.PHP ? importNode?.text ?? '' : '';
+ const importKind = language === SupportedLanguages.PHP
+ ? /^use\s+function\b/i.test(phpImportText)
+ ? 'function' as const
+ : /^use\s+const\b/i.test(phpImportText)
+ ? 'const' as const
+ : undefined
+ : undefined;
entities.push({ name: modName, kind: 'module', lineStart: importSource.node.startPosition.row + 1, lineEnd: importSource.node.startPosition.row + 1, language });
- relationships.push({ srcName: fileName, dstName: modName, predicate: 'IMPORTS', importRaw });
+ relationships.push({
+ srcName: fileName,
+ dstName: modName,
+ predicate: 'IMPORTS',
+ importRaw,
+ ...(importKind ? { importKind } : {}),
+ ...(language === SupportedLanguages.PHP && /\s+as\s+/i.test(phpImportText)
+ ? { importAliased: true }
+ : {}),
+ });
}
continue;
}
@@ -2490,6 +2532,16 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
if (callName) {
const callee = callName.node.text;
if (!callee || callee.length <= 1) continue;
+ const phpCallKind = language === SupportedLanguages.PHP
+ ? callName.node.parent?.type === 'object_creation_expression'
+ ? 'constructor' as const
+ : callName.node.parent?.type === 'member_call_expression' ||
+ callName.node.parent?.type === 'nullsafe_member_call_expression'
+ ? 'member' as const
+ : callName.node.parent?.type === 'scoped_call_expression'
+ ? 'static' as const
+ : 'function' as const
+ : undefined;
// If a _qualifier capture is present (field_expression / stable_identifier
// patterns like NodeKind.Decision, or Python attribute calls like
@@ -2662,9 +2714,15 @@ export function parseFile(filePath: string, source: string): FileParseResult | n
recordJsTsImportUse('CALLS', caller, effectiveCallee, callName.node, callee);
}
- if (!seen.has(effectiveCallee)) {
- seen.add(effectiveCallee);
- relationships.push({ srcName: caller, dstName: effectiveCallee, predicate: 'CALLS' });
+ const callKey = phpCallKind ? `${phpCallKind}:${effectiveCallee}` : effectiveCallee;
+ if (!seen.has(callKey)) {
+ seen.add(callKey);
+ relationships.push({
+ srcName: caller,
+ dstName: effectiveCallee,
+ predicate: 'CALLS',
+ ...(phpCallKind ? { phpCallKind } : {}),
+ });
}
continue;
}
@@ -2804,6 +2862,7 @@ export interface ResolvedEdge {
dstQualifiedKey: string; // qualified key used for nodeId in the defining file
predicate: string; // "CALLS" | "EXTENDS"
confidence: number; // 0.9 import-scoped | 0.8 transitive | 0.5 global
+ phpCallKind?: ParsedRelationship['phpCallKind'];
}
// ---------------------------------------------------------------------------
@@ -2815,6 +2874,28 @@ function qualifiedKey(e: ParsedEntity): string {
return e.container ? `${e.container}.${e.name}` : e.name;
}
+const PHP_TYPE_KINDS = new Set(['class', 'interface', 'trait', 'enum']);
+
+function phpTypeFqcn(entity: ParsedEntity): string | undefined {
+ if (entity.language !== SupportedLanguages.PHP || !PHP_TYPE_KINDS.has(entity.kind) || entity.container) {
+ return undefined;
+ }
+ const namespace = entity.packageScope?.replace(/^\\+|\\+$/g, '');
+ return `${namespace ? `${namespace}\\` : ''}${entity.name}`.toLowerCase();
+}
+
+function ambiguousPhpTypeNames(entities: ParsedEntity[]): Set<string> {
+ const counts = new Map<string, number>();
+ for (const entity of entities) {
+ if (entity.language !== SupportedLanguages.PHP || !PHP_TYPE_KINDS.has(entity.kind) || entity.container) {
+ continue;
+ }
+ const name = entity.name.toLowerCase();
+ counts.set(name, (counts.get(name) ?? 0) + 1);
+ }
+ return new Set([...counts].filter(([, count]) => count > 1).map(([name]) => name));
+}
+
/**
* Given a file's qualified-key map and a plain callee name, return the single
* unambiguous qualified key, or null if the name maps to 0 or >1 entities.
@@ -2831,6 +2912,24 @@ function bestQKey(
return qks.length === 1 ? qks[0] : null;
}
+function bestPhpQKey(
+ fileQKeys: Map<string, Map<string, string[]>>,
+ filePath: string,
+ plainName: string,
+ preferredQKey?: string,
+): string | null {
+ const qks = [...new Set(
+ [...(fileQKeys.get(filePath) ?? [])]
+ .filter(([name]) => name.toLowerCase() === plainName.toLowerCase())
+ .flatMap(([, keys]) => keys),
+ )];
+ if (preferredQKey) {
+ const preferred = qks.find(key => key.toLowerCase() === preferredQKey.toLowerCase());
+ if (preferred) return preferred;
+ }
+ return qks.length === 1 ? qks[0] : null;
+}
+
// ---------------------------------------------------------------------------
// Global resolution index — pre-scan for cross-batch edge resolution
// ---------------------------------------------------------------------------
@@ -2845,6 +2944,7 @@ export interface GlobalResolutionIndex {
packageToFiles: Map<string, string[]>;
goPkgDirToFiles: Map<string, string[]>;
goPkgPathToFiles: Map<string, string[]>;
+ phpFqcnToTypes?: Map<string, Array<{ filePath: string; typeName: string }>>;
}
/**
@@ -2869,6 +2969,7 @@ export function buildGlobalResolutionIndex(
const packageToFiles = new Map<string, string[]>();
const goPkgDirToFiles = new Map<string, string[]>();
const goPkgPathToFiles = new Map<string, string[]>();
+ const phpFqcnToTypes = new Map<string, Array<{ filePath: string; typeName: string }>>();
for (const fp of filePaths) {
const ext = nodePath.extname(fp);
@@ -3025,11 +3126,20 @@ export function buildGlobalResolutionIndex(
const parsed = preParsed?.get(fp) ?? parseFile(fp, src);
if (!parsed) continue;
const qkMap = new Map<string, string[]>();
+ const ambiguousTypes = ambiguousPhpTypeNames(parsed.entities);
for (const e of parsed.entities) {
if (e.kind === 'file' || e.kind === 'module') continue;
const list = qkMap.get(e.name) ?? [];
list.push(qualifiedKey(e));
qkMap.set(e.name, list);
+ const fqcn = phpTypeFqcn(e);
+ if (fqcn && !ambiguousTypes.has(e.name.toLowerCase())) {
+ const entries = phpFqcnToTypes.get(fqcn) ?? [];
+ if (!entries.some(entry => entry.filePath === fp && entry.typeName === e.name)) {
+ entries.push({ filePath: fp, typeName: e.name });
+ }
+ phpFqcnToTypes.set(fqcn, entries);
+ }
}
if (qkMap.size > 0) {
fileQKeys.set(fp, qkMap);
@@ -3078,6 +3188,7 @@ export function buildGlobalResolutionIndex(
packageToFiles,
goPkgDirToFiles,
goPkgPathToFiles,
+ phpFqcnToTypes,
};
}
@@ -3202,6 +3313,26 @@ export function resolveEdges(
if (!m.has(b.local)) m.set(b.local, b.imported);
}
}
+ const phpFqcnImportsByLocal = new Map<string, Map<string, string | null>>();
+ for (const result of results) {
+ if (result.language !== SupportedLanguages.PHP) continue;
+ for (const rel of result.relationships) {
+ if (
+ rel.predicate !== 'IMPORTS' ||
+ rel.importKind === 'function' ||
+ rel.importKind === 'const' ||
+ rel.importAliased ||
+ typeof rel.importRaw !== 'string'
+ ) continue;
+ const fqcn = rel.importRaw.replace(/^\\+/, '').toLowerCase();
+ const local = fqcn.split('\\').pop();
+ if (!local) continue;
+ const imports = phpFqcnImportsByLocal.get(result.filePath) ?? new Map<string, string | null>();
+ if (!imports.has(local)) imports.set(local, fqcn);
+ else if (imports.get(local) !== fqcn) imports.set(local, null);
+ phpFqcnImportsByLocal.set(result.filePath, imports);
+ }
+ }
// Cross-repo dependency graph: repo R depends on repo D when any file in R
// imports a module published by D. Built from the raw IMPORTS relationships.
const repoOf = opts?.repoOf;
@@ -3339,6 +3470,24 @@ export function resolveEdges(
fileHasSymbol.set(fp, new Set(qkMap.keys()));
}
+ const phpFqcnToTypes = new Map<string, Array<{ filePath: string; typeName: string }>>();
+ for (const [fqcn, entries] of globalIndex?.phpFqcnToTypes ?? []) {
+ phpFqcnToTypes.set(fqcn, [...entries]);
+ }
+ for (const result of results) {
+ if (result.language !== SupportedLanguages.PHP) continue;
+ const ambiguousTypes = ambiguousPhpTypeNames(result.entities);
+ for (const entity of result.entities) {
+ const fqcn = phpTypeFqcn(entity);
+ if (!fqcn || ambiguousTypes.has(entity.name.toLowerCase())) continue;
+ const entries = phpFqcnToTypes.get(fqcn) ?? [];
+ if (!entries.some(entry => entry.filePath === result.filePath && entry.typeName === entity.name)) {
+ entries.push({ filePath: result.filePath, typeName: entity.name });
+ }
+ phpFqcnToTypes.set(fqcn, entries);
+ }
+ }
+
// resultsByPath: O(1) lookup replacing results.find() in transitive import loop
const resultsByPath = new Map<string, FileParseResult>(results.map(r => [r.filePath, r]));
@@ -3847,6 +3996,28 @@ export function resolveEdges(
);
}
+ function importedPhpType(srcFilePath: string, rel: ParsedRelationship): {
+ entries: Array<{ filePath: string; typeName: string }>;
+ memberName?: string;
+ } | undefined {
+ if (rel.predicate === 'IMPORTS' && (rel.importKind === 'function' || rel.importKind === 'const')) {
+ return undefined;
+ }
+ const parts = rel.dstName.split('.');
+ if (rel.predicate === 'CALLS' && parts.length === 1 && rel.phpCallKind !== 'constructor') {
+ return undefined;
+ }
+ const imports = phpFqcnImportsByLocal.get(srcFilePath);
+ const local = parts[0].toLowerCase();
+ if (!imports?.has(local)) return undefined;
+ const fqcn = imports.get(local);
+ if (!fqcn) return { entries: [] };
+ return {
+ entries: phpFqcnToTypes.get(fqcn) ?? [],
+ memberName: parts.length > 1 ? parts[parts.length - 1] : undefined,
+ };
+ }
+
const resolved: ResolvedEdge[] = [];
for (const result of results) {
@@ -3860,6 +4031,13 @@ export function resolveEdges(
for (const rel of result.relationships) {
if (rel.predicate !== 'IMPORTS') continue;
if (pythonHasRelativeModuleImport && rel.importRaw === undefined) continue;
+ const phpType = srcLanguage === SupportedLanguages.PHP
+ ? importedPhpType(srcFilePath, rel)
+ : undefined;
+ if (phpType) {
+ for (const entry of phpType.entries) importedFilePaths.add(entry.filePath);
+ continue;
+ }
for (const fp of resolveImportTargets(srcFilePath, srcLanguage, rel.dstName, rel.importRaw)) {
importedFilePaths.add(fp);
}
@@ -3888,6 +4066,27 @@ export function resolveEdges(
// name ("ClaimId"), find files registered under that package, then find
// the one that defines the entity.
if (rel.predicate === 'IMPORTS') {
+ const phpType = srcLanguage === SupportedLanguages.PHP
+ ? importedPhpType(srcFilePath, rel)
+ : undefined;
+ if (phpType) {
+ if (phpType.entries.length === 1) {
+ const fp = phpType.entries[0].filePath;
+ resolved.push({
+ srcFilePath,
+ srcName: rel.srcName,
+ dstFilePath: fp,
+ dstName: rel.dstName,
+ dstQualifiedKey: fileEntityName(fp),
+ predicate: 'IMPORTS',
+ confidence: 0.9,
+ });
+ stats.resolvedImport++;
+ } else if (phpType.entries.length > 1) {
+ stats.skippedAmbiguous++;
+ }
+ continue;
+ }
if (result.language === SupportedLanguages.Scala || result.language === SupportedLanguages.Java) {
const dstName = rel.dstName;
const lastDot = dstName.lastIndexOf('.');
@@ -3959,6 +4158,36 @@ export function resolveEdges(
// fall through to Tier 1b → Tier 2 → Tier 3 below
}
+ const phpType = srcLanguage === SupportedLanguages.PHP
+ ? importedPhpType(srcFilePath, rel)
+ : undefined;
+ if (phpType) {
+ if (phpType.entries.length === 1) {
+ const entry = phpType.entries[0];
+ const plainName = phpType.memberName ?? entry.typeName;
+ const preferredQKey = phpType.memberName
+ ? `${entry.typeName}.${phpType.memberName}`
+ : entry.typeName;
+ const dstQualifiedKey = bestPhpQKey(fileQKeys, entry.filePath, plainName, preferredQKey);
+ if (dstQualifiedKey !== null) {
+ resolved.push({
+ srcFilePath,
+ srcName: rel.srcName,
+ dstFilePath: entry.filePath,
+ dstName: rel.dstName,
+ dstQualifiedKey,
+ predicate: rel.predicate,
+ confidence: 0.9,
+ ...(rel.phpCallKind ? { phpCallKind: rel.phpCallKind } : {}),
+ });
+ stats.resolvedQualifier++;
+ }
+ } else if (phpType.entries.length > 1) {
+ stats.skippedAmbiguous++;
+ }
+ continue;
+ }
+
const origDstName = rel.dstName;
// Z: resolve a renamed-import call by the provider's public symbol, but keep the
// ORIGINAL local name on the emitted edge (buildPatchWithResolution maps the edge
diff --git a/core-ingestion/src/patch-builder.ts b/core-ingestion/src/patch-builder.ts
index bf5db089..114f6eb9 100644
--- a/core-ingestion/src/patch-builder.ts
+++ b/core-ingestion/src/patch-builder.ts
@@ -478,7 +478,8 @@ export function buildPatchWithResolution(
const edgeResolution = new Map<string, { dstFilePath: string; dstQualifiedKey: string }>();
for (const edge of resolvedEdges) {
if (edge.srcFilePath !== result.filePath) continue;
- edgeResolution.set(`${edge.srcName}:${edge.predicate}:${edge.dstName}`, {
+ const callKind = edge.phpCallKind ? `:${edge.phpCallKind}` : '';
+ edgeResolution.set(`${edge.srcName}:${edge.predicate}:${edge.dstName}${callKind}`, {
dstFilePath: edge.dstFilePath,
dstQualifiedKey: edge.dstQualifiedKey,
});
@@ -616,6 +617,11 @@ export function buildPatchWithResolution(
}
const seenExternalNodes2 = new Set<string>();
+ const relationshipShapeCounts = new Map<string, number>();
+ for (const relationship of relationships) {
+ const key = `${relationship.srcName}:${relationship.predicate}:${relationship.dstName}`;
+ relationshipShapeCounts.set(key, (relationshipShapeCounts.get(key) ?? 0) + 1);
+ }
for (const r of relationships) {
const srcKey = resolveKey(r.srcName);
const dstKey = r.predicate === 'CONTAINS'
@@ -623,12 +629,18 @@ export function buildPatchWithResolution(
: resolveKey(r.dstName);
let dstNodeId: string;
- const resolutionKey = `${r.srcName}:${r.predicate}:${r.dstName}`;
-
- if (edgeResolution.has(resolutionKey)) {
+ const baseResolutionKey = `${r.srcName}:${r.predicate}:${r.dstName}`;
+ const resolutionKey = r.phpCallKind
+ ? `${baseResolutionKey}:${r.phpCallKind}`
+ : baseResolutionKey;
+ const matchedResolutionKey = edgeResolution.has(resolutionKey)
+ ? resolutionKey
+ : baseResolutionKey;
+
+ if (edgeResolution.has(matchedResolutionKey)) {
// Cross-file resolved — use the defining file's nodeId, in the dst repo's
// workspace namespace (matters only for cross-repo edges in a co-ingest).
- const { dstFilePath, dstQualifiedKey } = edgeResolution.get(resolutionKey)!;
+ const { dstFilePath, dstQualifiedKey } = edgeResolution.get(matchedResolutionKey)!;
dstNodeId = dstNodeIdInRepo(dstFilePath, dstQualifiedKey);
} else if (r.predicate === 'CALLS' && dstKey.includes('::') && !allQKeys2.has(dstKey)) {
const sep = dstKey.indexOf('::');
@@ -650,9 +662,12 @@ export function buildPatchWithResolution(
dstNodeId = nodeId(idPath, dstKey);
}
+ const edgeDstKey = r.phpCallKind && (relationshipShapeCounts.get(baseResolutionKey) ?? 0) > 1
+ ? `${dstKey}:${r.phpCallKind}`
+ : dstKey;
ops.push({
type: 'UpsertEdge',
- id: edgeId(idPath, srcKey, dstKey, r.predicate),
+ id: edgeId(idPath, srcKey, edgeDstKey, r.predicate),
src: nodeId(idPath, srcKey),
dst: dstNodeId,
predicate: r.predicate,
diff --git a/core-ingestion/src/queries.ts b/core-ingestion/src/queries.ts
index 261032ad..33e516f9 100644
--- a/core-ingestion/src/queries.ts
+++ b/core-ingestion/src/queries.ts
@@ -1028,7 +1028,7 @@ export const PHP_QUERIES = `
; Simple: use App\\Models\\User;
(namespace_use_declaration
(namespace_use_clause
- (qualified_name) @import.source)) @import
+ [(qualified_name) (name)] @import.source)) @import
; ── Function/method calls ────────────────────────────────────────────────────
; Regular function call: foo()