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.

feat(laravel): serve routes under their groups, link registrations, and read migrations as tables (#2512)

Raghav Chamadiya548e3fe75d79
diff --git a/docs/architecture/language-support.md b/docs/architecture/language-support.md
index c297715bb..4eba4730f 100644
--- a/docs/architecture/language-support.md
+++ b/docs/architecture/language-support.md
@@ -1060,7 +1060,7 @@ exchange) registers its extra passes in `matching.MATCHERS`.
| **gRPC** | `.proto` IDL, Go, Java, Python, NestJS (`@GrpcMethod`), C# (gRPC-dotnet) | Go, Java, Python, C# |
| **Topic** | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika), NATS | The same libraries' consumers, plus RabbitMQ queue bindings |
| **Socket** | SignalR `MapHub`, FastAPI `@app.websocket` | ClientWebSocket, SignalR client, NativeWebSocket, WebSocketSharp |
-| **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, ORM entities (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback) |
+| **Data** | DDL `CREATE`/`ALTER`, Alembic `op.create_table`, Laravel `Schema::create`/`Schema::table`, ORM entities (SQLAlchemy, SQLModel, Django, JPA, EF Core, ActiveRecord, Eloquent `$table` or the class-name convention) | SQL string literals in app code (sqlglot-parsed, verb-anchored-regex fallback), Laravel `DB::table` |
See [docs/scale/WORKSPACES.md](../scale/WORKSPACES.md) for the user-facing
workspace guide.
diff --git a/docs/layers/LANGUAGE_SUPPORT.md b/docs/layers/LANGUAGE_SUPPORT.md
index 2582bf17d..b58c5a068 100644
--- a/docs/layers/LANGUAGE_SUPPORT.md
+++ b/docs/layers/LANGUAGE_SUPPORT.md
@@ -254,7 +254,7 @@ bindings, heritage and a workspace resolver where their syntax supports them.
|----------|-----------|--------------|
| **C** | `.c` | `#include` via `compile_commands.json` (shares the C++ grammar) |
| **Swift** | `.swift` | SPM `Package.swift` target → directory mapping, intra-module type references, `@main` entry points |
-| **PHP** | `.php` | `use` declarations (grouped `use A\{B, C}` included) resolved through PSR-4 from the root and nested `composer.json` files, longest prefix first as composer does; same-namespace and `\Fully\Qualified` class references; Laravel, TYPO3 edges |
+| **PHP** | `.php` | `use` declarations (grouped `use A\{B, C}` included) resolved through PSR-4 from the root and nested `composer.json` files, longest prefix first as composer does; same-namespace and `\Fully\Qualified` class references; Laravel edges (route files to controllers and aliased middleware, registered and discovered listeners, policies, providers, commands by signature), TYPO3 edges |
| **Dart** | `.dart` | `import` / `export` / `part` URIs, `package:` via every `pubspec.yaml`, Flutter route tables and `runApp()` edges. **Health markers included** |
| **COBOL** | `.cbl` `.cob` `.cobol` `.cpy` | Program IDs, sections, paragraphs and data levels; literal `CALL` and `PERFORM` targets resolve to program/procedure symbols. Dynamic calls and `COPY` edges are deliberately silent |
diff --git a/docs/scale/WORKSPACES.md b/docs/scale/WORKSPACES.md
index dffeb31e0..eea41fc3b 100644
--- a/docs/scale/WORKSPACES.md
+++ b/docs/scale/WORKSPACES.md
@@ -233,7 +233,7 @@ Scans source files for HTTP route handlers, gRPC service definitions, and messag
|------|-----------|-----------|
| HTTP | Express, FastAPI, Spring, Laravel, Go (gin/echo/chi/net-http), ASP.NET (attribute + minimal API), Rust (Axum routes, Actix/Rocket attribute macros) | fetch/axios/URL-literal wrappers (JS/TS), requests/httpx (Python), HttpClient/UnityWebRequest/Best.HTTP (C#), reqwest (Rust) |
| gRPC | `.proto` service definitions, plus per-language dialects (Go, Java, Python, C#, TypeScript, NestJS `@GrpcMethod`) | gRPC client stubs |
-| Data / DB | DDL (`CREATE TABLE`/`VIEW`/`MATERIALIZED VIEW`), ORM dialects (SQLAlchemy, Django, JPA, EF Core, ActiveRecord, Eloquent) | Raw SQL string literals in app code (verb-anchored: `SELECT`/`INSERT`/`UPDATE`/`DELETE`/`MERGE`) |
+| Data / DB | DDL (`CREATE TABLE`/`VIEW`/`MATERIALIZED VIEW`), Alembic `op.create_table`, Laravel migrations (`Schema::create` / `Schema::table`), ORM dialects (SQLAlchemy, Django, JPA, EF Core, ActiveRecord, Eloquent `$table` or the class-name convention) | Raw SQL string literals in app code (verb-anchored: `SELECT`/`INSERT`/`UPDATE`/`DELETE`/`MERGE`), Laravel `DB::table(...)` |
| Topics | Kafka (Spring Kafka, kafkajs, kafka-python/confluent, sarama), RabbitMQ (Spring AMQP, amqplib, pika), NATS producers | The corresponding consumers, plus RabbitMQ queue bindings (`bindQueue`, `queue_bind`) |
| Socket / WebSocket | SignalR `MapHub<T>("/path")`, FastAPI `@app.websocket("/path")` | ClientWebSocket `ConnectAsync`, SignalR `HubConnectionBuilder.WithUrl`, NativeWebSocket and WebSocketSharp `new WebSocket(...)` |
@@ -252,11 +252,14 @@ nothing). Such a link carries the exchange as its `contract_id` and the queue as
binding site itself is linked. A publish to the default exchange
(`publish('', 'jobs')`) is a publish to the queue `jobs`.
-Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](#system-graph). The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.
+Data/DB contracts use the id scheme `data::<table>` and render as a `db` edge in the [system graph](#system-graph). A service that only models a table (an ORM class, no migration) is linked to the service whose migration or DDL defines that table's schema, when exactly one service defines it; two services that each migrate a table of one name are read as separate databases and not linked. The consumer side (SQL string matching) is heuristic and lower-confidence than the ORM-based providers; unlike HTTP and gRPC, there is no field-level breaking-change diffing for data contracts, only table/route-level removal.
HTTP routes are matched on their **full** path: a router mount prefix
(`APIRouter(prefix=...)`, `include_router(prefix=...)`, Express `app.use('/x', router)`,
-Go route groups) is stitched onto each handler path before matching. A client call
+Go route groups, Laravel `Route::prefix(...)->group(...)` and `Route::group(['prefix' => ...])`)
+is stitched onto each handler path before matching. Laravel's `routes/api.php` is
+served under `/api` unless `bootstrap/app.php` (`apiPrefix`) or a route provider says
+otherwise, and `Route::resource` / `apiResource` expand into the routes they register. A client call
whose base URL is an unresolved placeholder (`fetch(\`${API_BASE}/users\`)`) matches
on the host-relative path; the link is **exact** when exactly one workspace service
provides that path and a lower-confidence **candidate** when the target is ambiguous.
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/base.py b/packages/core/src/repowise/core/ingestion/framework_edges/base.py
index 64a092e69..2850d2223 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/base.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/base.py
@@ -1,8 +1,10 @@
"""Shared helpers and the ``FrameworkHandler`` protocol for framework-edge detection.
Split out of ``framework_edges.py`` (PR 3.5). Holds the cross-framework
-primitives: the dedup ``_add_edge_if_new`` guard, the unified ``read_text``
-file reader (collapses the old ``_read_text`` / ``_read_cs_text`` variants),
+primitives: the dedup ``_add_edge_if_new`` guard, the ``framework:`` anchor
+edges, the unified ``read_text`` file reader (collapses the old ``_read_text``
+/ ``_read_cs_text`` variants) and ``source_text``, which prefers the bytes
+ingestion already read,
the class/function-name → file maps, and the ``FrameworkHandler`` protocol the
dispatcher iterates over.
"""
@@ -101,13 +103,14 @@ def add_entry_edges(graph: nx.DiGraph, facts: FrameworkFacts, root: str, path_se
The ``framework:`` anchor is what dead-code liveness reads: a file it
points at is reached from outside the import graph.
"""
- count = 0
- for target in facts.entry_files(root, path_set):
- if facts.anchor not in graph:
- graph.add_node(facts.anchor, language="external")
- if _add_edge_if_new(graph, facts.anchor, target):
- count += 1
- return count
+ return sum(anchor_edge(graph, facts, target) for target in facts.entry_files(root, path_set))
+
+
+def anchor_edge(graph: nx.DiGraph, facts: FrameworkFacts, target: str) -> bool:
+ """Link *facts*' ``framework:`` anchor to *target*; True when the edge is new."""
+ if facts.anchor not in graph:
+ graph.add_node(facts.anchor, language="external")
+ return _add_edge_if_new(graph, facts.anchor, target)
def read_text(parsed: Any, encoding: str = "utf-8") -> str:
@@ -122,6 +125,20 @@ def read_text(parsed: Any, encoding: str = "utf-8") -> str:
return ""
+def source_text(
+ path: str, parsed: Any, source_map: dict[str, bytes], encoding: str = "utf-8"
+) -> str:
+ """Source text for *path*, preferring the bytes ingestion already read.
+
+ A handler whose file set is the repo's dominant language would otherwise
+ make a second full pass over the tree.
+ """
+ raw = source_map.get(path)
+ if raw is not None:
+ return raw.decode(encoding, errors="replace")
+ return read_text(parsed, encoding=encoding)
+
+
def _build_class_to_file(
parsed_files: dict[str, Any], languages: tuple[str, ...]
) -> dict[str, str]:
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges/godot.py b/packages/core/src/repowise/core/ingestion/framework_edges/godot.py
index a34734c69..764f0e414 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/godot.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/godot.py
@@ -85,7 +85,7 @@ from .base import (
FrameworkHandler,
_add_edge_if_new,
add_symbol_edge,
- read_text,
+ source_text,
)
if TYPE_CHECKING:
@@ -108,20 +108,6 @@ def _has_gdscript_or_csharp(parsed_files: dict[str, Any]) -> bool:
return any(p.file_info.language in ("gdscript", "csharp") for p in parsed_files.values())
-def _source_text(path: str, parsed: Any, source_map: dict[str, bytes]) -> str:
- """Source text for *path*, preferring bytes ingestion already read.
-
- This handler is the only one whose file set is the repo's dominant
- language, so re-reading it would be a second full pass over the tree.
- ``utf-8-sig`` on both paths: a BOM on line 1 would otherwise hide a
- ``class_name`` declared there.
- """
- raw = source_map.get(path)
- if raw is not None:
- return raw.decode("utf-8-sig", errors="replace")
- return read_text(parsed, encoding="utf-8-sig")
-
-
def _add_class_name_edges(
graph: nx.DiGraph,
parsed_files: dict[str, Any],
@@ -143,7 +129,8 @@ def _add_class_name_edges(
for path, parsed in parsed_files.items():
if parsed.file_info.language != "gdscript":
continue
- text = _source_text(path, parsed, source_map)
+ # utf-8-sig: a BOM on line 1 would otherwise hide a `class_name` there.
+ text = source_text(path, parsed, source_map, "utf-8-sig")
if not text:
continue
texts[path] = text
@@ -331,12 +318,7 @@ def _add_connection_edges(
continue
if not path.lower().endswith((".tscn", ".escn")):
continue
- raw = source_map.get(path)
- text = (
- raw.decode("utf-8-sig", errors="replace")
- if raw is not None
- else read_text(parsed, encoding="utf-8-sig")
- )
+ text = source_text(path, parsed, source_map, "utf-8-sig")
if "[connection" not in text:
continue
resources, nodes, connections = parse_scene(text)
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 29b2d41d0..a26b4a6a0 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges/laravel.py
@@ -1,56 +1,119 @@
-"""Laravel routes / service-provider / Eloquent convention edges.
+"""Laravel convention edges: routes, registrations, discovery, Eloquent.
-The files Laravel loads with no importer (providers, route files, commands,
-factories, ...) are named in ``framework_facts.LARAVEL`` and anchored to
-``framework:laravel`` here.
+The files Laravel loads with no importer (route files, config, commands,
+migrations, factories, ...) are named in ``framework_facts.LARAVEL`` and
+anchored to ``framework:laravel`` here. Everything the framework wires up
+*because some file registered it* is an edge from that file instead, so a
+listener, policy or provider nothing registers still reads as unused:
-Split out of ``framework_edges.py`` (PR 3.5) — behaviour-preserving move. The
-``Route::`` recogniser lives in ``ingestion.framework_routes``, shared with the
-contract extractor that reads the same call for its path.
+* route files to the controllers and middleware (by alias) they name;
+* ``$listen`` / ``$subscribe`` / ``$policies`` / ``$commands`` / middleware
+ alias arrays, ``Event::listen``, ``Gate::policy``, ``withProviders`` /
+ ``withCommands``, scheduled jobs, ``bootstrap/providers.php`` and
+ ``config/app.php`` to the classes they name;
+* a scheduled or called artisan command, by signature, to its class;
+* event discovery: a listener in ``app/Listeners`` whose ``handle`` takes an
+ event is linked from that event (or anchored, for a framework event);
+* policy discovery: ``Models/Post`` to ``Policies/PostPolicy``;
+* service-provider bindings and Eloquent relationships.
+
+Class names resolve the way the import graph resolves them
+(:func:`..resolvers.php.resolve_php_class`), so a vendor class never binds to
+a local file of the same short name. The ``Route::`` recogniser lives in
+``ingestion.framework_routes``, shared with the contract extractor.
"""
from __future__ import annotations
+import posixpath
import re
+from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from ..composer import repo_composer_manifests
from ..framework_facts import LARAVEL
-from ..framework_routes import laravel_routes
+from ..framework_routes import laravel_route_file, laravel_routes, match_paren
+from ..languages.php_same_namespace import file_namespace, php_use_aliases, qualify_php_name
from ..resolvers import ResolverContext
+from ..resolvers.php import resolve_php_class
from .base import (
DetectionContext,
FrameworkHandler,
_add_edge_if_new,
- _build_class_to_file,
add_entry_edges,
- read_text,
+ anchor_edge,
+ source_text,
)
if TYPE_CHECKING:
import networkx as nx
-_LARAVEL_BIND_RE = re.compile(
- r"->\s*(?:bind|singleton|instance)\s*\(\s*([\w\\]+)::class\s*,\s*([\w\\]+)::class"
+_NAME = r"\\?[A-Za-z_]\w*(?:\\[A-Za-z_]\w*)*"
+_CLASS_REF_RE = re.compile(rf"(?<![\w\\$])(?P<name>{_NAME})\s*::\s*class\b")
+_NEW_RE = re.compile(rf"\bnew\s+(?P<name>{_NAME})")
+
+_BIND_RE = re.compile(
+ rf"->\s*(?:bind|singleton|instance)\s*\(\s*(?P<a>{_NAME})::class\s*,\s*(?P<b>{_NAME})::class"
)
-_LARAVEL_ELOQUENT_RE = re.compile(
- r"\$this->\s*(?:hasMany|hasOne|belongsTo|belongsToMany|morphMany|morphOne|morphTo)\s*\(\s*([\w\\]+)::class"
+_ELOQUENT_RE = re.compile(
+ r"\$this->\s*(?:hasMany|hasOne|belongsTo|belongsToMany|morphMany|morphOne|morphTo)"
+ rf"\s*\(\s*(?P<name>{_NAME})::class"
)
+# Registration sites whose class arguments the framework instantiates. The
+# property arrays live on the event/auth providers and the console/HTTP kernels.
+_REGISTRY_RE = re.compile(
+ r"\$(?:listen|subscribe|policies|commands|middlewareAliases|routeMiddleware"
+ r"|middlewareGroups|middleware|observers)\s*=\s*(?P<open>\[)"
+ r"|(?:\bEvent::(?:listen|subscribe)|\bGate::policy|->\s*with(?:Providers|Commands|Events)"
+ r"|\bSchedule::job|->\s*job)\s*(?P<call>\()"
+)
-def _resolve_laravel_class(
- ctx: ResolverContext, fqn: str, class_to_file: dict[str, str], path_set: set[str]
-) -> str | None:
- """Resolve `Foo\\Bar\\Baz` (or short `Bar`) to repo-relative .php path."""
- from ..resolvers.php_composer import resolve_via_psr4
+# Middleware aliases: `'auth' => Authenticate::class` inside `->alias([...])`
+# (bootstrap/app.php) or a kernel's alias array.
+_ALIAS_SITE_RE = re.compile(
+ r"(?:->\s*alias\s*\(|\$(?:middlewareAliases|routeMiddleware)\s*=)\s*(?P<open>\[)"
+)
+_ALIAS_ENTRY_RE = re.compile(rf"""["'](?P<alias>[\w.-]+)["']\s*=>\s*(?P<name>{_NAME})::class""")
+# `->middleware('auth:sanctum')`, `middleware(['a', 'b'])`, `'middleware' => ...`.
+_MIDDLEWARE_USE_RE = re.compile(
+ r"""(?:\bmiddleware\s*\(|["']middleware["']\s*=>)\s*(?P<value>\[[^\]]*\]|["'][^"']*["'])"""
+)
+_MIDDLEWARE_NAME_RE = re.compile(r"""["'](?P<name>[\w.-]+)(?::[^"']*)?["']""")
- if "\\" in fqn:
- result = resolve_via_psr4(fqn, ctx)
- if result and result in path_set:
- return result
- short = fqn.rsplit("\\", 1)[-1]
- return class_to_file.get(short)
+# Artisan commands by signature: the first token of `$signature`, or the
+# `#[AsCommand(name: ...)]` attribute; called by the scheduler
+# (`Schedule::command('x')`, `$schedule->command('x')`), `Artisan::call` /
+# `queue`, and `$this->call` from another command.
+_SIGNATURE_RE = re.compile(r"""\$signature\s*=\s*["'](?P<name>[\w:.-]+)""")
+_AS_COMMAND_RE = re.compile(r"""#\[AsCommand\(\s*(?:name\s*:\s*)?["'](?P<name>[\w:.-]+)""")
+_COMMAND_CALL_RE = re.compile(
+ r"(?:(?:->\s*|\bSchedule::)command|\bArtisan::(?:call|queue)|->\s*call(?:Silently|Silent)?)"
+ r"""\s*\(\s*["'](?P<name>[\w:.-]+)"""
+)
+
+# Event discovery reads the type of a listener method's first parameter; a
+# union type names one event per member.
+_LISTENER_METHOD_RE = re.compile(
+ rf"function\s+(?:handle\w*|__invoke)\s*\(\s*(?P<types>{_NAME}(?:\s*\|\s*{_NAME})*)\s+\$"
+)
+
+# Substrings one of which a file must contain for each regex to run: none of
+# these patterns has a literal prefix, so the regex engine would otherwise try
+# every offset of every PHP file.
+_REGISTRY_HINTS = (
+ "$listen", "$subscribe", "$policies", "$commands", "$middleware", "$routeMiddleware",
+ "$observers", "Event::", "Gate::", "->with", "Schedule::", "->job",
+) # fmt: skip
+_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")
+
+# 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\\"
def _manifest_roots(ctx: ResolverContext) -> list[str]:
@@ -58,71 +121,177 @@ def _manifest_roots(ctx: ResolverContext) -> list[str]:
return [m.rel_dir for m in repo_composer_manifests(ctx) if LARAVEL.matches(m)]
+def _span(text: str, m: re.Match[str], group: str) -> str:
+ start = m.start(group)
+ end = match_paren(text, start, hash_comments=True)
+ return text[start : end + 1] if end != -1 else ""
+
+
+class _PhpFile:
+ """One PHP file's text and the names its ``use`` clauses and namespace bind."""
+
+ __slots__ = ("aliases", "namespace", "path", "text")
+
+ def __init__(self, path: str, parsed: Any, source_map: dict[str, bytes]) -> None:
+ self.path = path
+ 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)
+
+ def qualify(self, name: str) -> str:
+ return qualify_php_name(name, self.namespace, self.aliases)
+
+
+class _Linker:
+ def __init__(self, graph: nx.DiGraph, ctx: ResolverContext) -> None:
+ self.graph = graph
+ self.ctx = ctx
+ self.count = 0
+
+ def file_of(self, f: _PhpFile, name: str) -> str | None:
+ return resolve_php_class(f.qualify(name), self.ctx)
+
+ def edge(self, source: str, target: str | None) -> None:
+ if target and _add_edge_if_new(self.graph, source, target):
+ self.count += 1
+
+ def names(self, f: _PhpFile, names: Iterable[str]) -> None:
+ for name in names:
+ self.edge(f.path, self.file_of(f, name))
+
+ def refs(self, f: _PhpFile, text: str) -> None:
+ """Link *f* to every ``X::class`` and ``new X`` in *text*."""
+ self.names(f, (m.group("name") for m in _CLASS_REF_RE.finditer(text)))
+ self.names(f, (m.group("name") for m in _NEW_RE.finditer(text)))
+
+ def anchor(self, target: str) -> None:
+ if anchor_edge(self.graph, LARAVEL, target):
+ self.count += 1
+
+
+def _registrations(link: _Linker, f: _PhpFile) -> None:
+ text = f.text
+ if f.path.endswith("ServiceProvider.php"):
+ for m in _BIND_RE.finditer(text):
+ link.names(f, (m.group("a"), m.group("b")))
+ if "$this->" in text:
+ link.names(f, (m.group("name") for m in _ELOQUENT_RE.finditer(text)))
+ if any(h in text for h in _REGISTRY_HINTS):
+ for m in _REGISTRY_RE.finditer(text):
+ link.refs(f, _span(text, m, "open" if m.group("open") else "call"))
+
+
+def _route_handlers(link: _Linker, f: _PhpFile) -> None:
+ for route in laravel_routes(f.text):
+ handler = route.handler
+ if not handler:
+ continue # a closure route names no controller
+ target = link.file_of(f, handler)
+ if target is None and not handler.startswith("\\"):
+ target = resolve_php_class(_DEFAULT_CONTROLLER_NAMESPACE + handler, link.ctx)
+ link.edge(f.path, target)
+
+
+def _aliases(link: _Linker, files: list[_PhpFile]) -> dict[str, str]:
+ """``middleware alias -> file`` from every alias registration."""
+ out: dict[str, str] = {}
+ for f in files:
+ if "alias" not in f.text and "iddleware" not in f.text:
+ continue
+ for site in _ALIAS_SITE_RE.finditer(f.text):
+ for m in _ALIAS_ENTRY_RE.finditer(_span(f.text, site, "open")):
+ target = link.file_of(f, m.group("name"))
+ if target:
+ out.setdefault(m.group("alias"), target)
+ return out
+
+
+def _commands(files: list[_PhpFile]) -> dict[str, str]:
+ """``artisan signature -> file`` for every command class."""
+ out: dict[str, str] = {}
+ for f in files:
+ for pattern in (_SIGNATURE_RE, _AS_COMMAND_RE):
+ for m in pattern.finditer(f.text):
+ out.setdefault(m.group("name"), f.path)
+ return out
+
+
+def _discovered_listeners(link: _Linker, f: _PhpFile) -> None:
+ """Link a discovered listener from each event its methods take."""
+ for m in _LISTENER_METHOD_RE.finditer(f.text):
+ for name in m.group("types").split("|"):
+ event = link.file_of(f, name.strip())
+ if event:
+ link.edge(event, f.path)
+ else:
+ link.anchor(f.path) # a framework or package event
+
+
+def _discovered_policies(link: _Linker, roots: list[str], path_set: set[str]) -> None:
+ """``Models/Admin/Post.php`` to ``Policies/Admin/PostPolicy.php``.
+
+ Laravel guesses ``Policies`` beside the model's namespace and under
+ ``app``, keeping the model's sub-namespace, and the model may sit in
+ ``app/Models`` or directly in ``app``.
+ """
+ for root in roots:
+ app = posixpath.join(root, "app")
+ for policies in (f"{app}/Policies/", f"{app}/Models/Policies/"):
+ for path in path_set:
+ if not (path.startswith(policies) and path.endswith("Policy.php")):
+ continue
+ sub = path[len(policies) : -len("Policy.php")] # `Admin/Post`
+ for model in (f"{app}/Models/{sub}.php", f"{app}/{sub}.php"):
+ if model in path_set:
+ link.edge(model, path)
+ break
+
+
def _add_laravel_edges(
graph: nx.DiGraph,
parsed_files: dict[str, Any],
ctx: ResolverContext,
path_set: set[str],
) -> int:
- count = 0
- class_to_file = _build_class_to_file(parsed_files, ("php",))
roots = _manifest_roots(ctx)
+ link = _Linker(graph, ctx)
- # ---- files the framework loads by convention (providers, routes, ...) ----
- # Only where a manifest requires the framework: ``config/*.php`` or
- # ``app/Providers/*.php`` alone say nothing about Laravel.
- for root in roots:
- count += add_entry_edges(graph, LARAVEL, root, path_set)
-
- # ---- routes/web.php / routes/api.php → controllers ----
- for routes_path in (
- f"{root}/{name}" if root else name
- for root in dict.fromkeys(["", *roots])
- for name in ("routes/web.php", "routes/api.php")
- ):
- if routes_path not in path_set:
- continue
- text = read_text(parsed_files[routes_path])
- if not text:
- continue
- seen_targets: set[str] = set()
- for route in laravel_routes(text):
- if not route.handler:
- continue # a closure route names no controller to link to
- target = _resolve_laravel_class(ctx, route.handler, class_to_file, path_set)
- if target and target in path_set and target not in seen_targets:
- seen_targets.add(target)
- if _add_edge_if_new(graph, routes_path, target):
- count += 1
-
- # ---- Service providers → bound classes ----
- for path, parsed in parsed_files.items():
- if parsed.file_info.language != "php":
- continue
- if not path.endswith("ServiceProvider.php"):
- continue
- text = read_text(parsed)
- if not text:
- continue
- for m in _LARAVEL_BIND_RE.finditer(text):
- for fqn in (m.group(1), m.group(2)):
- target = _resolve_laravel_class(ctx, fqn, class_to_file, path_set)
- if target and target in path_set and _add_edge_if_new(graph, path, target):
- count += 1
-
- # ---- Eloquent relationships: model → related model ----
- for path, parsed in parsed_files.items():
- if parsed.file_info.language != "php":
- continue
- text = read_text(parsed)
- if not text:
- continue
- for m in _LARAVEL_ELOQUENT_RE.finditer(text):
- target = _resolve_laravel_class(ctx, m.group(1), class_to_file, path_set)
- if target and target in path_set and _add_edge_if_new(graph, path, target):
- count += 1
+ # ---- files the framework loads by convention (routes, config, ...) ----
+ # Only where a manifest requires the framework: ``config/*.php`` alone
+ # says nothing about Laravel.
+ entry = sum(add_entry_edges(graph, LARAVEL, root, path_set) for root in roots)
+
+ source_map = getattr(ctx, "source_map", None) or {}
+ files = [
+ f
+ for path, parsed in parsed_files.items()
+ if parsed.file_info.language == "php"
+ and (f := _PhpFile(path, parsed, source_map)).text
+ ]
+ aliases = _aliases(link, files)
+ commands = _commands(files)
+
+ 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}
+
+ for f in files:
+ if laravel_route_file(f.path):
+ _route_handlers(link, f)
+ if aliases and "iddleware" in f.text:
+ for use in _MIDDLEWARE_USE_RE.finditer(f.text):
+ for m in _MIDDLEWARE_NAME_RE.finditer(use.group("value")):
+ link.edge(f.path, aliases.get(m.group("name")))
+ if f.path in registry_files:
+ link.refs(f, f.text)
+ _registrations(link, f)
+ if commands and any(h in f.text for h in _COMMAND_CALL_HINTS):
+ for m in _COMMAND_CALL_RE.finditer(f.text):
+ link.edge(f.path, commands.get(m.group("name")))
+ if listener_dirs and f.path.startswith(listener_dirs):
+ _discovered_listeners(link, f)
- return count
+ _discovered_policies(link, roots, path_set)
+ return entry + link.count
class _LaravelHandler:
diff --git a/packages/core/src/repowise/core/ingestion/framework_facts.py b/packages/core/src/repowise/core/ingestion/framework_facts.py
index c752412e6..6240f8c8c 100644
--- a/packages/core/src/repowise/core/ingestion/framework_facts.py
+++ b/packages/core/src/repowise/core/ingestion/framework_facts.py
@@ -88,9 +88,11 @@ LARAVEL = FrameworkFacts(
name="Laravel",
anchor="framework:laravel",
composer_packages=("laravel/framework",),
- # Jobs, middleware and events are left out on purpose: code names them
- # (``Job::dispatch``, the middleware list, ``event(new ...)``), so one
- # with no importer really is unused.
+ # Jobs, middleware, events, listeners and policies are left out on
+ # purpose: code names or registers them (``Job::dispatch``, an alias
+ # array, ``$listen``, a typed ``handle`` in ``app/Listeners``, the model a
+ # policy is named after), and ``framework_edges/laravel.py`` links them
+ # from there, so one nothing names really is unused.
entry_globs=(
"routes/*.php",
"bootstrap/app.php",
@@ -101,8 +103,6 @@ LARAVEL = FrameworkFacts(
"app/Console/Commands/*.php", # auto-discovered artisan commands
"app/Http/Kernel.php",
"app/Exceptions/Handler.php",
- "app/Listeners/*.php", # event discovery
- "app/Policies/*.php", # policy discovery by model name
"database/migrations/*.php",
"database/factories/*.php", # resolved from the model by HasFactory
"database/seeders/*.php",
diff --git a/packages/core/src/repowise/core/ingestion/framework_routes.py b/packages/core/src/repowise/core/ingestion/framework_routes.py
index 71166d0ec..19bf597c3 100644
--- a/packages/core/src/repowise/core/ingestion/framework_routes.py
+++ b/packages/core/src/repowise/core/ingestion/framework_routes.py
@@ -18,7 +18,7 @@ the other way round.
from __future__ import annotations
import re
-from collections.abc import Iterator
+from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass
#: Verbs the contract layer records as an HTTP method. A consumer that sees a
@@ -60,14 +60,6 @@ def _opt(value: str | None) -> str | None:
return value or None
-def _next_top_level_comma(args: str, *, hash_comments: bool = False) -> int:
- """Index just past the first comma separating *args*, or -1."""
- for i, c, depth in scan_code(args, hash_comments=hash_comments):
- if c == "," and depth == 0:
- return i + 1
- return -1
-
-
def _groups(pattern: re.Pattern[str], content: str) -> Iterator[GroupMatch]:
"""Every ``var``/``parent``/``prefix`` match of *pattern* in *content*."""
for m in pattern.finditer(content):
@@ -274,13 +266,23 @@ def scan_code(
def match_paren(
text: str, open_idx: int, *, quotes: str = "\"'`", hash_comments: bool = False
) -> int:
- """Index of the ``)`` closing the ``(`` at *open_idx*, or -1."""
- for i, c, depth in scan_code(text, open_idx, quotes=quotes, hash_comments=hash_comments):
- if c == ")" and depth == 0:
- return i
+ """Index of the bracket closing the ``(``, ``[`` or ``{`` at *open_idx*, or -1."""
+ opener = text[open_idx]
+ closer = _CLOSERS.get(opener, ")")
+ nest = 0
+ for i, c, _depth in scan_code(text, open_idx, quotes=quotes, hash_comments=hash_comments):
+ if c == opener:
+ nest += 1
+ elif c == closer:
+ nest -= 1
+ if nest == 0:
+ return i
return -1
+_CLOSERS = {"(": ")", "[": "]", "{": "}"}
+
+
# ---------------------------------------------------------------------------
# Go — gin / echo / chi routers and stdlib net/http
# ---------------------------------------------------------------------------
@@ -329,18 +331,57 @@ def go_groups(content: str) -> Iterator[GroupMatch]:
# Laravel
# ---------------------------------------------------------------------------
-# `resource`/`apiResource`/`any`/`match` name no single verb; the contract
-# consumer drops them, the graph consumer wants their controller.
-_LARAVEL_VERBS = "get|post|put|patch|delete|any|match|resource|apiResource"
-
-_LARAVEL_CALL_RE = re.compile(
- rf"Route::(?P<verb>{_LARAVEL_VERBS})\s*(?P<paren>\()", re.IGNORECASE
+# A `Route::` call and the fluent chain hanging off it: `Route::prefix('v1')
+# ->middleware('auth')->group(function () { ... })`, `Route::middleware('x')
+# ->get(...)`, `Route::apiResource(...)->only([...])`.
+_LARAVEL_HEAD_RE = re.compile(r"\bRoute::(?P<name>\w+)\s*(?P<paren>\()")
+# Comments may sit between the links of a chain.
+_LARAVEL_LINK_RE = re.compile(
+ r"(?:\s|//[^\n]*|\#(?!\[)[^\n]*|/\*[\s\S]*?\*/)*->\s*(?P<name>\w+)\s*(?P<paren>\()"
)
+# What may come before the verb or `group` of a chain: the route registrar's
+# attributes. Anything else (`Route::getRoutes()->get('GET')`) is not a route.
+_LARAVEL_REGISTRAR = frozenset({
+ "as", "can", "controller", "domain", "middleware", "missing", "name", "namespace",
+ "prefix", "scopebindings", "where", "withoutmiddleware", "withoutscopedbindings",
+}) # fmt: skip
+
+# PHP method names are case-insensitive, so chain names are compared lower-cased.
+# `any` names no single verb and `match` lists its own; the contract consumer
+# keeps only HTTP_METHODS, the graph consumer wants every controller.
+_LARAVEL_VERBS = frozenset({"get", "post", "put", "patch", "delete", "options", "any", "match"})
+_LARAVEL_RESOURCES = frozenset({"resource", "apiresource", "resources", "apiresources"})
+
+# What `Route::resource` registers, in Laravel's order: (action, verbs, suffix,
+# on the member). `apiResource` drops the two HTML-form actions.
+_RESOURCE_ACTIONS: tuple[tuple[str, tuple[str, ...], str, bool], ...] = (
+ ("index", ("GET",), "", False),
+ ("create", ("GET",), "/create", False),
+ ("store", ("POST",), "", False),
+ ("show", ("GET",), "", True),
+ ("edit", ("GET",), "/edit", True),
+ ("update", ("PUT", "PATCH"), "", True),
+ ("destroy", ("DELETE",), "", True),
+)
+_FORM_ACTIONS = frozenset({"create", "edit"})
# The path literal, when the first argument is one. It often is not:
# `Route::post('/hook/'.config('x'), ...)` truncates to the literal head, which
# is what the matcher this replaces recorded too.
-_LARAVEL_PATH_RE = re.compile(r"""\s*(?P<q>["'])(?P<path>[^"']*)(?P=q)""")
+_LARAVEL_LITERAL_RE = re.compile(r"""\s*(?P<q>["'])(?P<text>[^"']*)(?P=q)\s*""")
+_LARAVEL_CLASS_RE = re.compile(r"\s*(?P<cls>[\w\\]+)\s*::\s*class\s*")
+_LARAVEL_WORD_RE = re.compile(r"""["'](\w+)["']""")
+# One `'key' => value` entry of an attribute array.
+_LARAVEL_ENTRY_RE = re.compile(r"""\s*["'](?P<key>[\w.-]+)["']\s*=>\s*(?P<value>.*)""", re.DOTALL)
+_LARAVEL_CLOSURE_RE = re.compile(r"\s*(?:static\s+)?(?:function|fn)\b")
+# A route file named in an expression (`base_path('routes/api.php')`,
+# `__DIR__.'/../routes/api.php'`), by basename.
+_LARAVEL_FILE_RE = re.compile(r"""["'][^"']*?(?P<name>[\w.-]+\.php)["']""")
+_LARAVEL_REQUIRE_RE = re.compile(
+ r"""\b(?:require|include)(?:_once)?\b[^;]*?["'][^"']*?(?P<name>[\w.-]+\.php)["']"""
+)
+_LARAVEL_WITH_ROUTING_RE = re.compile(r"->\s*withRouting\s*(?P<paren>\()")
+_LARAVEL_NAMED_ARG_RE = re.compile(r"(?P<key>\w+)\s*:(?!:)\s*(?P<value>.*)", re.DOTALL)
# Three handler spellings co-exist: the array form, the legacy
# 'Controller@method' string, and the bare `Controller::class` of a resource
@@ -352,8 +393,305 @@ _LARAVEL_HANDLER_RE = re.compile(
)
-def laravel_routes(content: str) -> Iterator[RouteMatch]:
- """``Route::verb(...)`` registrations in *content*.
+@dataclass(frozen=True, slots=True)
+class _Call:
+ """One call of a `Route::` chain, by lower-cased name and its paren span."""
+
+ name: str
+ paren: int
+ close: int
+
+
+@dataclass(frozen=True, slots=True)
+class _Group:
+ """A closure group: the span its routes sit in, and what it adds to them.
+
+ ``prefix`` is ``None`` when the group declares one this cannot read, which
+ refuses every route inside rather than serving it at the outer prefix.
+ """
+
+ start: int
+ end: int
+ prefix: str | None
+ controller: str | None
+
+
+def _php_args(text: str, max_split: int = -1) -> list[tuple[int, int]]:
+ """``(start, end)`` of each top-level argument of a PHP argument list.
+
+ Commas inside strings, comments, parens and array literals do not split.
+ After *max_split* commas the rest is one span, unscanned: a closure body
+ need not be walked to read the arguments before it.
+ """
+ spans: list[tuple[int, int]] = []
+ start, nest = 0, 0
+ for i, c, depth in scan_code(text, hash_comments=True):
+ if c in "[{":
+ nest += 1
+ elif c in "]}":
+ nest -= 1
+ elif c == "," and depth == 0 and nest == 0:
+ spans.append((start, i))
+ start = i + 1
+ if len(spans) == max_split:
+ break
+ if text[start:].strip() or spans:
+ spans.append((start, len(text)))
+ return spans
+
+
+def _literal(text: str) -> str | None:
+ """The body of *text* when it is exactly one string literal.
+
+ A double-quoted body with a ``$`` interpolates, so it is not one.
+ """
+ m = _LARAVEL_LITERAL_RE.fullmatch(text)
+ if m is None or (m.group("q") == '"' and "$" in m.group("text")):
+ return None
+ return m.group("text")
+
+
+def _class_ref(text: str) -> str | None:
+ """``Foo\\Bar`` when *text* is exactly ``Foo\\Bar::class``."""
+ m = _LARAVEL_CLASS_RE.fullmatch(text)
+ return m.group("cls") if m else None
+
+
+def _join_segments(segments: Iterable[str | None]) -> str | None:
+ """Slash-joined non-empty *segments*, or ``None`` when any is unreadable."""
+ parts: list[str] = []
+ for s in segments:
+ if s is None:
+ return None
+ if s.strip("/"):
+ parts.append(s.strip("/"))
+ return "/".join(parts)
+
+
+def _chain(content: str, head: re.Match[str]) -> list[_Call]:
+ calls: list[_Call] = []
+ name, paren = head.group("name"), head.start("paren")
+ while True:
+ close = match_paren(content, paren, hash_comments=True)
+ if close == -1:
+ return calls
+ calls.append(_Call(name.lower(), paren, close))
+ link = _LARAVEL_LINK_RE.match(content, close + 1)
+ if link is None:
+ return calls
+ name, paren = link.group("name"), link.start("paren")
+
+
+def _entries(text: str) -> dict[str, str]:
+ """``key -> value source`` of the attribute array *text* (``['prefix' => 'x']``)."""
+ body = text.strip()
+ if not (body.startswith("[") and body.endswith("]")):
+ return {}
+ body = body[1:-1]
+ out: dict[str, str] = {}
+ for a, b in _php_args(body):
+ m = _LARAVEL_ENTRY_RE.fullmatch(body[a:b])
+ if m:
+ out[m.group("key")] = m.group("value").strip()
+ return out
+
+
+def _apply_attrs(
+ attrs: dict[str, str], prefix: str | None, controller: str | None
+) -> tuple[str | None, str | None]:
+ if "prefix" in attrs:
+ prefix = _join_segments([prefix, _literal(attrs["prefix"])])
+ if "controller" in attrs:
+ controller = _class_ref(attrs["controller"]) or controller
+ return prefix, controller
+
+
+def _chain_attrs(content: str, calls: Iterable[_Call]) -> tuple[str | None, str | None]:
+ """The ``(prefix, controller)`` the modifier *calls* declare."""
+ prefix: str | None = ""
+ controller: str | None = None
+ for call in calls:
+ args = content[call.paren + 1 : call.close]
+ if call.name == "prefix":
+ prefix = _join_segments([prefix, _literal(args)])
+ elif call.name == "controller":
+ controller = _class_ref(args) or controller
+ elif call.name == "group":
+ # `Route::group(['prefix' => 'x'], ...)`: the attribute array.
+ spans = _php_args(args, max_split=1)
+ if len(spans) > 1:
+ a, b = spans[0]
+ prefix, controller = _apply_attrs(_entries(args[a:b]), prefix, controller)
+ return prefix, controller
+
+
+@dataclass
+class _LaravelScan:
+ """Every route chain, closure group and loaded route file in one file."""
+
+ routes: list[tuple[int, list[_Call], int]] # (head offset, chain, verb index)
+ groups: list[_Group]
+ files: list[tuple[int, str, str | None]] # (offset, route file, own prefix)
+
+ def enclosing(self, offset: int) -> list[_Group]:
+ """The groups around *offset*, outermost first."""
+ return [g for g in self.groups if g.start < offset < g.end]
+
+
+def _laravel_scan(content: str) -> _LaravelScan:
+ scan = _LaravelScan([], [], [])
+ if "Route::" not in content:
+ return scan # a substring test is far cheaper than the head regex
+ for head in _LARAVEL_HEAD_RE.finditer(content):
+ calls = _chain(content, head)
+ at = next((i for i, c in enumerate(calls) if c.name not in _LARAVEL_REGISTRAR), None)
+ if at is None:
+ continue
+ if calls[at].name in _LARAVEL_VERBS or calls[at].name in _LARAVEL_RESOURCES:
+ scan.routes.append((head.start(), calls, at))
+ continue
+ if calls[at].name != "group":
+ continue
+ group = calls[at]
+ prefix, controller = _chain_attrs(content, calls[: at + 1])
+ args = content[group.paren + 1 : group.close]
+ spans = _php_args(args, max_split=1) # `group` takes at most two arguments
+ if not spans:
+ continue
+ a, b = spans[-1]
+ body = args[a:b]
+ if _LARAVEL_CLOSURE_RE.match(body):
+ scan.groups.append(_Group(group.paren, group.close, prefix, controller))
+ elif file := _LARAVEL_FILE_RE.search(body):
+ scan.files.append((head.start(), file.group("name"), prefix))
+ return scan
+
+
+def _resource_paths(name: str, shallow: bool) -> tuple[str, str]:
+ """``(collection, member)`` paths of resource *name* (``photos.comments``).
+
+ Parameter names are the naive singular; path normalization erases them.
+ """
+ *parents, last = name.strip("/").split(".")
+ nested = "".join(f"/{p}/{{{_singular(p)}}}" for p in parents)
+ collection = f"{nested}/{last}"
+ member_base = f"/{last}" if shallow and parents else collection
+ return collection, f"{member_base}/{{{_singular(last)}}}"
+
+
+def _singular(segment: str) -> str:
+ word = segment.rsplit("/", 1)[-1]
+ return word[:-1] if word.endswith("s") else word
+
+
+def _resource_routes(
+ content: str,
+ calls: list[_Call],
+ at: int,
+ segments: list[str | None],
+ controller: str | None,
+ offset: int,
+) -> Iterator[RouteMatch]:
+ call = calls[at]
+ args = content[call.paren + 1 : call.close]
+ spans = [args[a:b] for a, b in _php_args(args)]
+ declared: list[tuple[str | None, str | None]] # (resource name, controller)
+ if call.name in ("resources", "apiresources"):
+ declared = [
+ (k, _class_ref(v)) for k, v in (_entries(spans[0]) if spans else {}).items()
+ ]
+ options: dict[str, str] = {}
+ else:
+ declared = [
+ (
+ _literal(spans[0]) if spans else None,
+ _class_ref(spans[1]) if len(spans) > 1 else None,
+ )
+ ]
+ options = _entries(spans[2]) if len(spans) > 2 else {}
+ only = _LARAVEL_WORD_RE.findall(options["only"]) if "only" in options else None
+ excluded = set(_LARAVEL_WORD_RE.findall(options.get("except", "")))
+ shallow = False
+ for mod in calls[at + 1 :]:
+ mod_args = content[mod.paren + 1 : mod.close]
+ if mod.name == "only":
+ only = _LARAVEL_WORD_RE.findall(mod_args)
+ elif mod.name == "except":
+ excluded |= set(_LARAVEL_WORD_RE.findall(mod_args))
+ elif mod.name == "shallow":
+ shallow = True
+ actions = [
+ a
+ for a in _RESOURCE_ACTIONS
+ if not (call.name.startswith("api") and a[0] in _FORM_ACTIONS)
+ and (only is None or a[0] in only)
+ and a[0] not in excluded
+ ]
+ for name, cls in declared:
+ handler = cls or controller
+ if not name:
+ # A computed name still names its controller for the graph.
+ yield RouteMatch("RESOURCE", None, None, handler, offset, call.paren)
+ continue
+ collection, member = _resource_paths(name, shallow)
+ for _action, verbs, suffix, on_member in actions:
+ path = _join_segments([*segments, (member if on_member else collection) + suffix])
+ for verb in verbs:
+ yield RouteMatch(
+ verb, None if path is None else f"/{path}", None, handler, offset, call.paren
+ )
+
+
+def _verb_routes(
+ content: str,
+ calls: list[_Call],
+ at: int,
+ segments: list[str | None],
+ controller: str | None,
+ offset: int,
+) -> Iterator[RouteMatch]:
+ call = calls[at]
+ args = content[call.paren + 1 : call.close]
+ spans = _php_args(args, max_split=2 if call.name == "match" else 1)
+ if call.name == "match":
+ verbs = [w.upper() for w in _LARAVEL_WORD_RE.findall(args[slice(*spans[0])])] if spans else []
+ spans = spans[1:]
+ else:
+ verbs = [call.name.upper()]
+ head = _LARAVEL_LITERAL_RE.match(args, spans[0][0]) if spans else None
+ raw = head.group("text") if head else None
+ if raw is None or None in segments:
+ path = None
+ elif not any(segments):
+ path = raw or None # no prefix in scope: the literal as written
+ else:
+ joined = _join_segments([*segments, raw])
+ path = None if joined is None else f"/{joined}"
+ # Only past the path argument: it can itself contain `X::class` or a quoted
+ # 'word@word', neither of which is the handler
+ # (`Route::get(trans('Contact@us'), [PageController::class, ...])`).
+ handler: str | None = None
+ if len(spans) > 1:
+ m = _LARAVEL_HANDLER_RE.search(args, spans[1][0])
+ if m:
+ handler = m.group("array") or m.group("legacy") or m.group("cls")
+ elif _literal(args[slice(*spans[1])]) is not None:
+ handler = controller # a bare method name, inside `controller(...)`
+ for verb in verbs:
+ yield RouteMatch(verb, path, None, handler, offset, call.paren)
+
+
+def laravel_routes(content: str, prefix: str = "") -> Iterator[RouteMatch]:
+ """Route registrations in *content*, served under *prefix*.
+
+ Reads `Route::verb(...)`, the chained `Route::middleware(...)->verb(...)`,
+ `Route::match`, and expands `resource` / `apiResource` / `resources` into
+ the routes they register (honouring `only`, `except` and `shallow`). Paths
+ carry every enclosing group prefix (`Route::prefix('x')->group`,
+ `Route::group(['prefix' => 'x'], ...)`, nested), and a bare method name
+ inside `Route::controller(C::class)->group` takes that controller. *prefix*
+ is where the file itself is served (``api`` for ``routes/api.php``, see
+ :func:`laravel_route_prefix`).
The arguments are delimited by the call's own parens: a route's path is
routinely a concatenation containing a call of its own, which a scan to the
@@ -362,29 +700,82 @@ def laravel_routes(content: str) -> Iterator[RouteMatch]:
``handler`` is the controller class only; the member name the array form
also carries is dropped, since the graph consumer links to the class's file.
"""
- for m in _LARAVEL_CALL_RE.finditer(content):
- close = match_paren(content, m.start("paren"), hash_comments=True)
- if close == -1:
- continue
- args = content[m.end() : close]
- path = _LARAVEL_PATH_RE.match(args)
- # Only past the first top-level comma: the path expression can itself
- # contain `X::class` or a quoted 'word@word', neither of which is the
- # handler (`Route::get(trans('Contact@us'), [PageController::class, ...])`).
- second = _next_top_level_comma(args, hash_comments=True)
- handler = _LARAVEL_HANDLER_RE.search(args, second) if second != -1 else None
- yield RouteMatch(
- verb=m.group("verb").upper(),
- path=path.group("path") or None if path else None,
- receiver=None,
- handler=(
- handler.group("array") or handler.group("legacy") or handler.group("cls")
- if handler
- else None
- ),
- offset=m.start(),
- paren_offset=m.start("paren"),
+ scan = _laravel_scan(content)
+ for offset, calls, at in scan.routes:
+ enclosing = scan.enclosing(offset)
+ chain_prefix, chain_controller = _chain_attrs(content, calls[:at])
+ segments = [prefix, *(g.prefix for g in enclosing), chain_prefix]
+ controller = chain_controller or next(
+ (g.controller for g in reversed(enclosing) if g.controller), None
)
+ expand = _resource_routes if calls[at].name in _LARAVEL_RESOURCES else _verb_routes
+ yield from expand(content, calls, at, segments, controller, offset)
+
+
+def laravel_route_file_prefixes(content: str) -> dict[str, str | None]:
+ """``route file basename -> prefix`` for each route file *content* loads.
+
+ Three registrations: `withRouting(api: ..., apiPrefix: ...)` in
+ ``bootstrap/app.php``; a group given a file (`Route::prefix('api')
+ ->group(base_path('routes/api.php'))`); and a file required inside a
+ closure group. A prefix this cannot read maps to ``None``.
+
+ Deliberate ceiling: a file loaded from inside another route file does not
+ inherit that file's own prefix, and files are keyed by basename, so two
+ route files of one name share a key (the merge drops them when they
+ disagree).
+ """
+ out: dict[str, str | None] = {}
+ if ".php" not in content:
+ return out
+ routing = _LARAVEL_WITH_ROUTING_RE.search(content) if "withRouting" in content else None
+ if routing:
+ close = match_paren(content, routing.start("paren"), hash_comments=True)
+ args = content[routing.end() : close] if close != -1 else ""
+ named = {
+ m.group("key"): m.group("value")
+ for a, b in _php_args(args)
+ if (m := _LARAVEL_NAMED_ARG_RE.fullmatch(args[a:b].strip()))
+ }
+ api_prefix = _literal(named["apiPrefix"]) if "apiPrefix" in named else "api"
+ for key, prefix in (("web", ""), ("api", api_prefix)):
+ for f in _LARAVEL_FILE_RE.finditer(named.get(key, "")):
+ out[f.group("name")] = prefix
+ if "Route::" not in content or ("group" not in content and "require" not in content):
+ return out # nothing here can load a route file
+ scan = _laravel_scan(content)
+ for offset, name, own in scan.files:
+ out[name] = _join_segments([*(g.prefix for g in scan.enclosing(offset)), own])
+ for m in _LARAVEL_REQUIRE_RE.finditer(content):
+ enclosing = scan.enclosing(m.start())
+ if enclosing:
+ out[m.group("name")] = _join_segments(g.prefix for g in enclosing)
+ return out
+
+
+def laravel_route_file(rel_path: str) -> bool:
+ """Whether *rel_path* is a route file: a PHP file under a ``routes`` directory.
+
+ Case-insensitive, as module packages spell it ``Routes``.
+ """
+ return rel_path.endswith(".php") and "routes" in rel_path.lower().split("/")[:-1]
+
+
+def laravel_route_prefix(rel_path: str, declared: Mapping[str, str | None]) -> str | None:
+ """The prefix Laravel serves the route file at *rel_path* under.
+
+ *declared* is :func:`laravel_route_file_prefixes` merged over the repo, by
+ basename; declarations that disagree were dropped by the merge, so the
+ default applies. Undeclared, ``routes/api.php`` is served under ``api``
+ (the framework default) and every other route file at the root. ``None``
+ refuses the file.
+ """
+ if not laravel_route_file(rel_path):
+ return ""
+ folder, _, name = rel_path.rpartition("/")
+ if name in declared:
+ return declared[name]
+ return "api" if name == "api.php" and folder.rpartition("/")[2].lower() == "routes" else ""
# ---------------------------------------------------------------------------
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 bff80afb0..eb8cf8bbb 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
@@ -56,6 +56,30 @@ def file_namespace(text: str) -> str | None:
return found.pop() if len(found) == 1 else None
+def php_use_aliases(parsed: Any) -> dict[str, str]:
+ """Local name -> imported FQN for every ``use`` in a parsed PHP file."""
+ return {
+ binding.local_name: binding.exported_name
+ for imp in parsed.imports
+ for binding in imp.bindings
+ if binding.local_name and binding.exported_name
+ }
+
+
+def qualify_php_name(name: str, namespace: str | None, aliases: dict[str, str]) -> str:
+ """The FQN class *name* denotes in a file with *namespace* and ``use`` *aliases*.
+
+ A leading separator makes it absolute; otherwise its first segment goes
+ through a ``use`` alias, else it is relative to the file's namespace.
+ """
+ if name.startswith("\\"):
+ return name[1:]
+ head, sep, rest = name.partition("\\")
+ if head in aliases:
+ return aliases[head] + sep + rest
+ return f"{namespace}\\{name}" if namespace else name
+
+
def resolve_php_same_namespace_refs(
graph: nx.DiGraph,
parsed_files: dict[str, Any],
@@ -81,35 +105,19 @@ def resolve_php_same_namespace_refs(
if not index:
return 0
- def aliases(path: str) -> dict[str, str]:
- """Local name -> imported FQN for every ``use`` in *path*."""
- return {
- binding.local_name: binding.exported_name
- for imp in parsed_files[path].imports
- for binding in imp.bindings
- if binding.local_name and binding.exported_name
- }
-
def declarers(fqn: str) -> list[str]:
ns, _, name = fqn.rpartition("\\")
return index.get(ns, {}).get(name, [])
def plan(path: str, _text: str) -> FileScope:
- ns, bound = namespaces[path], aliases(path)
+ ns, bound = namespaces[path], php_use_aliases(parsed_files[path])
types = index.get(ns or "", {})
def same_namespace(ident: str) -> list[str]:
return [] if "\\" in ident else types.get(ident, [])
def qualified(ident: str) -> list[str]:
- if "\\" not in ident:
- return []
- if ident.startswith("\\"):
- return declarers(ident[1:])
- head, _, rest = ident.partition("\\")
- if head in bound:
- return declarers(f"{bound[head]}\\{rest}")
- return declarers(f"{ns}\\{ident}" if ns else ident)
+ return declarers(qualify_php_name(ident, ns, bound)) if "\\" in ident else []
return FileScope(
tiers=(
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/php.py b/packages/core/src/repowise/core/ingestion/resolvers/php.py
index c01ac4fcb..c805db1ac 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/php.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/php.py
@@ -32,6 +32,15 @@ def resolve_php_import(module_path: str, importer_path: str, ctx: ResolverContex
return root_candidate
return ctx.add_external_node(module_path)
+ return resolve_php_class(module_path, ctx) or ctx.add_external_node(module_path)
+
+
+def resolve_php_class(module_path: str, ctx: ResolverContext) -> str | None:
+ """The first-party file declaring class *module_path* (an FQN), or None.
+
+ None for a class that lives in a dependency. Adds nothing to the graph,
+ so a framework handler can resolve a class name it read from code.
+ """
# composer.json autoload.psr-4 is the authoritative mapping in real
# Laravel/Symfony/etc. apps; consult before stem fallback so non-conventional
# prefix maps (``"App\\": "src/"``) resolve correctly.
@@ -55,4 +64,4 @@ def resolve_php_import(module_path: str, importer_path: str, ctx: ResolverContex
result = next(iter(basename_index(ctx).get(f"{local}.php", ())), None)
if result and (not unclaimed or in_classmap(result, ctx)):
return result
- return ctx.add_external_node(module_path)
+ return None
diff --git a/packages/core/src/repowise/core/workspace/contracts.py b/packages/core/src/repowise/core/workspace/contracts.py
index 5ce7d0ec0..9e1d0a76c 100644
--- a/packages/core/src/repowise/core/workspace/contracts.py
+++ b/packages/core/src/repowise/core/workspace/contracts.py
@@ -52,7 +52,10 @@ CONTRACTS_FILENAME = "contracts.json"
# Version 8 adds bounded OpenAPI 3.x schemas and their extraction diagnostics.
# Version 9 gives topic contracts a kind and routing key, and adds RabbitMQ
# queue bindings.
-CONTRACTS_VERSION = 9
+# Version 10 serves Laravel routes under their group and route-file prefixes
+# with resources expanded, and adds Laravel migration, model-convention and
+# query-builder table contracts.
+CONTRACTS_VERSION = 10
#: ``meta["kind"]`` of a topic contract: the destination a broker call names.
#: A queue is read by one consumer group; a topic or subject fans out; an
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/__init__.py b/packages/core/src/repowise/core/workspace/extractors/data/__init__.py
index 7f6bf4138..d255c7889 100644
--- a/packages/core/src/repowise/core/workspace/extractors/data/__init__.py
+++ b/packages/core/src/repowise/core/workspace/extractors/data/__init__.py
@@ -1,7 +1,7 @@
"""App-to-database contract extraction.
Scans source files for table *providers* (DDL, migrations, ORM entities) and
-table *consumers* (SQL string literals in app code). Each recogniser is an
+table *consumers* (SQL string literals and query builders in app code). Each recogniser is an
independent dialect module registered in :data:`PROVIDER_DIALECTS` /
:data:`CONSUMER_DIALECTS`, run by the shared :class:`..dialect.DialectExtractor`.
Matching happens downstream in :mod:`repowise.core.workspace.matching` on the
@@ -13,11 +13,11 @@ from __future__ import annotations
from ..dialect import ContractDialect, DialectExtractor
from .ddl import DdlDialect
+from .laravel import EloquentDialect, LaravelMigrationDialect, LaravelQueryDialect
from .names import normalize_table_name
from .orm_models import (
ActiveRecordDialect,
EfCoreDialect,
- EloquentDialect,
JpaDialect,
SqlAlchemyDjangoDialect,
)
@@ -31,10 +31,11 @@ PROVIDER_DIALECTS: tuple[ContractDialect, ...] = (
EfCoreDialect(),
ActiveRecordDialect(),
EloquentDialect(),
+ LaravelMigrationDialect(),
)
# Table-access recognisers.
-CONSUMER_DIALECTS: tuple[ContractDialect, ...] = (SqlStringsDialect(),)
+CONSUMER_DIALECTS: tuple[ContractDialect, ...] = (SqlStringsDialect(), LaravelQueryDialect())
class DataExtractor(DialectExtractor):
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/ddl.py b/packages/core/src/repowise/core/workspace/extractors/data/ddl.py
index 0d40eba1a..8032e3de5 100644
--- a/packages/core/src/repowise/core/workspace/extractors/data/ddl.py
+++ b/packages/core/src/repowise/core/workspace/extractors/data/ddl.py
@@ -13,7 +13,7 @@ import logging
from typing import TYPE_CHECKING
from ..base import ScanContext
-from .dialect import build_table_provider
+from .dialect import ALTER_CONFIDENCE, build_table_provider
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract
@@ -58,6 +58,7 @@ class DdlDialect:
continue
raw: str | None = None
confidence = 0.85
+ schema = "create"
if isinstance(stmt, exp.Create) and (stmt.kind or "").upper() in _CREATE_KINDS:
target = stmt.this
if isinstance(target, exp.Schema):
@@ -65,12 +66,13 @@ class DdlDialect:
raw = _qualified_name(target)
elif isinstance(stmt, exp.Alter) and (stmt.args.get("kind") or "").upper() == "TABLE":
raw = _qualified_name(stmt.this)
- confidence = 0.8
+ confidence = ALTER_CONFIDENCE
+ schema = "alter"
if raw is None or raw in seen:
continue
seen.add(raw)
contract = build_table_provider(
- ctx, table_raw=raw, framework="sql-ddl", confidence=confidence
+ ctx, table_raw=raw, framework="sql-ddl", confidence=confidence, schema=schema
)
if contract is not None:
out.append(contract)
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py b/packages/core/src/repowise/core/workspace/extractors/data/dialect.py
index bdb362629..67c288e21 100644
--- a/packages/core/src/repowise/core/workspace/extractors/data/dialect.py
+++ b/packages/core/src/repowise/core/workspace/extractors/data/dialect.py
@@ -9,8 +9,11 @@ scheme (``data::<normalized table>``) and the normalization rules stay in
from __future__ import annotations
+import re
+from collections.abc import Callable
from typing import TYPE_CHECKING
+from ..base import line_at
from ..dialect import build_contract
from .names import normalize_table_name
@@ -27,12 +30,15 @@ def build_table_provider(
framework: str,
line: int | None = None,
confidence: float = 0.85,
+ schema: str | None = None,
) -> Contract | None:
"""Build a provider contract for a declared table, or ``None``.
Providers are declarations of ownership: a ``CREATE TABLE``, an ORM entity,
a migration. ``None`` when the raw token does not normalize to a concrete
- table name.
+ table name. *schema* (``create`` / ``alter``) marks a declaration that
+ defines the table's schema rather than modelling it, which is how the
+ repo owning a shared table is told from the repos reading it.
"""
table = normalize_table_name(table_raw)
if table is None:
@@ -45,7 +51,7 @@ def build_table_provider(
symbol_name=f"{framework}:{table_raw}",
confidence=confidence,
line=line,
- meta={"table": table, "framework": framework},
+ meta={"table": table, "framework": framework, **({"schema": schema} if schema else {})},
)
@@ -77,3 +83,60 @@ def build_table_consumer(
line=line,
meta={"table": table, "verb": verb, "client": client},
)
+
+
+EXPLICIT_CONFIDENCE = 0.85
+CONVENTION_CONFIDENCE = 0.6
+# A declaration that evolves a table (``ALTER TABLE``, ``Schema::table``).
+ALTER_CONFIDENCE = 0.8
+
+
+#: One table declaration: ``(raw_name, confidence, line)``.
+_Found = tuple[str, float, int]
+
+
+def found_names(
+ pattern: re.Pattern[str],
+ content: str,
+ confidence: float,
+ transform: Callable[[str], str] = str,
+) -> list[_Found]:
+ r"""Every match of *pattern*'s first group, with the line it sits on.
+
+ The line comes from the group, not the match: three of these patterns open
+ with ``^\s*`` under ``MULTILINE``, where ``^`` matches at a preceding blank
+ line and ``\s*`` eats the newlines, putting ``m.start()`` above the
+ declaration.
+ """
+ return [
+ (transform(m.group(1)), confidence, line_at(content, m.start(1)))
+ for m in pattern.finditer(content)
+ ]
+
+
+def dedup_emit(
+ ctx: ScanContext,
+ framework: str,
+ found: list[_Found],
+ *,
+ schema: str | None = None,
+ seen: set[str] | None = None,
+) -> list[Contract]:
+ """One provider per raw name in *found*, skipping names already in *seen*."""
+ out: list[Contract] = []
+ seen = set() if seen is None else seen
+ for raw, confidence, line in found:
+ if raw in seen:
+ continue
+ seen.add(raw)
+ contract = build_table_provider(
+ ctx,
+ table_raw=raw,
+ framework=framework,
+ line=line,
+ confidence=confidence,
+ schema=schema,
+ )
+ if contract is not None:
+ out.append(contract)
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/laravel.py b/packages/core/src/repowise/core/workspace/extractors/data/laravel.py
new file mode 100644
index 000000000..c8e0813d9
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/extractors/data/laravel.py
@@ -0,0 +1,150 @@
+"""Laravel data dialects: Eloquent models, schema migrations, the query builder.
+
+* **Eloquent** (provider): ``protected $table = 'x'``, or Laravel's own
+ convention when a model names none, the snake-case plural of the class
+ (``GuestlistEntry`` -> ``guestlist_entries``).
+* **Migrations** (provider): ``Schema::create('x', ...)`` declares the table,
+ ``Schema::table('x', ...)`` evolves it. Both carry ``meta['schema']``, which
+ is what marks the repo that owns the table's schema.
+* **Query builder** (consumer): ``DB::table('x')``, read as an insert, update
+ or delete when the statement chains one, else a select. Raw SQL through
+ ``DB::select(...)`` is already the SQL-strings dialect's.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from repowise.core.ingestion.framework_routes import scan_code
+
+from ..base import ScanContext, line_at
+from ..langs import PHP
+from .dialect import (
+ ALTER_CONFIDENCE,
+ CONVENTION_CONFIDENCE,
+ EXPLICIT_CONFIDENCE,
+ build_table_consumer,
+ dedup_emit,
+ found_names,
+)
+from .names import pluralize, snake_case
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+
+# Query-builder writes whose name does not start with the SQL verb they run.
+_WRITE_ALIASES = {"upsert": "insert", "updateorinsert": "update", "truncate": "delete"}
+
+
+class EloquentDialect:
+ """Eloquent models: the ``$table`` property, else the class-name convention."""
+
+ name = "eloquent"
+ extensions = PHP
+
+ _TABLE_RE = re.compile(r"protected\s+\$table\s*=\s*['\"](\w+)['\"]")
+ # Only the framework's own bases: a model extending an app base class
+ # (`extends BaseModel`) is missed rather than guessed at, and a pivot's
+ # default table follows a different rule.
+ _MODEL_CLASS_RE = re.compile(
+ r"^[ \t]*(?:final[ \t]+)?class[ \t]+(\w+)[ \t]+extends[ \t]+"
+ r"\\?(?:[\w\\]*\\)?(?:Model|Authenticatable)\b",
+ re.MULTILINE,
+ )
+ # The file imports Eloquent (or the auth user built on it), so `Model` is
+ # that `Model` and not some other library's.
+ _ELOQUENT_IMPORT = ("Illuminate\\Database\\Eloquent", "Illuminate\\Foundation\\Auth")
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ found = found_names(self._TABLE_RE, ctx.content, EXPLICIT_CONFIDENCE)
+ if not found and any(i in ctx.content for i in self._ELOQUENT_IMPORT):
+ found = found_names(
+ self._MODEL_CLASS_RE,
+ ctx.content,
+ CONVENTION_CONFIDENCE,
+ lambda cls: pluralize(snake_case(cls)),
+ )
+ return dedup_emit(ctx, self.name, found)
+
+
+class LaravelMigrationDialect:
+ """``Schema::create`` / ``Schema::table`` in migrations."""
+
+ name = "laravel-migration"
+ extensions = PHP
+
+ _HEAD = r"\bSchema::(?:connection\s*\([^)]*\)\s*->\s*)?"
+ _CREATE_RE = re.compile(_HEAD + r"create\s*\(\s*['\"]([\w.]+)['\"]")
+ _ALTER_RE = re.compile(_HEAD + r"table\s*\(\s*['\"]([\w.]+)['\"]")
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ if "Schema::" not in ctx.content:
+ return [] # far cheaper than the regexes, which have no literal prefix
+ created = found_names(self._CREATE_RE, ctx.content, EXPLICIT_CONFIDENCE)
+ altered = found_names(self._ALTER_RE, ctx.content, ALTER_CONFIDENCE)
+ return dedup_emit(ctx, self.name, created, schema="create") + dedup_emit(
+ ctx, self.name, altered, schema="alter"
+ )
+
+
+class LaravelQueryDialect:
+ """``DB::table('x')`` query-builder access."""
+
+ name = "laravel-db"
+ extensions = PHP
+
+ _TABLE_RE = re.compile(
+ r"\bDB::(?:connection\s*\([^)]*\)\s*->\s*)?table\s*\(\s*"
+ r"(?P<q>['\"])(?P<table>[\w.]+)(?:\s+as\s+\w+)?(?P=q)"
+ )
+ # A write the statement chains, first wins; anything else reads.
+ _WRITE_RE = re.compile(
+ r"->\s*(?P<method>insert\w*|upsert|updateOrInsert|update\w*|increment\w*"
+ r"|decrement\w*|delete|truncate)\s*\("
+ )
+
+ def _verb(self, content: str, start: int) -> str:
+ # Only the statement's own chain counts: a `;` or `->write(` inside a
+ # string, an argument or a closure passed to it is not this statement's.
+ # The scan starts inside `table(`, so chain level is depth -1.
+ write = None
+ for i, c, depth in scan_code(content, start, hash_comments=True):
+ if depth >= 0:
+ continue
+ if c == ";":
+ break
+ if c == "-" and (write := self._WRITE_RE.match(content, i)):
+ break
+ if write is None:
+ return "select"
+ method = write.group("method").lower()
+ if method in _WRITE_ALIASES:
+ return _WRITE_ALIASES[method]
+ for verb in ("insert", "update", "delete"):
+ if method.startswith(verb):
+ return verb
+ return "update" # increment / decrement
+
+ def extract(self, ctx: ScanContext) -> list[Contract]:
+ out: list[Contract] = []
+ if "DB::" not in ctx.content:
+ return out
+ seen: set[tuple[str, str]] = set()
+ for m in self._TABLE_RE.finditer(ctx.content):
+ verb = self._verb(ctx.content, m.end())
+ key = (m.group("table").lower(), verb)
+ if key in seen:
+ continue
+ seen.add(key)
+ contract = build_table_consumer(
+ ctx,
+ table_raw=m.group("table"),
+ verb=verb,
+ client=self.name,
+ line=line_at(ctx.content, m.start()),
+ )
+ if contract is not None:
+ out.append(contract)
+ return out
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/names.py b/packages/core/src/repowise/core/workspace/extractors/data/names.py
index 4627cf7bb..dc9a74f61 100644
--- a/packages/core/src/repowise/core/workspace/extractors/data/names.py
+++ b/packages/core/src/repowise/core/workspace/extractors/data/names.py
@@ -65,3 +65,21 @@ def normalize_table_name(raw: str) -> str | None:
if schema in _DEFAULT_SCHEMAS or not _IDENT_RE.match(schema):
schema = None
return f"{schema}.{table}" if schema else table
+
+
+def snake_case(name: str) -> str:
+ return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()
+
+
+def pluralize(name: str) -> str:
+ """Naive English pluralization, matching the common ActiveRecord cases.
+
+ Deliberate ceiling: irregular nouns (person/people) are wrong here and
+ yield a missed link, not a false one. Upgrade path: vendor a real
+ inflector if Rails smoke tests show it matters.
+ """
+ if name.endswith(("s", "x", "z", "ch", "sh")):
+ return name + "es"
+ if name.endswith("y") and len(name) > 1 and name[-2] not in "aeiou":
+ return name[:-1] + "ies"
+ return name + "s"
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/orm_models.py b/packages/core/src/repowise/core/workspace/extractors/data/orm_models.py
index a4049fee0..701b3cffa 100644
--- a/packages/core/src/repowise/core/workspace/extractors/data/orm_models.py
+++ b/packages/core/src/repowise/core/workspace/extractors/data/orm_models.py
@@ -5,7 +5,7 @@ which table the repo owns. Consumers of the model are already visible through
the import graph, so this module never scans for model *usage*; it only emits
the declaration.
-Explicit names (``__tablename__``, ``@Table(name=...)``, ``$table``,
+Explicit names (``__tablename__``, ``@Table(name=...)``,
``self.table_name``, ``db_table``) are extracted verbatim at high confidence.
Convention-derived names (JPA entity class, ActiveRecord class, EF ``DbSet``
property) are emitted at lower confidence: a wrong guess costs a missed link
@@ -15,80 +15,16 @@ property) are emitted at lower confidence: a wrong guess costs a missed link
from __future__ import annotations
import re
-from collections.abc import Callable
from typing import TYPE_CHECKING
-from ..base import ScanContext, line_at
-from ..langs import CSHARP, JAVA, KOTLIN, PHP, PYTHON, RUBY
-from .dialect import build_table_provider
+from ..base import ScanContext
+from ..langs import CSHARP, JAVA, KOTLIN, PYTHON, RUBY
+from .dialect import CONVENTION_CONFIDENCE, EXPLICIT_CONFIDENCE, dedup_emit, found_names
+from .names import pluralize, snake_case
if TYPE_CHECKING:
from repowise.core.workspace.contracts import Contract
-_EXPLICIT_CONFIDENCE = 0.85
-_CONVENTION_CONFIDENCE = 0.6
-
-
-def _snake_case(name: str) -> str:
- return re.sub(r"(?<=[a-z0-9])(?=[A-Z])", "_", name).lower()
-
-
-def _pluralize(name: str) -> str:
- """Naive English pluralization, matching the common ActiveRecord cases.
-
- Deliberate ceiling: irregular nouns (person/people) are wrong here and
- yield a missed link, not a false one. Upgrade path: vendor a real
- inflector if Rails smoke tests show it matters.
- """
- if name.endswith(("s", "x", "z", "ch", "sh")):
- return name + "es"
- if name.endswith("y") and len(name) > 1 and name[-2] not in "aeiou":
- return name[:-1] + "ies"
- return name + "s"
-
-
-#: One table declaration: ``(raw_name, confidence, line)``.
-_Found = tuple[str, float, int]
-
-
-def _found(
- pattern: re.Pattern[str],
- content: str,
- confidence: float,
- transform: Callable[[str], str] = str,
-) -> list[_Found]:
- r"""Every match of *pattern*'s first group, with the line it sits on.
-
- The line comes from the group, not the match: three of these patterns open
- with ``^\s*`` under ``MULTILINE``, where ``^`` matches at a preceding blank
- line and ``\s*`` eats the newlines, putting ``m.start()`` above the
- declaration.
- """
- return [
- (transform(m.group(1)), confidence, line_at(content, m.start(1)))
- for m in pattern.finditer(content)
- ]
-
-
-def _dedup_emit(
- ctx: ScanContext,
- framework: str,
- found: list[_Found],
-) -> list[Contract]:
- out: list[Contract] = []
- seen: set[str] = set()
- for raw, confidence, line in found:
- if raw in seen:
- continue
- seen.add(raw)
- contract = build_table_provider(
- ctx, table_raw=raw, framework=framework, line=line, confidence=confidence
- )
- if contract is not None:
- out.append(contract)
- return out
-
-
class SqlAlchemyDjangoDialect:
"""Python ORMs and migrations: SQLAlchemy ``__tablename__``, Django
``Meta.db_table``, SQLModel ``table=True`` classes (default table = class
@@ -103,11 +39,14 @@ class SqlAlchemyDjangoDialect:
_SQLMODEL_RE = re.compile(r"\bclass\s+(\w+)\([^)]*\btable\s*=\s*True[^)]*\)")
def extract(self, ctx: ScanContext) -> list[Contract]:
- found = _found(self._TABLENAME_RE, ctx.content, _EXPLICIT_CONFIDENCE)
- found += _found(self._DB_TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)
- found += _found(self._CREATE_TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)
- found += _found(self._SQLMODEL_RE, ctx.content, _CONVENTION_CONFIDENCE, str.lower)
- return _dedup_emit(ctx, self.name, found)
+ # A migration's `create_table` defines the schema; the rest model it.
+ seen: set[str] = set()
+ created = found_names(self._CREATE_TABLE_RE, ctx.content, EXPLICIT_CONFIDENCE)
+ out = dedup_emit(ctx, self.name, created, schema="create", seen=seen)
+ found = found_names(self._TABLENAME_RE, ctx.content, EXPLICIT_CONFIDENCE)
+ found += found_names(self._DB_TABLE_RE, ctx.content, EXPLICIT_CONFIDENCE)
+ found += found_names(self._SQLMODEL_RE, ctx.content, CONVENTION_CONFIDENCE, str.lower)
+ return out + dedup_emit(ctx, self.name, found, seen=seen)
class JpaDialect:
@@ -123,14 +62,14 @@ class JpaDialect:
)
def extract(self, ctx: ScanContext) -> list[Contract]:
- found = _found(self._TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)
+ found = found_names(self._TABLE_RE, ctx.content, EXPLICIT_CONFIDENCE)
if not found:
# Only fall back to the class-name convention when no explicit
# @Table names the table (one entity per file is the JPA norm).
- found = _found(
- self._ENTITY_CLASS_RE, ctx.content, _CONVENTION_CONFIDENCE, _snake_case
+ found = found_names(
+ self._ENTITY_CLASS_RE, ctx.content, CONVENTION_CONFIDENCE, snake_case
)
- return _dedup_emit(ctx, self.name, found)
+ return dedup_emit(ctx, self.name, found)
class EfCoreDialect:
@@ -143,9 +82,9 @@ class EfCoreDialect:
_DBSET_RE = re.compile(r"\bDbSet<\s*\w+\s*>\s+(\w+)")
def extract(self, ctx: ScanContext) -> list[Contract]:
- found = _found(self._TABLE_ATTR_RE, ctx.content, _EXPLICIT_CONFIDENCE)
- found += _found(self._DBSET_RE, ctx.content, _CONVENTION_CONFIDENCE)
- return _dedup_emit(ctx, self.name, found)
+ found = found_names(self._TABLE_ATTR_RE, ctx.content, EXPLICIT_CONFIDENCE)
+ found += found_names(self._DBSET_RE, ctx.content, CONVENTION_CONFIDENCE)
+ return dedup_emit(ctx, self.name, found)
class ActiveRecordDialect:
@@ -160,25 +99,12 @@ class ActiveRecordDialect:
)
def extract(self, ctx: ScanContext) -> list[Contract]:
- found = _found(self._TABLE_NAME_RE, ctx.content, _EXPLICIT_CONFIDENCE)
+ found = found_names(self._TABLE_NAME_RE, ctx.content, EXPLICIT_CONFIDENCE)
if not found:
- found = _found(
+ found = found_names(
self._MODEL_CLASS_RE,
ctx.content,
- _CONVENTION_CONFIDENCE,
- lambda m: _pluralize(_snake_case(m)),
+ CONVENTION_CONFIDENCE,
+ lambda m: pluralize(snake_case(m)),
)
- return _dedup_emit(ctx, self.name, found)
-
-
-class EloquentDialect:
- """Laravel Eloquent: ``protected $table = '...'``."""
-
- name = "eloquent"
- extensions = PHP
-
- _TABLE_RE = re.compile(r"protected\s+\$table\s*=\s*['\"](\w+)['\"]")
-
- def extract(self, ctx: ScanContext) -> list[Contract]:
- found = _found(self._TABLE_RE, ctx.content, _EXPLICIT_CONFIDENCE)
- return _dedup_emit(ctx, self.name, found)
+ return dedup_emit(ctx, self.name, found)
diff --git a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py b/packages/core/src/repowise/core/workspace/extractors/http/laravel.py
index dbcf0a7f1..ec336294d 100644
--- a/packages/core/src/repowise/core/workspace/extractors/http/laravel.py
+++ b/packages/core/src/repowise/core/workspace/extractors/http/laravel.py
@@ -1,14 +1,22 @@
"""Laravel (PHP) HTTP provider dialect — ``Route::get('/path', ...)``.
The route call is recognised by ``ingestion.framework_routes``, shared with the
-graph-edge builder that reads the same call for its controller class.
+graph-edge builder that reads the same call for its controller class. Where a
+route file is served (``routes/api.php`` under ``/api``, or whatever
+``bootstrap/app.php`` or a route provider declares) is collected repo-wide
+through the orchestrator's mount pass, under keys no router variable can take.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
-from repowise.core.ingestion.framework_routes import HTTP_METHODS, laravel_routes
+from repowise.core.ingestion.framework_routes import (
+ HTTP_METHODS,
+ laravel_route_file_prefixes,
+ laravel_route_prefix,
+ laravel_routes,
+)
from ..base import line_at
from ..langs import PHP
@@ -19,16 +27,38 @@ if TYPE_CHECKING:
from ..base import ScanContext
+_MOUNT_KEY = "laravel-route-file:"
+# The mount merge drops a key two files disagree on. This second key, always
+# the same value, survives it, so a declared-but-dropped file reads as
+# ambiguous (refused) rather than undeclared (served at the default).
+_DECLARED_KEY = "laravel-route-file-declared:"
+# Mount values are strings; a declared prefix this cannot read travels as this.
+_UNREADABLE = "\0"
+
class LaravelDialect:
name = "laravel"
extensions = PHP
+ def collect_mounts(self, content: str) -> dict[str, str]:
+ out: dict[str, str] = {}
+ for name, prefix in laravel_route_file_prefixes(content).items():
+ out[f"{_MOUNT_KEY}{name}"] = _UNREADABLE if prefix is None else prefix
+ out[f"{_DECLARED_KEY}{name}"] = ""
+ return out
+
def extract(self, ctx: ScanContext) -> list[Contract]:
+ name = ctx.rel_path.rpartition("/")[2]
+ declared: dict[str, str | None] = {}
+ if f"{_DECLARED_KEY}{name}" in ctx.mounts:
+ value = ctx.mounts.get(f"{_MOUNT_KEY}{name}", _UNREADABLE)
+ declared[name] = None if value == _UNREADABLE else value
+ prefix = laravel_route_prefix(ctx.rel_path, declared)
+ if prefix is None:
+ return [] # served under a prefix this cannot read
out: list[Contract] = []
- for route in laravel_routes(ctx.content):
- # `resource`/`apiResource` stand for a set of routes and `any`/`match`
- # for an unnamed verb, so neither is one method+path contract.
+ for route in laravel_routes(ctx.content, prefix):
+ # `any` names no single verb, and a computed path no one route.
if route.verb not in HTTP_METHODS or not route.path:
continue
c = build_provider_contract(
diff --git a/packages/core/src/repowise/core/workspace/matching/__init__.py b/packages/core/src/repowise/core/workspace/matching/__init__.py
index f682b5ca6..7e6db6f67 100644
--- a/packages/core/src/repowise/core/workspace/matching/__init__.py
+++ b/packages/core/src/repowise/core/workspace/matching/__init__.py
@@ -16,7 +16,7 @@ from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING
-from . import http, topic
+from . import data, http, topic
from .common import MatchState, find_matching_keys, internal, prefer_target_repo
from .http import annotate_consumer_targets
@@ -41,6 +41,7 @@ MATCHERS: dict[str, TypeMatcher] = {
"topic": TypeMatcher(
deferred=topic.is_binding, accepts=topic.accepts, passes=(topic.binding_pass,)
),
+ "data": TypeMatcher(passes=(data.shared_table_pass,)),
}
_NO_RULES = TypeMatcher()
diff --git a/packages/core/src/repowise/core/workspace/matching/data.py b/packages/core/src/repowise/core/workspace/matching/data.py
new file mode 100644
index 000000000..13241a6cb
--- /dev/null
+++ b/packages/core/src/repowise/core/workspace/matching/data.py
@@ -0,0 +1,56 @@
+"""Data matching: a service that models another service's table shares it.
+
+The exact pass links a table's readers (SQL, query builders) to the services
+declaring it. A service that only *models* a table (an ORM class, no migration)
+while another service defines its schema reads that service's table all the
+same, and no consumer row says so. The pass here links them.
+"""
+
+from __future__ import annotations
+
+from collections import defaultdict
+from typing import TYPE_CHECKING
+
+from .common import internal
+
+if TYPE_CHECKING:
+ from repowise.core.workspace.contracts import Contract
+
+ from .common import MatchState
+
+# How strongly a declaration claims a table: creating its schema, evolving it,
+# or only modelling it.
+_SCHEMA_RANK = {"create": 0, "alter": 1}
+_MODEL_RANK = 2
+
+
+def _rank(c: Contract) -> tuple[int, str, int]:
+ return (_SCHEMA_RANK.get(c.meta.get("schema", ""), _MODEL_RANK), c.file_path, c.line or 0)
+
+
+def shared_table_pass(state: MatchState) -> None:
+ """Link each service that only models a table to the one defining its schema.
+
+ Only when exactly one service defines it (a migration or DDL creating or
+ altering it): two services that each migrate ``users`` are far more often
+ two apps with their own databases than one shared table, and two services
+ that only model a table say nothing about whose it is. Each modelling
+ service is linked once, from its first model to the owner's strongest
+ declaration.
+ """
+ for key, providers in state.provider_index.items():
+ if not key.startswith("data::"):
+ continue
+ by_service: dict[tuple[str, str | None], list[Contract]] = defaultdict(list)
+ for p in providers:
+ by_service[(p.repo, p.service)].append(p)
+ if len(by_service) < 2:
+ continue
+ best = [min(group, key=_rank) for group in by_service.values()]
+ owners = [c for c in best if _rank(c)[0] < _MODEL_RANK]
+ if len(owners) != 1:
+ continue
+ owner = owners[0]
+ for other in best:
+ if other is not owner and not internal(owner, other):
+ state.add(other, owner, "exact", min(owner.confidence, other.confidence))
diff --git a/tests/unit/dead_code/test_laravel_liveness.py b/tests/unit/dead_code/test_laravel_liveness.py
index 394df7042..5e9369002 100644
--- a/tests/unit/dead_code/test_laravel_liveness.py
+++ b/tests/unit/dead_code/test_laravel_liveness.py
@@ -108,3 +108,39 @@ def test_without_the_framework_the_same_files_are_flagged(tmp_path: Path) -> Non
assert dead in flagged, dead
# The base class is reached through its subclasses either way.
assert "app/Http/Controllers/Controller.php" not in flagged
+
+
+_REGISTERED = {
+ "app/Events/TicketSold.php": "<?php\nnamespace App\\Events;\nclass TicketSold {}\n",
+ "app/Http/Controllers/SaleController.php": (
+ "<?php\nnamespace App\\Http\\Controllers;\nuse App\\Events\\TicketSold;\n"
+ "class SaleController extends Controller {\n"
+ " public function store() { event(new TicketSold()); }\n}\n"
+ ),
+ "app/Listeners/SendReceipt.php": (
+ "<?php\nnamespace App\\Listeners;\nuse App\\Events\\TicketSold;\n"
+ "class SendReceipt { public function handle(TicketSold $event): void {} }\n"
+ ),
+ "app/Listeners/Orphan.php": (
+ "<?php\nnamespace App\\Listeners;\nclass Orphan { public function handle($event): void {} }\n"
+ ),
+ "app/Policies/TicketPolicy.php": "<?php\nnamespace App\\Policies;\nclass TicketPolicy {}\n",
+ "app/Policies/NoModelPolicy.php": "<?php\nnamespace App\\Policies;\nclass NoModelPolicy {}\n",
+}
+
+
+def test_discovered_listeners_and_policies_live_and_orphans_do_not(tmp_path: Path) -> None:
+ # Listeners and policies are linked from what registers or discovers them,
+ # not anchored by directory, so one nothing reaches still reads as unused.
+ _write_app(tmp_path, {"laravel/framework": "^11.0"})
+ for rel, text in _REGISTERED.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+ flagged = {path for _kind, path in _analyze(tmp_path)}
+
+ assert "app/Listeners/SendReceipt.php" not in flagged
+ assert "app/Policies/TicketPolicy.php" not in flagged
+ assert "app/Listeners/Orphan.php" in flagged
+ assert "app/Policies/NoModelPolicy.php" in flagged
diff --git a/tests/unit/ingestion/test_laravel_framework_edges.py b/tests/unit/ingestion/test_laravel_framework_edges.py
index 644d05ebf..27511b49c 100644
--- a/tests/unit/ingestion/test_laravel_framework_edges.py
+++ b/tests/unit/ingestion/test_laravel_framework_edges.py
@@ -233,3 +233,317 @@ class TestLaravelConventionFiles:
)
graph = self._graph(tmp_path)
assert graph.has_edge("api/routes/api.php", "api/app/Http/Controllers/PingController.php")
+
+
+def _laravel_app(repo: Path, files: dict[str, str]) -> nx.DiGraph:
+ """A Laravel app at *repo* with *files*; the framework edges it gets."""
+ (repo / "composer.json").write_text(
+ json.dumps(
+ {"require": {"laravel/framework": "^11"}, "autoload": {"psr-4": {"App\\": "app/"}}}
+ )
+ )
+ for rel, text in files.items():
+ (repo / rel).parent.mkdir(parents=True, exist_ok=True)
+ (repo / rel).write_text(text)
+ parsed = _build_parsed(repo)
+ graph = nx.DiGraph()
+ graph.add_nodes_from(parsed)
+ add_framework_edges(graph, parsed, _ctx(repo, parsed), tech_stack=[])
+ return graph
+
+
+def _class(fqn: str, body: str = "") -> str:
+ namespace, _, name = fqn.rpartition("\\")
+ return f"<?php\nnamespace {namespace};\nclass {name} {{ {body} }}\n"
+
+
+def _anchored(graph: nx.DiGraph) -> set[str]:
+ return set(graph.successors("framework:laravel")) if "framework:laravel" in graph else set()
+
+
+class TestLaravelRegistrations:
+ def test_listen_array_links_events_and_listeners(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Events/OrderPlaced.php": _class("App\\Events\\OrderPlaced"),
+ "app/Mail/SendReceipt.php": _class("App\\Mail\\SendReceipt"),
+ "app/Providers/EventServiceProvider.php": (
+ "<?php\nnamespace App\\Providers;\n"
+ "use App\\Events\\OrderPlaced;\nuse App\\Mail\\SendReceipt;\n"
+ "class EventServiceProvider {\n"
+ " protected $listen = [OrderPlaced::class => [SendReceipt::class]];\n}\n"
+ ),
+ },
+ )
+ provider = "app/Providers/EventServiceProvider.php"
+ assert graph.has_edge(provider, "app/Events/OrderPlaced.php")
+ assert graph.has_edge(provider, "app/Mail/SendReceipt.php")
+
+ def test_event_listen_and_gate_policy_calls(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Events/Refunded.php": _class("App\\Events\\Refunded"),
+ "app/Handlers/NotifyFinance.php": _class("App\\Handlers\\NotifyFinance"),
+ "app/Models/Ticket.php": _class("App\\Models\\Ticket"),
+ "app/Auth/TicketRules.php": _class("App\\Auth\\TicketRules"),
+ "app/Providers/AppServiceProvider.php": (
+ "<?php\nnamespace App\\Providers;\nclass AppServiceProvider {\n"
+ " public function boot() {\n"
+ " Event::listen(\\App\\Events\\Refunded::class, [\\App\\Handlers\\NotifyFinance::class, 'handle']);\n"
+ " Gate::policy(\\App\\Models\\Ticket::class, \\App\\Auth\\TicketRules::class);\n"
+ " }\n}\n"
+ ),
+ },
+ )
+ provider = "app/Providers/AppServiceProvider.php"
+ assert graph.has_edge(provider, "app/Handlers/NotifyFinance.php")
+ assert graph.has_edge(provider, "app/Auth/TicketRules.php")
+
+ def test_a_discovered_listener_is_linked_from_its_event(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Events/OrderPlaced.php": _class("App\\Events\\OrderPlaced"),
+ "app/Listeners/SendReceipt.php": (
+ "<?php\nnamespace App\\Listeners;\nuse App\\Events\\OrderPlaced;\n"
+ "class SendReceipt { public function handle(OrderPlaced $event): void {} }\n"
+ ),
+ },
+ )
+ assert graph.has_edge("app/Events/OrderPlaced.php", "app/Listeners/SendReceipt.php")
+ assert "app/Listeners/SendReceipt.php" not in _anchored(graph)
+
+ def test_a_listener_for_a_framework_event_is_anchored(self, tmp_path: Path) -> None:
+ # A local class that shares the vendor event's short name must not
+ # stand in for it.
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Models/Login.php": _class("App\\Models\\Login"),
+ "app/Listeners/AuditLogin.php": (
+ "<?php\nnamespace App\\Listeners;\nuse Illuminate\\Auth\\Events\\Login;\n"
+ "class AuditLogin { public function handle(Login $event): void {} }\n"
+ ),
+ },
+ )
+ assert "app/Listeners/AuditLogin.php" in _anchored(graph)
+ assert not graph.has_edge("app/Models/Login.php", "app/Listeners/AuditLogin.php")
+
+ def test_an_unregistered_listener_is_neither_linked_nor_anchored(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {"app/Listeners/Orphan.php": _class("App\\Listeners\\Orphan", "public function handle($e) {}")},
+ )
+ assert graph.in_degree("app/Listeners/Orphan.php") == 0
+
+ def test_a_policy_is_found_from_its_model(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Models/Guestlist.php": _class("App\\Models\\Guestlist"),
+ "app/Policies/GuestlistPolicy.php": _class("App\\Policies\\GuestlistPolicy"),
+ "app/Policies/OrphanPolicy.php": _class("App\\Policies\\OrphanPolicy"),
+ },
+ )
+ assert graph.has_edge("app/Models/Guestlist.php", "app/Policies/GuestlistPolicy.php")
+ assert graph.in_degree("app/Policies/OrphanPolicy.php") == 0
+
+ def test_bootstrap_providers_link_every_provider(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Billing/BillingServiceProvider.php": _class("App\\Billing\\BillingServiceProvider"),
+ "bootstrap/providers.php": (
+ "<?php\nreturn [\n App\\Billing\\BillingServiceProvider::class,\n];\n"
+ ),
+ },
+ )
+ assert graph.has_edge("bootstrap/providers.php", "app/Billing/BillingServiceProvider.php")
+
+ def test_a_scheduled_command_is_linked_by_signature(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Console/Commands/PruneOrders.php": _class(
+ "App\\Console\\Commands\\PruneOrders",
+ "protected $signature = 'orders:prune {--days=30}';",
+ ),
+ "bootstrap/app.php": (
+ "<?php\nreturn Application::configure()->withSchedule(function ($schedule) {\n"
+ " $schedule->command('orders:prune --days=7')->daily();\n})->create();\n"
+ ),
+ },
+ )
+ assert graph.has_edge("bootstrap/app.php", "app/Console/Commands/PruneOrders.php")
+
+ def test_a_middleware_alias_links_the_route_file(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Http/Middleware/IdempotencyKey.php": _class("App\\Http\\Middleware\\IdempotencyKey"),
+ "bootstrap/app.php": (
+ "<?php\nuse App\\Http\\Middleware\\IdempotencyKey;\n"
+ "return Application::configure()->withMiddleware(function ($middleware) {\n"
+ " $middleware->alias(['idempotent' => IdempotencyKey::class]);\n})->create();\n"
+ ),
+ "routes/api.php": (
+ "<?php\nRoute::middleware(['auth', 'idempotent:strict'])->post('/pay', fn () => 1);\n"
+ ),
+ },
+ )
+ assert graph.has_edge("routes/api.php", "app/Http/Middleware/IdempotencyKey.php")
+
+ def test_every_route_file_and_a_controller_group(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Http/Controllers/ReportController.php": _class(
+ "App\\Http\\Controllers\\ReportController"
+ ),
+ "routes/admin.php": (
+ "<?php\nuse App\\Http\\Controllers\\ReportController;\n"
+ "Route::controller(ReportController::class)->group(function () {\n"
+ " Route::get('/revenue', 'revenue');\n});\n"
+ ),
+ },
+ )
+ assert graph.has_edge("routes/admin.php", "app/Http/Controllers/ReportController.php")
+
+
+class TestLaravelRegistrationShapes:
+ def test_subscribers_commands_and_scheduled_jobs(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Subscribers/AuditSubscriber.php": _class("App\\Subscribers\\AuditSubscriber"),
+ "app/Ops/Prune.php": _class("App\\Ops\\Prune"),
+ "app/Jobs/Rollup.php": _class("App\\Jobs\\Rollup"),
+ "app/Providers/EventServiceProvider.php": (
+ "<?php\nnamespace App\\Providers;\nuse App\\Subscribers\\AuditSubscriber;\n"
+ "class EventServiceProvider { protected $subscribe = [AuditSubscriber::class]; }\n"
+ ),
+ "bootstrap/app.php": (
+ "<?php\nreturn Application::configure()\n"
+ " ->withCommands([App\\Ops\\Prune::class])\n"
+ " ->withSchedule(function ($schedule) {\n"
+ " $schedule->job(new App\\Jobs\\Rollup())->hourly();\n"
+ " })->create();\n"
+ ),
+ },
+ )
+ assert graph.has_edge(
+ "app/Providers/EventServiceProvider.php", "app/Subscribers/AuditSubscriber.php"
+ )
+ assert graph.has_edge("bootstrap/app.php", "app/Ops/Prune.php")
+ assert graph.has_edge("bootstrap/app.php", "app/Jobs/Rollup.php")
+
+ def test_config_app_providers(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Billing/BillingServiceProvider.php": _class(
+ "App\\Billing\\BillingServiceProvider"
+ ),
+ "config/app.php": (
+ "<?php\nreturn ['providers' => [\n"
+ " App\\Billing\\BillingServiceProvider::class,\n]];\n"
+ ),
+ },
+ )
+ assert graph.has_edge("config/app.php", "app/Billing/BillingServiceProvider.php")
+
+ def test_a_vendor_class_in_a_registration_binds_nothing_local(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Models/Login.php": _class("App\\Models\\Login"),
+ "app/Providers/EventServiceProvider.php": (
+ "<?php\nnamespace App\\Providers;\n"
+ "class EventServiceProvider {\n"
+ " protected $listen = [\\Illuminate\\Auth\\Events\\Login::class => []];\n}\n"
+ ),
+ },
+ )
+ assert not graph.has_edge("app/Providers/EventServiceProvider.php", "app/Models/Login.php")
+
+ def test_commands_called_by_signature(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Ops/Prune.php": _class(
+ "App\\Ops\\Prune", "protected $signature = 'orders:prune';"
+ ),
+ "app/Ops/Reindex.php": (
+ "<?php\nnamespace App\\Ops;\n#[AsCommand(name: 'search:reindex')]\nclass Reindex {}\n"
+ ),
+ "routes/console.php": "<?php\nSchedule::command('orders:prune')->daily();\n",
+ "app/Http/Controllers/AdminController.php": (
+ "<?php\nnamespace App\\Http\\Controllers;\n"
+ "class AdminController { public function go() { Artisan::call('search:reindex'); } }\n"
+ ),
+ },
+ )
+ assert graph.has_edge("routes/console.php", "app/Ops/Prune.php")
+ assert graph.has_edge("app/Http/Controllers/AdminController.php", "app/Ops/Reindex.php")
+
+ def test_a_kernel_alias_used_by_a_controller(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Http/Middleware/Guard.php": _class("App\\Http\\Middleware\\Guard"),
+ "app/Http/Kernel.php": (
+ "<?php\nnamespace App\\Http;\nuse App\\Http\\Middleware\\Guard;\n"
+ "class Kernel { protected $routeMiddleware = ['guard' => Guard::class]; }\n"
+ ),
+ "app/Http/Controllers/AccountController.php": (
+ "<?php\nnamespace App\\Http\\Controllers;\n"
+ "class AccountController { public function __construct() { $this->middleware('guard'); } }\n"
+ ),
+ },
+ )
+ assert graph.has_edge(
+ "app/Http/Controllers/AccountController.php", "app/Http/Middleware/Guard.php"
+ )
+
+ def test_a_union_typed_listener_is_linked_from_each_event(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Events/Paid.php": _class("App\\Events\\Paid"),
+ "app/Events/Refunded.php": _class("App\\Events\\Refunded"),
+ "app/Listeners/Ledger.php": (
+ "<?php\nnamespace App\\Listeners;\nuse App\\Events\\Paid;\nuse App\\Events\\Refunded;\n"
+ "class Ledger { public function handle(Paid|Refunded $event): void {} }\n"
+ ),
+ },
+ )
+ assert graph.has_edge("app/Events/Paid.php", "app/Listeners/Ledger.php")
+ assert graph.has_edge("app/Events/Refunded.php", "app/Listeners/Ledger.php")
+
+ def test_a_policy_in_a_subfolder_keeps_the_model_sub_namespace(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Models/User.php": _class("App\\Models\\User"),
+ "app/Models/Admin/User.php": _class("App\\Models\\Admin\\User"),
+ "app/Policies/Admin/UserPolicy.php": _class("App\\Policies\\Admin\\UserPolicy"),
+ },
+ )
+ assert graph.has_edge("app/Models/Admin/User.php", "app/Policies/Admin/UserPolicy.php")
+ assert not graph.has_edge("app/Models/User.php", "app/Policies/Admin/UserPolicy.php")
+
+ def test_a_legacy_string_handler_in_the_default_namespace(self, tmp_path: Path) -> None:
+ graph = _laravel_app(
+ tmp_path,
+ {
+ "app/Http/Controllers/Admin/DashboardController.php": _class(
+ "App\\Http\\Controllers\\Admin\\DashboardController"
+ ),
+ "routes/web.php": "<?php\nRoute::get('/d', 'Admin\\DashboardController@index');\n",
+ },
+ )
+ assert graph.has_edge(
+ "routes/web.php", "app/Http/Controllers/Admin/DashboardController.php"
+ )
diff --git a/tests/unit/test_no_bare_type_name_copies.py b/tests/unit/test_no_bare_type_name_copies.py
index bc4a81fa5..02608af51 100644
--- a/tests/unit/test_no_bare_type_name_copies.py
+++ b/tests/unit/test_no_bare_type_name_copies.py
@@ -87,6 +87,10 @@ _KNOWN: dict[str, int] = {
_PREFIX + "dynamic_hints/swift.py": 1,
# Splits an import statement's package path, not a type reference.
_PREFIX + "languages/jvm_same_package.py": 1,
+ # Qualifies a PHP name against its `use` alias (the HEAD segment) and
+ # splits an FQN into the namespace it indexes by and the class: it asks
+ # which namespace, the opposite end from the shared helper.
+ _PREFIX + "languages/php_same_namespace.py": 2,
# Takes the head of a URLconf's `views.detail` to reach the Python module
# declaring the view. The trailing segment is the view function and the
# head is a module path, so neither end is a type.
@@ -110,7 +114,6 @@ _KNOWN: dict[str, int] = {
_PREFIX + "framework_edges/jakarta.py": 2,
_PREFIX + "framework_edges/micronaut.py": 2,
_PREFIX + "framework_edges/spring.py": 4,
- _PREFIX + "framework_edges/laravel.py": 1,
_PREFIX + "parser_helpers.py": 1,
_PREFIX + "languages/go_interface_satisfaction.py": 1,
}
diff --git a/tests/unit/workspace/test_data_contracts.py b/tests/unit/workspace/test_data_contracts.py
index 7cdf0a82a..87d115a0e 100644
--- a/tests/unit/workspace/test_data_contracts.py
+++ b/tests/unit/workspace/test_data_contracts.py
@@ -128,7 +128,9 @@ class TestOrmProviders:
'def upgrade():\n op.create_table("orders", sa.Column("id", sa.Integer))\n',
)
contracts = DataExtractor().extract(tmp_path, "api")
- assert any(c.contract_id == "data::orders" for c in contracts)
+ (orders,) = [c for c in contracts if c.contract_id == "data::orders"]
+ # A migration defines the schema, which marks the owning repo.
+ assert orders.meta["schema"] == "create"
def test_sqlmodel_table_true(self, tmp_path: Path) -> None:
_write(
@@ -330,3 +332,190 @@ class TestDataMatching:
contracts = DataExtractor().extract(backend, "backend")
contracts += DataExtractor().extract(worker, "worker")
assert len(match_contracts(contracts)) == 1
+
+
+_ELOQUENT_HEAD = "<?php\nnamespace App\\Models;\nuse Illuminate\\Database\\Eloquent\\Model;\n"
+
+
+def _data(repo: Path, alias: str = "app") -> dict[tuple[str, str], dict]:
+ """``(contract_id, framework or client) -> meta`` for *repo*'s data contracts."""
+ return {
+ (c.contract_id, c.meta.get("framework") or c.meta["client"]): c.meta
+ for c in DataExtractor().extract(repo, alias)
+ }
+
+
+class TestLaravelData:
+ def test_model_table_follows_the_naming_convention(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/Models/GuestlistEntry.php", _ELOQUENT_HEAD + "class GuestlistEntry extends Model {}\n")
+ _write(
+ tmp_path,
+ "app/Models/User.php",
+ "<?php\nuse Illuminate\\Foundation\\Auth\\User as Authenticatable;\n"
+ "class User extends Authenticatable {}\n",
+ )
+ assert set(_data(tmp_path)) == {
+ ("data::guestlist_entries", "eloquent"),
+ ("data::users", "eloquent"),
+ }
+
+ def test_an_explicit_table_wins_over_the_convention(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "app/Models/Table.php",
+ _ELOQUENT_HEAD + "class Table extends Model {\n protected $table = 'venue_tables';\n}\n",
+ )
+ assert set(_data(tmp_path)) == {("data::venue_tables", "eloquent")}
+
+ def test_the_convention_needs_eloquent_and_a_concrete_class(self, tmp_path: Path) -> None:
+ # Another library's `Model`, and an abstract base, name no table.
+ _write(tmp_path, "src/Widget.php", "<?php\nuse Acme\\Model;\nclass Widget extends Model {}\n")
+ _write(tmp_path, "app/Models/Base.php", _ELOQUENT_HEAD + "abstract class Base extends Model {}\n")
+ assert _data(tmp_path) == {}
+
+ def test_migrations_create_and_alter_with_schema_meta(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "database/migrations/2024_01_01_000000_create_orders_table.php",
+ "<?php\nreturn new class extends Migration {\n"
+ " public function up(): void {\n"
+ " Schema::create('orders', function (Blueprint $t) { $t->id(); });\n"
+ " Schema::connection('audit')->table('order_log', function (Blueprint $t) {});\n"
+ " }\n"
+ " public function down(): void { Schema::dropIfExists('orders'); }\n"
+ "};\n",
+ )
+ found = _data(tmp_path)
+ assert found[("data::orders", "laravel-migration")]["schema"] == "create"
+ assert found[("data::order_log", "laravel-migration")]["schema"] == "alter"
+ assert len(found) == 2
+
+ def test_query_builder_reads_and_writes(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "app/Services/Stats.php",
+ "<?php\nclass Stats {\n public function run() {\n"
+ " DB::table('tickets')->where('event_id', 1)->count();\n"
+ " DB::table('event_scan_stats')->updateOrInsert(['id' => 1], ['n' => 2]);\n"
+ " DB::table('audit as a')->insert(['x' => 1]);\n"
+ " DB::table('sessions')->where('old', true)->delete();\n"
+ " DB::table('counters')->increment('hits');\n"
+ " }\n}\n",
+ )
+ verbs = {cid: meta["verb"] for (cid, _), meta in _data(tmp_path).items()}
+ assert verbs == {
+ "data::tickets": "select",
+ "data::event_scan_stats": "update",
+ "data::audit": "insert",
+ "data::sessions": "delete",
+ "data::counters": "update",
+ }
+
+ def test_less_common_spellings(self, tmp_path: Path) -> None:
+ _write(tmp_path, "app/Models/Seat.php", _ELOQUENT_HEAD + "final class Seat extends Model {}\n")
+ _write(
+ tmp_path,
+ "app/Jobs/Sync.php",
+ "<?php\nclass Sync { public function run() {\n"
+ " DB::connection('reporting')->table('rollups')->upsert([], ['id']);\n"
+ " DB::table('scratch')->truncate();\n"
+ " Schema::connection('audit')->create('audit_log', function ($t) {});\n"
+ "} }\n",
+ )
+ found = _data(tmp_path)
+ assert ("data::seats", "eloquent") in found
+ assert found[("data::rollups", "laravel-db")]["verb"] == "insert"
+ assert found[("data::scratch", "laravel-db")]["verb"] == "delete"
+ assert found[("data::audit_log", "laravel-migration")]["schema"] == "create"
+
+ def test_a_semicolon_in_a_string_does_not_end_the_statement(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "app/Jobs/Purge.php",
+ "<?php\nDB::table('tokens')->where('note', 'a;b')->delete();\n",
+ )
+ assert _data(tmp_path)[("data::tokens", "laravel-db")]["verb"] == "delete"
+
+ def test_a_write_inside_a_callback_is_not_the_outer_statement(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "app/Jobs/Backfill.php",
+ "<?php\nDB::table('orders')->orderBy('id')->each(function ($o) {\n"
+ " DB::table('ledger')->insert(['order' => $o->id]);\n});\n",
+ )
+ verbs = {cid: meta["verb"] for (cid, _), meta in _data(tmp_path).items()}
+ assert verbs == {"data::orders": "select", "data::ledger": "insert"}
+
+ def test_an_aliased_eloquent_base_is_missed_not_guessed(self, tmp_path: Path) -> None:
+ # Deliberate ceiling: only the framework's own base-class names count.
+ _write(
+ tmp_path,
+ "app/Models/Seat.php",
+ "<?php\nuse Illuminate\\Database\\Eloquent\\Model as Eloquent;\nclass Seat extends Eloquent {}\n",
+ )
+ assert _data(tmp_path) == {}
+
+ def test_a_ddl_create_carries_schema_meta(self, tmp_path: Path) -> None:
+ _write(tmp_path, "schema.sql", "CREATE TABLE a (id INT);\nALTER TABLE b ADD COLUMN x INT;")
+ found = _data(tmp_path)
+ assert found[("data::a", "sql-ddl")]["schema"] == "create"
+ assert found[("data::b", "sql-ddl")]["schema"] == "alter"
+
+
+class TestSharedTables:
+ def _extract(self, root: Path, *aliases: str) -> list:
+ return [c for a in aliases for c in DataExtractor().extract(root / a, a)]
+
+ def test_a_model_is_linked_to_the_service_owning_the_migration(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path / "api",
+ "database/migrations/2024_create_events.php",
+ "<?php\nSchema::create('events', function ($t) {});\n",
+ )
+ _write(tmp_path / "api", "app/Models/Event.php", _ELOQUENT_HEAD + "class Event extends Model {}\n")
+ _write(tmp_path / "admin", "app/Models/Event.php", _ELOQUENT_HEAD + "class Event extends Model {}\n")
+ links = match_contracts(self._extract(tmp_path, "admin", "api"))
+ assert [(k.consumer_repo, k.consumer_file, k.provider_repo, k.provider_file) for k in links] == [
+ ("admin", "app/Models/Event.php", "api", "database/migrations/2024_create_events.php")
+ ]
+ assert links[0].contract_type == "data"
+
+ def test_models_alone_say_nothing(self, tmp_path: Path) -> None:
+ # Nobody defines the schema, so nothing says whose table it is.
+ for alias in ("a", "b"):
+ _write(tmp_path / alias, "app/Models/Venue.php", _ELOQUENT_HEAD + "class Venue extends Model {}\n")
+ assert match_contracts(self._extract(tmp_path, "a", "b")) == []
+
+ def test_two_apps_migrating_one_table_name_are_not_linked(self, tmp_path: Path) -> None:
+ # Every stock Laravel app creates `users`; two of them are two databases.
+ for alias in ("shop", "blog"):
+ _write(
+ tmp_path / alias,
+ "database/migrations/0001_create_users_table.php",
+ "<?php\nSchema::create('users', function ($t) {});\n",
+ )
+ _write(tmp_path / alias, "app/Models/User.php", _ELOQUENT_HEAD + "class User extends Model {}\n")
+ assert match_contracts(self._extract(tmp_path, "shop", "blog")) == []
+
+ def test_an_alter_only_owner_still_owns(self, tmp_path: Path) -> None:
+ _write(tmp_path / "api", "db/002.sql", "ALTER TABLE seats ADD COLUMN row INT;")
+ _write(tmp_path / "admin", "app/Models/Seat.php", _ELOQUENT_HEAD + "class Seat extends Model {}\n")
+ links = match_contracts(self._extract(tmp_path, "admin", "api"))
+ assert [(k.consumer_repo, k.provider_repo) for k in links] == [("admin", "api")]
+
+ def test_one_service_declaring_twice_shares_nothing(self, tmp_path: Path) -> None:
+ _write(tmp_path / "api", "db/schema.sql", "CREATE TABLE zones (id INT);")
+ _write(tmp_path / "api", "app/Models/Zone.php", _ELOQUENT_HEAD + "class Zone extends Model {}\n")
+ assert match_contracts(self._extract(tmp_path, "api")) == []
+
+ def test_readers_and_models_both_link(self, tmp_path: Path) -> None:
+ # The shared-table pass adds to the exact pass; it does not replace it.
+ _write(tmp_path / "api", "db/schema.sql", "CREATE TABLE refunds (id INT);")
+ _write(tmp_path / "admin", "app/Models/Refund.php", _ELOQUENT_HEAD + "class Refund extends Model {}\n")
+ _write(tmp_path / "worker", "job.py", 'q = "SELECT id FROM refunds WHERE x = 1"\n')
+ links = match_contracts(self._extract(tmp_path, "api", "admin", "worker"))
+ assert sorted((k.consumer_repo, k.provider_repo) for k in links) == [
+ ("admin", "api"),
+ ("worker", "admin"),
+ ("worker", "api"),
+ ]
diff --git a/tests/unit/workspace/test_framework_routes.py b/tests/unit/workspace/test_framework_routes.py
index 2afabff0d..237b50a31 100644
--- a/tests/unit/workspace/test_framework_routes.py
+++ b/tests/unit/workspace/test_framework_routes.py
@@ -433,11 +433,14 @@ class TestGoRecognition:
class TestLaravelRecognition:
def test_all_three_handler_spellings(self) -> None:
- routes = [(r.verb, r.path, r.handler) for r in laravel_routes(ROUTES_PHP)]
+ routes = [
+ (r.verb, r.path, r.handler)
+ for r in laravel_routes(ROUTES_PHP)
+ if "photos" not in (r.path or "")
+ ]
assert routes == [
("GET", "/orders/{id}", "OrderController"),
("POST", "/orders", "OrderController"),
- ("RESOURCE", "photos", "PhotoController"),
("GET", "/ping", None),
]
@@ -474,10 +477,22 @@ class TestLaravelRecognition:
(route,) = list(laravel_routes("Route::put($uri, [EditController::class, 'e']);"))
assert (route.path, route.handler) == (None, "EditController")
- def test_resource_reaches_the_graph_consumer_with_its_controller(self) -> None:
- # It stands for a set of routes, so only the graph consumer can use it.
- (resource,) = [r for r in laravel_routes(ROUTES_PHP) if r.verb == "RESOURCE"]
- assert resource.handler == "PhotoController"
+ def test_a_resource_expands_to_its_routes_with_its_controller(self) -> None:
+ photos = [
+ (r.verb, r.path, r.handler)
+ for r in laravel_routes(ROUTES_PHP)
+ if "photos" in (r.path or "")
+ ]
+ assert photos == [
+ ("GET", "/photos", "PhotoController"),
+ ("GET", "/photos/create", "PhotoController"),
+ ("POST", "/photos", "PhotoController"),
+ ("GET", "/photos/{photo}", "PhotoController"),
+ ("GET", "/photos/{photo}/edit", "PhotoController"),
+ ("PUT", "/photos/{photo}", "PhotoController"),
+ ("PATCH", "/photos/{photo}", "PhotoController"),
+ ("DELETE", "/photos/{photo}", "PhotoController"),
+ ]
class TestAxumRecognition:
@@ -572,14 +587,24 @@ class TestLaravelConsumers:
# that the one shared alternation now covers.
assert graph.has_edge("routes/api.php", "app/Http/Controllers/PhotoController.php")
- def test_contracts_cover_the_verbs_and_nothing_else(self, tmp_path: Path) -> None:
+ def test_contracts_are_served_under_api_with_resources_expanded(
+ self, tmp_path: Path
+ ) -> None:
+ # routes/api.php is served under /api when nothing declares otherwise.
self._write(tmp_path)
- ids = set(_providers(tmp_path))
- assert "http::GET::/orders/{param}" in ids
- assert "http::POST::/orders" in ids
- assert "http::GET::/ping" in ids
- # `resource` stands for a set of routes, so it is not one contract.
- assert not [i for i in ids if "photos" in i]
+ assert set(_providers(tmp_path)) == {
+ "http::GET::/api/orders/{param}",
+ "http::POST::/api/orders",
+ "http::GET::/api/ping",
+ "http::GET::/api/photos",
+ "http::GET::/api/photos/create",
+ "http::POST::/api/photos",
+ "http::GET::/api/photos/{param}",
+ "http::GET::/api/photos/{param}/edit",
+ "http::PUT::/api/photos/{param}",
+ "http::PATCH::/api/photos/{param}",
+ "http::DELETE::/api/photos/{param}",
+ }
class TestAxumConsumers:
diff --git a/tests/unit/workspace/test_laravel_routes.py b/tests/unit/workspace/test_laravel_routes.py
new file mode 100644
index 000000000..9593fd00d
--- /dev/null
+++ b/tests/unit/workspace/test_laravel_routes.py
@@ -0,0 +1,327 @@
+"""Laravel route groups, resources and route-file prefixes.
+
+The recogniser in ``ingestion.framework_routes`` serves both the graph and the
+contract layer, so the paths here are what a consumer's URL must match: every
+enclosing group prefix, the prefix the route file itself is served under, and
+the routes a resource registration stands for.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.framework_routes import (
+ laravel_route_file_prefixes,
+ laravel_route_prefix,
+ laravel_routes,
+)
+from repowise.core.workspace.extractors.http import HttpExtractor
+
+
+def _routes(php: str, prefix: str = "") -> list[tuple[str, str | None, str | None]]:
+ return [(r.verb, r.path, r.handler) for r in laravel_routes(php, prefix)]
+
+
+def _providers(repo: Path) -> set[str]:
+ return {c.contract_id for c in HttpExtractor().extract(repo, "api") if c.role == "provider"}
+
+
+def _write(repo: Path, rel: str, text: str) -> None:
+ path = repo / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text, encoding="utf-8")
+
+
+class TestGroups:
+ def test_prefix_groups_nest(self) -> None:
+ php = """<?php
+Route::prefix('v1')->middleware('auth')->group(function () {
+ Route::get('/me', [MeController::class, 'show']);
+ Route::prefix('admin')->group(function () {
+ Route::delete('users/{id}', [UserController::class, 'destroy']);
+ });
+});
+Route::get('/health', [HealthController::class, 'show']);
+"""
+ assert _routes(php) == [
+ ("GET", "/v1/me", "MeController"),
+ ("DELETE", "/v1/admin/users/{id}", "UserController"),
+ ("GET", "/health", "HealthController"),
+ ]
+
+ def test_the_array_form_declares_a_prefix(self) -> None:
+ php = """<?php
+Route::group(['middleware' => ['web'], 'prefix' => 'radio'], static function (): void {
+ Route::get('stations', [StationController::class, 'index']);
+});
+"""
+ assert _routes(php) == [("GET", "/radio/stations", "StationController")]
+
+ def test_a_bare_method_takes_the_controller_of_its_group(self) -> None:
+ php = """<?php
+Route::controller(OrderController::class)->prefix('orders')->group(function () {
+ Route::get('/{id}', 'show');
+ Route::post('/', 'store');
+ Route::get('/export', [ExportController::class, 'csv']);
+});
+"""
+ assert _routes(php) == [
+ ("GET", "/orders/{id}", "OrderController"),
+ ("POST", "/orders", "OrderController"),
+ ("GET", "/orders/export", "ExportController"),
+ ]
+
+ def test_an_empty_path_is_the_group_root(self) -> None:
+ php = "<?php\nRoute::prefix('users')->group(function () { Route::get('', [U::class, 'i']); });"
+ assert _routes(php) == [("GET", "/users", "U")]
+
+ def test_a_middleware_chain_can_end_in_a_verb(self) -> None:
+ php = "<?php\nRoute::middleware('auth:sanctum')->prefix('v2')->get('/user', [U::class, 'me']);"
+ assert _routes(php) == [("GET", "/v2/user", "U")]
+
+ def test_a_comment_between_links_keeps_the_chain(self) -> None:
+ php = """<?php
+Route::prefix('api')
+ ->middleware('api')
+ // a flat list of routes
+ ->group(static function (): void {
+ Route::get('ping', static fn () => null);
+ });
+"""
+ assert _routes(php) == [("GET", "/api/ping", None)]
+
+ def test_an_unreadable_prefix_refuses_the_path_but_keeps_the_handler(self) -> None:
+ # Serving the route at the outer prefix would be a guess; the graph
+ # still wants the controller.
+ php = """<?php
+Route::prefix(config('app.admin'))->group(function () {
+ Route::get('/stats', [StatsController::class, 'show']);
+});
+"""
+ assert _routes(php) == [("GET", None, "StatsController")]
+
+ def test_a_route_registry_call_is_not_a_route(self) -> None:
+ assert _routes("<?php\n$routes = Route::getRoutes()->get('GET');") == []
+
+ def test_match_lists_its_verbs(self) -> None:
+ php = "<?php\nRoute::match(['get', 'post'], '/search', [SearchController::class, 'run']);"
+ assert _routes(php) == [
+ ("GET", "/search", "SearchController"),
+ ("POST", "/search", "SearchController"),
+ ]
+
+ def test_the_array_form_declares_a_controller(self) -> None:
+ php = (
+ "<?php\nRoute::group(['controller' => C::class, 'prefix' => 'c'], function () {\n"
+ " Route::get('/x', 'show');\n});"
+ )
+ assert _routes(php) == [("GET", "/c/x", "C")]
+
+ def test_an_interpolated_prefix_is_unreadable(self) -> None:
+ php = "<?php\nRoute::prefix(\"v$ver\")->group(function () { Route::get('/u', [U::class, 'i']); });"
+ assert _routes(php) == [("GET", None, "U")]
+
+ def test_any_and_options_are_read_but_are_not_contracts(self, tmp_path: Path) -> None:
+ php = "<?php\nRoute::any('/hook', [H::class, 'i']);\nRoute::options('/pre', [P::class, 'i']);"
+ assert [v for v, _, _ in _routes(php)] == ["ANY", "OPTIONS"]
+ _write(tmp_path, "routes/web.php", php)
+ assert _providers(tmp_path) == set()
+
+ def test_the_file_prefix_goes_first(self) -> None:
+ php = "<?php\nRoute::prefix('orders')->group(function () { Route::get('/', [O::class, 'i']); });"
+ assert _routes(php, "api") == [("GET", "/api/orders", "O")]
+
+ def test_no_prefix_keeps_the_literal_as_written(self) -> None:
+ assert _routes("<?php\nRoute::get('users', [U::class, 'i']);") == [("GET", "users", "U")]
+
+
+class TestResources:
+ def test_api_resource_drops_the_form_routes(self) -> None:
+ verbs = [(v, p) for v, p, _ in _routes("<?php\nRoute::apiResource('tickets', T::class);")]
+ assert verbs == [
+ ("GET", "/tickets"),
+ ("POST", "/tickets"),
+ ("GET", "/tickets/{ticket}"),
+ ("PUT", "/tickets/{ticket}"),
+ ("PATCH", "/tickets/{ticket}"),
+ ("DELETE", "/tickets/{ticket}"),
+ ]
+
+ def test_only_and_except_filter_the_actions(self) -> None:
+ only = _routes("<?php\nRoute::apiResource('users', U::class)->only(['index', 'show']);")
+ assert [(v, p) for v, p, _ in only] == [("GET", "/users"), ("GET", "/users/{user}")]
+ except_ = _routes(
+ "<?php\nRoute::resource('photos', P::class)->except(['create', 'edit', 'destroy']);"
+ )
+ assert [(v, p) for v, p, _ in except_] == [
+ ("GET", "/photos"),
+ ("POST", "/photos"),
+ ("GET", "/photos/{photo}"),
+ ("PUT", "/photos/{photo}"),
+ ("PATCH", "/photos/{photo}"),
+ ]
+ single = _routes("<?php\nRoute::apiResource('venues', V::class)->only('index');")
+ assert [(v, p) for v, p, _ in single] == [("GET", "/venues")]
+
+ def test_the_options_array_filters_too(self) -> None:
+ routes = _routes("<?php\nRoute::resource('tags', T::class, ['only' => ['index']]);")
+ assert routes == [("GET", "/tags", "T")]
+
+ def test_nested_and_shallow(self) -> None:
+ nested = _routes("<?php\nRoute::apiResource('posts.comments', C::class)->only(['index', 'show']);")
+ assert [p for _, p, _ in nested] == ["/posts/{post}/comments", "/posts/{post}/comments/{comment}"]
+ shallow = _routes(
+ "<?php\nRoute::apiResource('posts.comments', C::class)->only(['index', 'show'])->shallow();"
+ )
+ assert [p for _, p, _ in shallow] == ["/posts/{post}/comments", "/comments/{comment}"]
+
+ def test_resources_registers_each_pair(self) -> None:
+ php = "<?php\nRoute::apiResources(['albums' => AlbumController::class, 'songs' => SongController::class]);"
+ handlers = {(p, h) for v, p, h in _routes(php) if v == "GET"}
+ assert ("/albums", "AlbumController") in handlers
+ assert ("/songs/{song}", "SongController") in handlers
+
+ def test_a_resource_inside_a_group_carries_the_prefix(self) -> None:
+ php = "<?php\nRoute::prefix('v1')->group(function () { Route::apiResource('orders', O::class)->only('index'); });"
+ assert _routes(php) == [("GET", "/v1/orders", "O")]
+
+ def test_a_computed_resource_name_still_names_its_controller(self) -> None:
+ assert _routes("<?php\nRoute::resource($name, PhotoController::class);") == [
+ ("RESOURCE", None, "PhotoController")
+ ]
+
+
+class TestRouteFilePrefixes:
+ def test_with_routing_serves_api_under_its_prefix(self) -> None:
+ bootstrap = """<?php
+return Application::configure(basePath: dirname(__DIR__))
+ ->withRouting(
+ web: __DIR__.'/../routes/web.php',
+ api: __DIR__.'/../routes/api.php',
+ apiPrefix: 'api/v2',
+ health: '/up',
+ )->create();
+"""
+ assert laravel_route_file_prefixes(bootstrap) == {"web.php": "", "api.php": "api/v2"}
+
+ def test_with_routing_defaults_to_api(self) -> None:
+ bootstrap = "<?php\nApplication::configure()->withRouting(api: __DIR__.'/../routes/api.php');"
+ assert laravel_route_file_prefixes(bootstrap) == {"api.php": "api"}
+
+ def test_an_unreadable_api_prefix_is_none(self) -> None:
+ bootstrap = (
+ "<?php\nApplication::configure()->withRouting("
+ "api: __DIR__.'/../routes/api.php', apiPrefix: env('API_PREFIX'));"
+ )
+ assert laravel_route_file_prefixes(bootstrap) == {"api.php": None}
+
+ def test_a_provider_group_names_the_file_it_loads(self) -> None:
+ provider = """<?php
+class RouteServiceProvider {
+ public function boot() {
+ Route::prefix('api')->middleware('api')->group(base_path('routes/api.php'));
+ Route::middleware('web')->group(base_path('routes/web.php'));
+ Route::group(['prefix' => 'admin'], function ($router) {
+ require base_path('routes/admin.php');
+ });
+ }
+}
+"""
+ assert laravel_route_file_prefixes(provider) == {
+ "api.php": "api",
+ "web.php": "",
+ "admin.php": "admin",
+ }
+
+ def test_a_route_file_loaded_from_with_routing_then(self) -> None:
+ bootstrap = """<?php
+Application::configure()->withRouting(
+ web: __DIR__.'/../routes/web.php',
+ then: function () {
+ Route::middleware('api')->prefix('webhooks')->group(base_path('routes/webhooks.php'));
+ },
+);
+"""
+ assert laravel_route_file_prefixes(bootstrap) == {"web.php": "", "webhooks.php": "webhooks"}
+
+ def test_a_top_level_require_names_nothing(self) -> None:
+ # Outside a group the loaded file inherits the loader's own prefix,
+ # which this file cannot know.
+ assert laravel_route_file_prefixes("<?php\nRoute::get('/', [H::class, 'i']);\nrequire __DIR__.'/auth.php';") == {}
+
+ def test_route_prefix_defaults(self) -> None:
+ assert laravel_route_prefix("routes/api.php", {}) == "api"
+ assert laravel_route_prefix("routes/web.php", {}) == ""
+ assert laravel_route_prefix("apps/shop/routes/api.php", {}) == "api"
+ assert laravel_route_prefix("routes/api.php", {"api.php": "v1"}) == "v1"
+ assert laravel_route_prefix("routes/api.php", {"api.php": None}) is None
+ # Only files in a routes directory are route files, at any depth and
+ # in either case; the default applies to `routes/api.php` alone.
+ assert laravel_route_prefix("app/Http/api.php", {"api.php": "v1"}) == ""
+ assert laravel_route_prefix("routes/api/v1.php", {"v1.php": "api/v1"}) == "api/v1"
+ assert laravel_route_prefix("routes/api/v1.php", {}) == ""
+ assert laravel_route_prefix("Modules/Blog/Routes/api.php", {}) == "api"
+
+
+class TestContracts:
+ def test_api_routes_default_to_the_api_prefix(self, tmp_path: Path) -> None:
+ _write(tmp_path, "routes/api.php", "<?php\nRoute::get('/orders', [O::class, 'i']);")
+ _write(tmp_path, "routes/web.php", "<?php\nRoute::get('/home', [H::class, 'i']);")
+ assert _providers(tmp_path) == {"http::GET::/api/orders", "http::GET::/home"}
+
+ def test_bootstrap_declares_the_api_prefix(self, tmp_path: Path) -> None:
+ _write(tmp_path, "routes/api.php", "<?php\nRoute::get('/orders', [O::class, 'i']);")
+ _write(
+ tmp_path,
+ "bootstrap/app.php",
+ "<?php\nApplication::configure()->withRouting(api: __DIR__.'/../routes/api.php', apiPrefix: 'v1');",
+ )
+ assert _providers(tmp_path) == {"http::GET::/v1/orders"}
+
+ def test_an_unreadable_file_prefix_refuses_the_file(self, tmp_path: Path) -> None:
+ _write(tmp_path, "routes/api.php", "<?php\nRoute::get('/orders', [O::class, 'i']);")
+ _write(
+ tmp_path,
+ "bootstrap/app.php",
+ "<?php\nApplication::configure()->withRouting(api: __DIR__.'/../routes/api.php', apiPrefix: env('P'));",
+ )
+ assert _providers(tmp_path) == set()
+
+ def test_disagreeing_declarations_refuse_the_file(self, tmp_path: Path) -> None:
+ # Two declarations of one file name the merge cannot settle: serving
+ # the file at the default would be a guess.
+ _write(tmp_path, "routes/api.php", "<?php\nRoute::get('/orders', [O::class, 'i']);")
+ _write(
+ tmp_path,
+ "bootstrap/app.php",
+ "<?php\nApplication::configure()"
+ "->withRouting(api: __DIR__.'/../routes/api.php', apiPrefix: 'v1');",
+ )
+ _write(
+ tmp_path,
+ "app/Providers/RouteServiceProvider.php",
+ "<?php\nRoute::prefix('api')->group(base_path('routes/api.php'));",
+ )
+ assert _providers(tmp_path) == set()
+
+ def test_a_nested_route_file_takes_its_declared_prefix(self, tmp_path: Path) -> None:
+ _write(tmp_path, "routes/api/v1.php", "<?php\nRoute::get('/users', [U::class, 'i']);")
+ _write(
+ tmp_path,
+ "app/Providers/RouteServiceProvider.php",
+ "<?php\nRoute::prefix('api/v1')->group(base_path('routes/api/v1.php'));",
+ )
+ assert _providers(tmp_path) == {"http::GET::/api/v1/users"}
+
+ def test_a_group_and_resource_reach_the_contract(self, tmp_path: Path) -> None:
+ _write(
+ tmp_path,
+ "routes/api.php",
+ "<?php\nRoute::prefix('events/{event}')->group(function () {\n"
+ " Route::apiResource('tickets', TicketController::class)->only(['index', 'store']);\n"
+ "});\n",
+ )
+ assert _providers(tmp_path) == {
+ "http::GET::/api/events/{param}/tickets",
+ "http::POST::/api/events/{param}/tickets",
+ }