Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(php): a class named only in a comment no longer closes an import cycle (#2824)

Raghav Chamadiya78c8475bbc58
diff --git a/packages/core/src/repowise/core/ingestion/cohesion.py b/packages/core/src/repowise/core/ingestion/cohesion.py
index 31b2be44f..7584437cc 100644
--- a/packages/core/src/repowise/core/ingestion/cohesion.py
+++ b/packages/core/src/repowise/core/ingestion/cohesion.py
@@ -33,6 +33,11 @@ SAME_PACKAGE_HINT = "same_package"
#: (C#, VB.NET, PHP), where the language needs no import to name it.
SAME_NAMESPACE_HINT = "same_namespace"
+#: Hint stamped on a PHP edge whose only evidence is a class name inside a
+#: comment or docblock (``@param \App\Foo $x``). A docblock type keeps its
+#: target reachable, but no code depends on it, so it cannot close a cycle.
+DOC_COMMENT_HINT = "doc_comment"
+
#: Languages whose import statement names a *compilation unit* that is exactly a
#: directory, so a fan-out landing in the importer's own directory landed on its
#: siblings — and a unit cannot depend on itself.
@@ -71,6 +76,8 @@ COHESION_HINTS: frozenset[str] = frozenset(
"same_module", # Swift SPM target siblings
"partial_class", # C# fragments of one partial type
"header_source_pair", # C/C++ foo.h <-> foo.c
+ DOC_COMMENT_HINT, # PHP name seen only in a comment: not co-membership,
+ # but the same split applies (reachability yes, cycle no)
}
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.py b/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.py
index e58348185..7dbec7b99 100644
--- a/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.py
+++ b/packages/core/src/repowise/core/ingestion/languages/php_same_namespace.py
@@ -18,7 +18,9 @@ file's ``namespace`` declaration) and the shadowing rule (a name bound by a
needed: an unqualified name in a namespace never falls back to a global class.
Edges carry ``hint_source="same_namespace"`` (as for C#) or
-``"qualified_name"``.
+``"qualified_name"``. A file reached only through names inside comments
+(``@param \\App\\Foo $x``, ``// see Bar``) is linked with ``"doc_comment"``
+instead, which keeps it reachable but out of cycle detection.
"""
from __future__ import annotations
@@ -26,7 +28,7 @@ from __future__ import annotations
import re
from typing import TYPE_CHECKING, Any
-from ..cohesion import SAME_NAMESPACE_HINT
+from ..cohesion import DOC_COMMENT_HINT, SAME_NAMESPACE_HINT
from .scope_scan import FileScope, ScopeTier, emit_scope_edges
if TYPE_CHECKING:
@@ -55,6 +57,23 @@ PHP_CLASS_DECL_RE = re.compile(_DECLARATION + r"class[ \t]+(?P<cls>[A-Za-z_]\w*)
# The first declaration of any kind: every `use` clause comes before it.
_FIRST_DECL_RE = re.compile(_DECLARATION + r"(?:class|interface|trait|enum|function)\b", re.MULTILINE)
+#: A quoted string (kept, so a ``//`` inside one is not a comment) or a comment:
+#: ``/* */`` / ``/** */``, ``//`` or ``#`` to end of line, but not a ``#[``
+#: attribute, which names a class in code. Heredocs are not lexed; a quote in
+#: one can leave a later comment unblanked, which only costs the doc_comment hint.
+_STRING_OR_COMMENT_RE = re.compile(
+ r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\"|/\*.*?\*/|(?://|#(?!\[))[^\n]*", re.DOTALL
+)
+_NOT_NEWLINE_RE = re.compile(r"[^\n]")
+
+
+def _blank_comments(text: str) -> str:
+ """*text* with every comment blanked to spaces, strings and newlines kept."""
+ return _STRING_OR_COMMENT_RE.sub(
+ lambda m: m.group() if m.group()[0] in "'\"" else _NOT_NEWLINE_RE.sub(" ", m.group()),
+ text,
+ )
+
def file_namespace(text: str) -> str | None:
"""The one ``namespace`` a PHP file declares, or None.
@@ -171,6 +190,18 @@ def resolve_php_same_namespace_refs(
shadowed=frozenset(bound),
)
- return emit_scope_edges(
- graph, sorted(texts.items()), plan, skip_names=frozenset(), ident_re=_NAME_RE
+ def comment_plan(path: str, text: str) -> FileScope:
+ code = plan(path, text)
+ return FileScope(
+ tiers=tuple(ScopeTier(hint=DOC_COMMENT_HINT, lookup=t.lookup) for t in code.tiers),
+ shadowed=code.shadowed,
+ )
+
+ # Code first, so a name used in code gets its real hint. The second pass
+ # reads the raw text, comments included; ``emit_scope_edges`` skips any
+ # pair already linked, so it only adds files no code names.
+ code_texts = sorted((path, _blank_comments(text)) for path, text in texts.items())
+ added = emit_scope_edges(graph, code_texts, plan, skip_names=frozenset(), ident_re=_NAME_RE)
+ return added + emit_scope_edges(
+ graph, sorted(texts.items()), comment_plan, skip_names=frozenset(), ident_re=_NAME_RE
)
diff --git a/tests/unit/health/test_refactoring_break_cycle.py b/tests/unit/health/test_refactoring_break_cycle.py
index d9a84d38d..31735444f 100644
--- a/tests/unit/health/test_refactoring_break_cycle.py
+++ b/tests/unit/health/test_refactoring_break_cycle.py
@@ -177,3 +177,67 @@ def test_cycle_edges_matches_full_edge_scan():
assert cycle_edges(g, members) == reference(g, members)
assert cycle_edges(g, ()) == []
assert cycle_edges(None, members) == []
+
+
+_PHP_IDENTITY = (
+ "<?php\nnamespace App\\Identity;\nuse App\\Validation\\HostValidator;\n"
+ "class HostIdentity { public function check() { return new HostValidator(); } }\n"
+)
+
+
+def _php_break_cycles(tmp_path, validator_src: str) -> list:
+ from datetime import datetime
+
+ from repowise.core.ingestion.graph import GraphBuilder
+ from repowise.core.ingestion.models import FileInfo
+ from repowise.core.ingestion.parser import ASTParser
+
+ files = {
+ "src/Identity/HostIdentity.php": _PHP_IDENTITY,
+ "src/Validation/HostValidator.php": validator_src,
+ }
+ builder, parser = GraphBuilder(), ASTParser()
+ for rel, text in files.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+ info = FileInfo(
+ path=rel,
+ abs_path=str(path),
+ language="php",
+ size_bytes=len(text),
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ builder.add_file(parser.parse_file(info, text.encode()))
+ return _detect(builder.build(), "src/Identity/HostIdentity.php")
+
+
+def test_php_docblock_only_reference_does_not_close_a_cycle(tmp_path):
+ # HostValidator names HostIdentity only in comments; no code depends on it.
+ validator = (
+ "<?php\nnamespace App\\Validation;\n"
+ "/** Validates a host, see \\App\\Identity\\HostIdentity. */\n"
+ "class HostValidator {\n"
+ " /** @param \\App\\Identity\\HostIdentity $host */\n"
+ " public function ok($host) { return true; } // not HostIdentity-specific\n"
+ "}\n"
+ )
+ assert _php_break_cycles(tmp_path, validator) == []
+
+
+def test_php_use_both_ways_is_a_cycle(tmp_path):
+ validator = (
+ "<?php\nnamespace App\\Validation;\nuse App\\Identity\\HostIdentity;\n"
+ "class HostValidator { public function ok(HostIdentity $host) { return true; } }\n"
+ )
+ out = _php_break_cycles(tmp_path, validator)
+ assert len(out) == 1
+ assert out[0].plan["cycle"] == [
+ "src/Identity/HostIdentity.php",
+ "src/Validation/HostValidator.php",
+ ]
diff --git a/tests/unit/ingestion/test_php_same_namespace.py b/tests/unit/ingestion/test_php_same_namespace.py
index 70a493bf1..7bc276abf 100644
--- a/tests/unit/ingestion/test_php_same_namespace.py
+++ b/tests/unit/ingestion/test_php_same_namespace.py
@@ -6,7 +6,7 @@ from datetime import datetime
import networkx as nx
-from repowise.core.ingestion.cohesion import SAME_NAMESPACE_HINT
+from repowise.core.ingestion.cohesion import DOC_COMMENT_HINT, SAME_NAMESPACE_HINT
from repowise.core.ingestion.languages.php_same_namespace import (
QUALIFIED_NAME_HINT,
resolve_php_same_namespace_refs,
@@ -160,3 +160,55 @@ def test_fully_qualified_reference_from_a_global_file() -> None:
edge = graph.get_edge_data("config/auth.php", "app/Actions/Login.php")
assert edge is not None and edge["hint_source"] == QUALIFIED_NAME_HINT
assert graph.number_of_edges() == 1
+
+
+LOGIN = "<?php\nnamespace App\\Actions;\nclass Login {}\n"
+
+
+def test_a_name_only_in_comments_links_as_doc_comment() -> None:
+ graph = _resolve(
+ {
+ "app/Actions/Login.php": LOGIN,
+ "app/Http/Guard.php": (
+ "<?php\nnamespace App\\Http;\n"
+ "/** @param \\App\\Actions\\Login $login */\n"
+ "class Guard { public function f($login) {} } // or \\App\\Actions\\Login\n"
+ "# \\App\\Actions\\Login\n"
+ ),
+ }
+ )
+ edge = graph.get_edge_data("app/Http/Guard.php", "app/Actions/Login.php")
+ assert edge is not None and edge["hint_source"] == DOC_COMMENT_HINT
+
+
+def test_a_name_in_code_keeps_its_hint_even_when_a_comment_repeats_it() -> None:
+ graph = _resolve(
+ {
+ "app/Actions/Login.php": LOGIN,
+ "app/Http/Guard.php": (
+ "<?php\nnamespace App\\Http;\n"
+ "/** @return \\App\\Actions\\Login */\n"
+ "class Guard { public function f() { return new \\App\\Actions\\Login(); } }\n"
+ ),
+ }
+ )
+ edge = graph.get_edge_data("app/Http/Guard.php", "app/Actions/Login.php")
+ assert edge is not None and edge["hint_source"] == QUALIFIED_NAME_HINT
+
+
+def test_attributes_and_strings_are_code_not_comments() -> None:
+ graph = _resolve(
+ {
+ "app/Actions/Login.php": LOGIN,
+ "app/Http/Attr.php": (
+ "<?php\nnamespace App\\Http;\n#[\\App\\Actions\\Login]\nclass Attr {}\n"
+ ),
+ "app/Http/Url.php": (
+ "<?php\nnamespace App\\Http;\n"
+ "class Url { public $u = 'http://x'; public $c = \\App\\Actions\\Login::class; }\n"
+ ),
+ }
+ )
+ for src in ("app/Http/Attr.php", "app/Http/Url.php"):
+ edge = graph.get_edge_data(src, "app/Actions/Login.php")
+ assert edge is not None and edge["hint_source"] == QUALIFIED_NAME_HINT, src