process( new JsonRequest(), static fn(): Response => new Response(['ok' => true]), ); self::assertSame(['ok' => true], $response->body()); self::assertTrue($pipeline->isEmpty()); } public function testRunsMiddlewaresOutsideIn(): void { $order = []; $first = new Recorder('first', $order); $second = new Recorder('second', $order); $pipeline = new Pipeline([$first, $second]); $pipeline->process(new JsonRequest(), static function (Request $request) use ( &$order, ): Response { $order[] = 'handler'; return new Response(null); }); self::assertSame( ['first:before', 'second:before', 'handler', 'second:after', 'first:after'], $order, ); } public function testMiddlewareCanShortCircuit(): void { $blocked = new class implements Middleware { public function process(Request $request, callable $next): Response { return new Response(['blocked' => true], 403); } }; $pipeline = new Pipeline([$blocked]); $response = $pipeline->process(new JsonRequest(), static function (): Response { self::fail('The handler must not run when a middleware short-circuits.'); }); self::assertSame(403, $response->status()); } public function testWithReturnsCopy(): void { $order = []; $base = new Pipeline(); $withOne = $base->with(new Recorder('x', $order)); self::assertTrue($base->isEmpty()); self::assertCount(1, $withOne->middlewares()); } } final class Recorder implements Middleware { /** * The array is shared by reference with the test, so appending to it is the only operation. * * @param list $order Passed by reference so the test observes the shared log. */ public function __construct( private readonly string $name, /** @phpstan-ignore property.onlyWritten */ private array &$order, ) {} public function process(Request $request, callable $next): Response { $this->order[] = $this->name . ':before'; $response = $next($request); $this->order[] = $this->name . ':after'; return $response; } }