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): link files loaded by a __DIR__ path or a view name (#2971)

Raghav Chamadiya0cb3e9f8b87d
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/php.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/php.py
index 5ecbb303e..78775830e 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/php.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/php.py
@@ -2,9 +2,13 @@
from __future__ import annotations
+import bisect
+import posixpath
import re
from pathlib import Path
+from ...code_origin import code_origin
+from ..languages.php_same_namespace import blank_php_comments
from .base import DynamicEdge, DynamicHintExtractor
_SKIP_DIRS = {"vendor", "node_modules", ".git", "storage", "bootstrap"}
@@ -26,6 +30,26 @@ _NEW_DOLLAR_RE = re.compile(r"new\s+\$\w+\s*\(")
_CLASS_DECL_RE = re.compile(r"^\s*(?:abstract\s+|final\s+)?(?:class|interface|trait|enum)\s+([A-Z]\w*)", re.MULTILINE)
+# A path the code builds from its own directory: `__DIR__.'/views'`,
+# `dirname(__DIR__, 2)."/config/$name.php"`. Group `up` is dirname's level
+# count, `path` the literal up to any interpolation.
+_DIR_PATH_RE = re.compile(
+ r"(?P<call>dirname\(\s*)?__DIR__(?(call)\s*(?:,\s*(?P<up>\d+)\s*)?\))"
+ r"""\s*\.\s*(?P<q>['"])(?P<path>/[^'"$\{]*)"""
+)
+# The literal ends the path: its quote closes with no `.` joining more on.
+_CLOSED_RE = re.compile(r"""(['"])(?!\s*\.)""")
+# The import graph already follows a `require`/`include` of a literal file.
+_INCLUDE_TAIL_RE = re.compile(r"\b(?:require|include)(?:_once)?\s*\(?\s*$")
+# A statement that loads the files of a folder it names: a view, migration or
+# translation namespace, a publish map, a Finder, glob or directory scan, an
+# include of a variable name.
+_FOLDER_LOADER_RE = re.compile(
+ r"\b(?:load(?:Views|Migrations|Translations|JsonTranslations)From"
+ r"|(?:add|replace|prepend)Namespace|publishes|glob|scandir|opendir|in)\s*\("
+ r"|\b(?:include|require)(?:_once)?\b"
+)
+
class PhpDynamicHints(DynamicHintExtractor):
"""Discover PHP reflection, container, and dynamic-instantiation patterns."""
@@ -34,32 +58,14 @@ class PhpDynamicHints(DynamicHintExtractor):
def extract(self, repo_root: Path) -> list[DynamicEdge]:
edges: list[DynamicEdge] = []
+ sources = self._read_sources(repo_root)
type_to_file: dict[str, str] = {}
- php_files: list[tuple[Path, str]] = []
- repo_root_resolved = repo_root.resolve()
- for src in self._rglob(repo_root, "*.php"):
- try:
- rel_path = src.resolve().relative_to(repo_root_resolved)
- except ValueError:
- continue
- if any(part in _SKIP_DIRS for part in rel_path.parts):
- continue
- try:
- text = src.read_text(encoding="utf-8", errors="ignore")
- except OSError:
- continue
- rel = rel_path.as_posix()
- php_files.append((src, text))
+ for rel, text in sources:
for match in _CLASS_DECL_RE.finditer(text):
type_to_file.setdefault(match.group(1), rel)
- for src, text in php_files:
- try:
- rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
- except ValueError:
- continue
-
+ for rel, text in sources:
for match in _CALL_USER_FUNC_RE.finditer(text):
name = match.group(1) or match.group(2)
target = type_to_file.get(name)
@@ -97,4 +103,113 @@ class PhpDynamicHints(DynamicHintExtractor):
hint_source=f"{self.name}:new_var",
))
+ edges.extend(self._dir_path_edges(sources))
return edges
+
+ def _read_sources(self, repo_root: Path) -> list[tuple[str, str]]:
+ """``(repo-relative path, text)`` of every first-party PHP file."""
+ sources: list[tuple[str, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ for src in self._rglob(repo_root, "*.php"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ sources.append((rel_path.as_posix(), text))
+ return sources
+
+ def _dir_path_edges(self, sources: list[tuple[str, str]]) -> list[DynamicEdge]:
+ paths = sorted(rel for rel, _ in sources)
+ return [
+ DynamicEdge(
+ source=rel,
+ target=target,
+ edge_type="dynamic_imports",
+ hint_source=f"{self.name}:dir_path",
+ )
+ for rel, text in sources
+ for target in sorted(_dir_path_targets(rel, blank_php_comments(text), paths))
+ ]
+
+
+def _dir_path_targets(rel: str, text: str, paths: list[str]) -> set[str]:
+ """The PHP files a ``__DIR__``-relative path in *text* names.
+
+ A file path names that file. A folder names its files only when the
+ statement hands it to a loader (:data:`_FOLDER_LOADER_RE`): every file
+ under it (a view namespace, a config directory a ``Finder`` reads), or,
+ joined with a variable (``"/components/$view.php"``), the files of that
+ folder starting with the literal part. *text* has its comments blanked;
+ *paths* is the sorted list of the repo's PHP files.
+ """
+ out = {p for m in _DIR_PATH_RE.finditer(text) for p in _named_files(rel, text, m, paths)}
+ out.discard(rel)
+ return out
+
+
+def _named_files(rel: str, text: str, m: re.Match[str], paths: list[str]) -> list[str]:
+ """The files one ``__DIR__`` path match in *text* names."""
+ target = _dir_path(posixpath.dirname(rel), m)
+ if target is None:
+ return []
+ statement = text[text.rfind(";", 0, m.start()) + 1 : m.start()]
+ inside = _under(paths, target)
+ if inside or _CLOSED_RE.match(text, m.end("path")) is None:
+ if not _loads_folder(rel, target, statement):
+ return []
+ return inside or _prefixed(paths, target)
+ if _contains(paths, target) and not _INCLUDE_TAIL_RE.search(statement):
+ return [target]
+ return []
+
+
+def _dir_path(here: str, m: re.Match[str]) -> str | None:
+ """The repo-relative path a ``__DIR__`` match builds, or None outside the repo."""
+ base = here
+ for _ in range(int(m.group("up") or 1) if m.group("call") else 0):
+ base = posixpath.dirname(base)
+ target = posixpath.normpath(posixpath.join(base, m.group("path").lstrip("/")))
+ return None if target in (".", "..") or target.startswith("../") else target
+
+
+def _loads_folder(rel: str, folder: str, statement: str) -> bool:
+ """Whether naming *folder* in *statement* of file *rel* loads its files.
+
+ Only production code handing the folder to a loader counts. A test or a
+ tool naming a folder (``tests/bootstrap.php``, a lint config listing its
+ scan scope) loads nothing, and a folder holding *rel* itself
+ (``__DIR__.'/..'``) says nothing about which sibling is used.
+ """
+ return (
+ _FOLDER_LOADER_RE.search(statement) is not None
+ and not (posixpath.dirname(rel) + "/").startswith(folder + "/")
+ and code_origin(rel) == "production"
+ )
+
+
+def _prefixed(paths: list[str], prefix: str) -> list[str]:
+ """The files directly in *prefix*'s folder whose name starts with its last part."""
+ folder, stem = posixpath.split(prefix)
+ return [
+ p
+ for p in _under(paths, folder)
+ if posixpath.dirname(p) == folder and posixpath.basename(p).startswith(stem)
+ ]
+
+
+def _contains(paths: list[str], path: str) -> bool:
+ i = bisect.bisect_left(paths, path)
+ return i < len(paths) and paths[i] == path
+
+
+def _under(paths: list[str], folder: str) -> list[str]:
+ """Every path in sorted *paths* inside *folder*."""
+ start = bisect.bisect_left(paths, folder + "/")
+ end = bisect.bisect_left(paths, folder + "0") # "0" sorts right after "/"
+ return paths[start:end]
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py b/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py
index 6333ba858..e5537e82b 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py
@@ -40,6 +40,7 @@ from ..framework_routes import (
)
from ..languages.php_same_namespace import (
PHP_CLASS_NAME,
+ blank_php_comments,
file_namespace,
php_use_aliases,
qualify_php_name,
@@ -121,6 +122,24 @@ _COMMAND_CALL_HINTS = ("command", "Artisan::", "call")
# Whole-file registries: every class they name is loaded by the framework.
_REGISTRY_FILES = ("bootstrap/providers.php", "config/app.php")
+# A view by name, where the code hands that name to the view layer:
+# `view('emails.welcome')`, `->markdown(...)`, `@include('partials.nav')`,
+# `Route::view('/', 'welcome')`, `$rootView = 'app'`, or a `<x-alert>`
+# component tag. Views live under each app's `resources/views`; a name spells
+# the path with dots or slashes. A quoted word elsewhere is not a use.
+_VIEWS_DIR = "resources/views"
+_VIEW_SUFFIXES = (".blade.php", ".php")
+_VIEW_NAME = r"""(?P<q>['"])(?P<name>[\w-]+(?:[./][\w-]+)*)(?P=q)"""
+_VIEW_NAME_RES = (
+ re.compile(
+ r"(?:\bview|\bView::(?:make|first)|->\s*(?:view|markdown|text|html)"
+ r"|@(?:include(?:If|First)?|extends|component|each))\s*\(\s*\[?\s*" + _VIEW_NAME
+ ),
+ re.compile(r"""\bRoute::view\s*\(\s*['"][^'"]*['"]\s*,\s*""" + _VIEW_NAME),
+ re.compile(r"\$(?:rootView|view|layout)\s*=\s*" + _VIEW_NAME),
+)
+_COMPONENT_TAG_RE = re.compile(r"<x-(?P<name>[\w-]+(?:\.[\w-]+)*)")
+
# Where a legacy string handler (`'Admin\DashboardController@index'`) lives
# when no group names a namespace: the framework's default controller namespace.
_DEFAULT_CONTROLLER_NAMESPACE = "App\\Http\\Controllers\\"
@@ -140,10 +159,11 @@ def _span(text: str, m: re.Match[str], group: str) -> str:
class _PhpFile:
"""One PHP file's text and the names its ``use`` clauses and namespace bind."""
- __slots__ = ("aliases", "namespace", "path", "text")
+ __slots__ = ("aliases", "is_test", "namespace", "path", "text")
def __init__(self, path: str, parsed: Any, source_map: dict[str, bytes]) -> None:
self.path = path
+ self.is_test = bool(parsed.file_info.is_test)
self.text = source_text(path, parsed, source_map)
self.namespace = file_namespace(self.text) if self.text else None
self.aliases = php_use_aliases(parsed)
@@ -237,6 +257,36 @@ def _discovered_listeners(link: _Linker, f: _PhpFile) -> None:
link.anchor(f.path) # a framework or package event
+def _views_by_name(roots: list[str], path_set: set[str]) -> dict[str, str]:
+ """``view name -> file`` for every view under an app's ``resources/views``."""
+ out: dict[str, str] = {}
+ for root in roots:
+ prefix = posixpath.join(root, _VIEWS_DIR) + "/"
+ for path in path_set:
+ if not path.startswith(prefix):
+ continue
+ stem = next((path[: -len(x)] for x in _VIEW_SUFFIXES if path.endswith(x)), None)
+ if stem:
+ out.setdefault(stem[len(prefix) :].replace("/", "."), path)
+ return out
+
+
+def _view_references(link: _Linker, f: _PhpFile, views: dict[str, str]) -> None:
+ """Link *f* to each view its code renders by name, and each component tag.
+
+ A test renders views to check them, which is no use of one.
+ """
+ if f.is_test:
+ return
+ code = blank_php_comments(f.text)
+ for pattern in _VIEW_NAME_RES:
+ for m in pattern.finditer(code):
+ link.edge(f.path, views.get(m.group("name").replace("/", ".")))
+ if "<x-" in code:
+ for m in _COMPONENT_TAG_RE.finditer(code):
+ link.edge(f.path, views.get("components." + m.group("name")))
+
+
def _discovered_policies(link: _Linker, roots: list[str], path_set: set[str]) -> None:
"""``Models/Admin/Post.php`` to ``Policies/Admin/PostPolicy.php``.
@@ -281,6 +331,7 @@ def _add_laravel_edges(
aliases = _aliases(link, files)
commands = _commands(files)
+ views = _views_by_name(roots, path_set)
listener_dirs = tuple(posixpath.join(root, "app/Listeners/") for root in roots)
registry_files = {posixpath.join(root, name) for root in roots for name in _REGISTRY_FILES}
@@ -299,6 +350,8 @@ def _add_laravel_edges(
link.edge(f.path, commands.get(m.group("name")))
if listener_dirs and f.path.startswith(listener_dirs):
_discovered_listeners(link, f)
+ if views:
+ _view_references(link, f, views)
_discovered_policies(link, roots, path_set)
return entry + link.count
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 7dbec7b99..9259a955a 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
@@ -67,7 +67,7 @@ _STRING_OR_COMMENT_RE = re.compile(
_NOT_NEWLINE_RE = re.compile(r"[^\n]")
-def _blank_comments(text: str) -> str:
+def blank_php_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()),
@@ -200,7 +200,7 @@ def resolve_php_same_namespace_refs(
# 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())
+ code_texts = sorted((path, blank_php_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/ingestion/test_dynamic_hints_per_language.py b/tests/unit/ingestion/test_dynamic_hints_per_language.py
index 88c07d73d..d44f386d2 100644
--- a/tests/unit/ingestion/test_dynamic_hints_per_language.py
+++ b/tests/unit/ingestion/test_dynamic_hints_per_language.py
@@ -78,6 +78,87 @@ class TestPhpHints:
assert "Foo.php" in targets
+def _php_dir_targets(root: Path, files: dict[str, str]) -> dict[str, set[str]]:
+ """``source -> targets`` of the ``__DIR__`` path edges over *files*."""
+ for rel, text in files.items():
+ (root / rel).parent.mkdir(parents=True, exist_ok=True)
+ (root / rel).write_text(text)
+ out: dict[str, set[str]] = {}
+ for e in PhpDynamicHints().extract(root):
+ if e.hint_source == "php:dir_path":
+ assert e.edge_type == "dynamic_imports"
+ out.setdefault(e.source, set()).add(e.target)
+ return out
+
+
+class TestPhpDirPaths:
+ def test_dir_paths_name_files_and_folders(self, tmp_path: Path) -> None:
+ provider = "src/Mail/MailServiceProvider.php"
+ targets = _php_dir_targets(
+ tmp_path,
+ {
+ provider: (
+ "<?php\nclass MailServiceProvider {\n"
+ " function boot() { $this->loadViewsFrom(__DIR__.'/resources/views', 'mail'); }\n"
+ " function cfg() { return dirname(__DIR__, 2) . '/config/mail.php'; }\n}\n"
+ ),
+ "src/Mail/resources/views/html/button.blade.php": "<a>{{ $slot }}</a>\n",
+ "src/Mail/resources/views/text/button.blade.php": "{{ $slot }}\n",
+ "config/mail.php": "<?php\nreturn [];\n",
+ "config/queue.php": "<?php\nreturn [];\n",
+ },
+ )
+ assert targets[provider] == {
+ "src/Mail/resources/views/html/button.blade.php",
+ "src/Mail/resources/views/text/button.blade.php",
+ "config/mail.php",
+ }
+
+ def test_an_interpolated_name_keeps_its_folder_and_prefix(self, tmp_path: Path) -> None:
+ component = "src/Console/View/Component.php"
+ targets = _php_dir_targets(
+ tmp_path,
+ {
+ component: (
+ '<?php\nclass Component { function render($view) {\n'
+ ' include __DIR__."/../resources/views/components/$view.php";\n'
+ " require __DIR__.'/../stubs/make-'.$view.'.php';\n} }\n"
+ ),
+ "src/Console/resources/views/components/alert.php": "<?php echo 1;\n",
+ "src/Console/resources/views/layout.php": "<?php echo 1;\n",
+ "src/Console/stubs/make-model.php": "<?php\n",
+ "src/Console/stubs/other.php": "<?php\n",
+ },
+ )
+ assert targets[component] == {
+ "src/Console/resources/views/components/alert.php",
+ "src/Console/stubs/make-model.php",
+ }
+
+ def test_no_folder_edge_without_a_production_loader(self, tmp_path: Path) -> None:
+ targets = _php_dir_targets(
+ tmp_path,
+ {
+ "composer.json": "{}",
+ # A tool config lists the folders it scans.
+ "rector.php": "<?php\nreturn [__DIR__.'/src', __DIR__.'/tests'];\n",
+ # Naming a folder is not loading it.
+ "config/ide.php": "<?php\nreturn ['paths' => [dirname(__DIR__).'/src']];\n",
+ # A test bootstrap loading a folder is no use of it.
+ "tests/bootstrap.php": "<?php\n$finder->in(__DIR__.'/../src');\n",
+ # A comment is not code.
+ "src/Loader.php": "<?php\n// $this->loadViewsFrom(__DIR__.'/Dead', 'x');\n",
+ # An ancestor folder says nothing about which sibling is used.
+ "src/Support/Finder.php": "<?php\n$all = glob(__DIR__.'/..');\n",
+ # The import graph already follows a literal require.
+ "src/boot.php": "<?php\nrequire __DIR__.'/Support/Finder.php';\n",
+ "src/Dead/Dead0.php": "<?php\n",
+ "tests/FinderTest.php": "<?php\n",
+ },
+ )
+ assert targets == {}
+
+
class TestScalaHints:
def test_class_forname(self, tmp_path: Path) -> None:
(tmp_path / "Foo.scala").write_text("package x\nclass Foo\n")
diff --git a/tests/unit/ingestion/test_laravel_framework_edges.py b/tests/unit/ingestion/test_laravel_framework_edges.py
index 27511b49c..d6ce2057d 100644
--- a/tests/unit/ingestion/test_laravel_framework_edges.py
+++ b/tests/unit/ingestion/test_laravel_framework_edges.py
@@ -547,3 +547,75 @@ class TestLaravelRegistrationShapes:
assert graph.has_edge(
"routes/web.php", "app/Http/Controllers/Admin/DashboardController.php"
)
+
+
+class TestLaravelViews:
+ def test_views_named_by_string_or_component_tag(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Mail/UserInvited.php": _class(
+ "App\\Mail\\UserInvited",
+ "public function build() { return $this->markdown('emails.user.invitation'); }",
+ ),
+ "app/Http/Middleware/HandleInertiaRequests.php": _class(
+ "App\\Http\\Middleware\\HandleInertiaRequests", "protected $rootView = 'app';"
+ ),
+ "resources/views/emails/user/invitation.blade.php": (
+ "@include('partials/footer')\n<x-alert type=\"info\" />\n"
+ ),
+ "resources/views/app.blade.php": "<html></html>\n",
+ "resources/views/partials/footer.blade.php": "<footer></footer>\n",
+ "resources/views/components/alert.blade.php": "<div></div>\n",
+ "resources/views/emails/unused.blade.php": "<p></p>\n",
+ },
+ )
+ invitation = "resources/views/emails/user/invitation.blade.php"
+ assert graph.has_edge("app/Mail/UserInvited.php", invitation)
+ assert graph.has_edge(
+ "app/Http/Middleware/HandleInertiaRequests.php", "resources/views/app.blade.php"
+ )
+ assert graph.has_edge(invitation, "resources/views/partials/footer.blade.php")
+ assert graph.has_edge(invitation, "resources/views/components/alert.blade.php")
+ assert not any(graph.predecessors("resources/views/emails/unused.blade.php"))
+
+ def test_a_quoted_word_outside_a_view_call_links_no_view(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Models/Order.php": _class(
+ "App\\Models\\Order",
+ "protected $fillable = ['welcome'];\n"
+ "/** Previously rendered view('dashboard'). */\n"
+ "public function show() { return response()->json(['orders' => 1]); }",
+ ),
+ "resources/views/welcome.blade.php": "<p></p>\n",
+ "resources/views/dashboard.blade.php": "<p></p>\n",
+ "resources/views/orders.blade.php": '<div class="welcome"></div>\n',
+ },
+ )
+ for view in ("welcome", "dashboard", "orders"):
+ assert not any(graph.predecessors(f"resources/views/{view}.blade.php")), view
+
+ def test_a_test_rendering_a_view_links_nothing(self, tmp_path: Path) -> None:
+ (tmp_path / "composer.json").write_text(
+ json.dumps({"require": {"laravel/framework": "^11"}})
+ )
+ files = {
+ "tests/Feature/WelcomeTest.php": "<?php\n$this->view('welcome');\n",
+ "resources/views/welcome.blade.php": "<p></p>\n",
+ }
+ for rel, text in files.items():
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text(text)
+ parsed = _build_parsed(tmp_path)
+ parsed["tests/Feature/WelcomeTest.php"].file_info.is_test = True
+ graph = nx.DiGraph()
+ graph.add_nodes_from(parsed)
+ add_framework_edges(graph, parsed, _ctx(tmp_path, parsed), tech_stack=[])
+
+ assert not any(graph.predecessors("resources/views/welcome.blade.php"))
+ # The control: the same call from app code is a use.
+ parsed["tests/Feature/WelcomeTest.php"].file_info.is_test = False
+ add_framework_edges(graph, parsed, _ctx(tmp_path, parsed), tech_stack=[])
+ assert graph.has_edge("tests/Feature/WelcomeTest.php", "resources/views/welcome.blade.php")