feat(resolution): bridge Laravel event(new X) to its listener handles

Laravel decouples an event dispatch from its listener(s), linked by the event
class: event(new OrderShipped($order)) has no static edge to the
handle(OrderShipped $event) that runs it (usually a separate app/Listeners/
class). laravelEventEdges bridges each event(new X(...)) site -> every
listener's handle for X.

Two registration mechanisms, both real and both needed (built together):
- (A) auto-discovery: a typed handle(EventType $e) first param, read from the
  method declaration source (PHP method nodes carry no signature, like C#); a
  handle(A|B $e) union is split into two events.
- (B) the `protected $listen = [XEvent::class => [Listener::class, ...]]` map in
  an EventServiceProvider, parsed from comment-stripped source (so a
  fully-commented map on an auto-discovery app contributes nothing). This is the
  only way to link a listener whose handle() is untyped.

Job exclusion is free: queued jobs dispatch via ::dispatch()/dispatch() (not
matched) and their handle() takes an injected service, never an event type, so
matching only event(new X) excludes them by construction. `use Dispatchable` is
not keyed on (unreliable in real apps).

Surfaces as `dynamic: laravel event` via the generic synth-edge fallback.

Validated 100% precision on two grep-confirmed repos exercising both
mechanisms: koel (small, populated $listen map, 9 edges incl. the untyped-handle
case and a fan-out) and firefly-iii (large, pure auto-discovery / empty $listen,
141 edges, 0 source/target false positives, 0 namespace mismatch, union split
verified); 0 on the guzzle control. Namespace-agnostic (FireflyIII\ not
hardcoded). Node-stable (pure edge synth). Suite 1623 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Colby McHenry
2026-06-21 09:45:24 -05:00
co-authored by Claude Opus 4.8
parent 2c522c6254
commit feb2f641de
4 changed files with 316 additions and 2 deletions
+169
View File
@@ -0,0 +1,169 @@
/**
* Laravel event-dispatch bridge (PHP).
*
* Laravel decouples an event dispatch from its listener(s), linked by the event class:
* `event(new SongLiked($id))` has no static edge to the `handle(SongLiked $e)` that runs it
* (usually a separate `app/Listeners/` file). This bridges each `event(new X(...))` site to every
* listener's `handle` for X, via TWO registration mechanisms: (A) a typed `handle(EventType $e)`
* (auto-discovery, union-split for `A|B`) and (B) the `protected $listen` map in an
* EventServiceProvider (which also covers a listener whose `handle()` is untyped). Queued JOBS
* dispatch via `::dispatch()`/`dispatch()` and their `handle()` takes a service — so only
* `event(new X)` is matched and jobs are excluded.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import { CodeGraph } from '../src';
describe('laravel-event synthesizer', () => {
let dir: string;
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'laravel-event-')); });
afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); });
const write = (rel: string, body: string) => {
const p = path.join(dir, rel);
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, body);
};
it('bridges event(new X) to listener handles via typed handles, the $listen map, unions, and fan-out; excludes jobs', async () => {
for (const [name, body] of [
['SongLiked', 'public int $id; public function __construct(int $id) { $this->id = $id; }'],
['LibraryChanged', ''],
['ScanDone', ''],
['OwnerTest', ''],
['UserTest', ''],
] as const) {
write(`app/Events/${name}.php`, `<?php\nnamespace App\\Events;\nclass ${name} {\n ${body}\n}\n`);
}
// (A) typed-handle listener — auto-discovery, no $listen entry needed.
write('app/Listeners/LoveTrack.php', `<?php
namespace App\\Listeners;
use App\\Events\\SongLiked;
class LoveTrack {
public function handle(SongLiked $event): void {}
}
`);
// (B) UNTYPED handle — linkable only through the $listen map.
write('app/Listeners/PruneLibrary.php', `<?php
namespace App\\Listeners;
class PruneLibrary {
public function handle(): void {}
}
`);
// Fan-out: two listeners for ScanDone.
write('app/Listeners/WriteScanLog.php', `<?php
namespace App\\Listeners;
use App\\Events\\ScanDone;
class WriteScanLog {
public function handle(ScanDone $event): void {}
}
`);
write('app/Listeners/DeleteStale.php', `<?php
namespace App\\Listeners;
use App\\Events\\ScanDone;
class DeleteStale {
public function handle(ScanDone $event): void {}
}
`);
// Union-typed handle — one listener, two events.
write('app/Listeners/SendsTestNotification.php', `<?php
namespace App\\Listeners;
use App\\Events\\OwnerTest;
use App\\Events\\UserTest;
class SendsTestNotification {
public function handle(OwnerTest|UserTest $event): void {}
}
`);
// A queued JOB — handle takes a service, dispatched via ::dispatch()/dispatch(). Never an edge.
write('app/Jobs/ProcessAudio.php', `<?php
namespace App\\Jobs;
use App\\Services\\AudioService;
class ProcessAudio implements ShouldQueue {
public function handle(AudioService $svc): void {}
}
`);
// The $listen map — registers the untyped PruneLibrary for LibraryChanged.
write('app/Providers/EventServiceProvider.php', `<?php
namespace App\\Providers;
use App\\Events\\LibraryChanged;
use App\\Listeners\\PruneLibrary;
class EventServiceProvider {
protected $listen = [
LibraryChanged::class => [
PruneLibrary::class,
],
];
}
`);
write('app/Services/SongService.php', `<?php
namespace App\\Services;
use App\\Events\\SongLiked;
use App\\Events\\LibraryChanged;
use App\\Events\\ScanDone;
use App\\Events\\OwnerTest;
use App\\Events\\UserTest;
use App\\Jobs\\ProcessAudio;
class SongService {
public function like(int $id): void { event(new SongLiked($id)); }
public function deleteSongs(): void { event(new LibraryChanged()); }
public function scan(): void { event(new ScanDone()); }
public function ownerTest(): void { event(new OwnerTest()); }
public function userTest(): void { event(new UserTest()); }
public function process(): void {
ProcessAudio::dispatch();
dispatch(new ProcessAudio());
}
}
`);
const cg = await CodeGraph.init(dir, { silent: true });
await cg.indexAll();
const db = (cg as any).db.db;
const edges = db
.prepare(
`SELECT s.name source, t.name target, t.file_path tf, json_extract(e.metadata,'$.via') via
FROM edges e JOIN nodes s ON s.id = e.source JOIN nodes t ON t.id = e.target
WHERE json_extract(e.metadata,'$.synthesizedBy') = 'laravel-event'`
)
.all();
const bySrc = (s: string) => edges.filter((r: any) => r.source === s);
const file = (r: any) => /(\w+)\.php$/.exec(r.tf)![1];
expect(edges.length).toBe(6);
expect(edges.every((r: any) => r.target === 'handle')).toBe(true);
// (A) typed handle.
expect(bySrc('like').map((r: any) => [r.via, file(r)])).toEqual([['SongLiked', 'LoveTrack']]);
// (B) untyped handle via the $listen map.
expect(bySrc('deleteSongs').map((r: any) => [r.via, file(r)])).toEqual([['LibraryChanged', 'PruneLibrary']]);
// Fan-out: ScanDone → both listeners.
expect(new Set(bySrc('scan').map(file))).toEqual(new Set(['WriteScanLog', 'DeleteStale']));
// Union split: OwnerTest and UserTest each reach the one listener (separate dispatchers,
// so they aren't deduped to a single source→target edge).
expect(bySrc('ownerTest').map((r: any) => [r.via, file(r)])).toEqual([['OwnerTest', 'SendsTestNotification']]);
expect(bySrc('userTest').map((r: any) => [r.via, file(r)])).toEqual([['UserTest', 'SendsTestNotification']]);
// PRECISION: a queued job (::dispatch / dispatch()) produces nothing.
expect(edges.some((r: any) => r.source === 'process')).toBe(false);
cg.close?.();
});
it('produces no edges in a PHP project with no Laravel events (clean control)', async () => {
write('src/Client.php', `<?php
namespace Acme;
class Client {
public function send(string $url): string { return $url; }
}
`);
const cg = await CodeGraph.init(dir, { silent: true });
await cg.indexAll();
const db = (cg as any).db.db;
const count = db
.prepare(`SELECT count(*) c FROM edges WHERE json_extract(metadata,'$.synthesizedBy') = 'laravel-event'`)
.get();
expect(count.c).toBe(0);
cg.close?.();
});
});