ptgs / php-type-bridge
Static API contract collection and TypeScript generation for PHP APIs
Requires
- php: >=8.4
- nette/neon: ^3.4
- phpstan/phpdoc-parser: ^2.3
- symfony/config: ^7.3 || ^8.0
- symfony/console: ^7.3 || ^8.0
- symfony/dependency-injection: ^7.3 || ^8.0
- symfony/event-dispatcher: ^7.3 || ^8.0
- symfony/form: ^7.3 || ^8.0
- symfony/http-foundation: ^7.3 || ^8.0
- symfony/http-kernel: ^7.3 || ^8.0
- symfony/routing: ^7.3 || ^8.0
- symfony/validator: ^7.3 || ^8.0
- symfony/yaml: ^7.3 || ^8.0
Requires (Dev)
- phpstan/extension-installer: ^1.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-symfony: ^2.0
- phpunit/phpunit: ^11.0
- ptgs/phpstan-rules: dev-main
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-12-04 12:26:36 UTC
README
PTGS\TypeBridge is a static contract and TypeScript generation package for PHP APIs.
It provides:
#[ApiResponses([...])]to declare flat endpoint response contracts#[ApiRequest(...)]to declare flat endpoint request contracts for query/body/path inputs- semantic status marker interfaces such as
HttpOkandHttpCreated - collectors for
_selfPHPStan shapes, response DTOs, endpoint contracts, and Symfony form-backed request inputs - a PHPStan extension for endpoint, contract-form, and shape-naming enforcement
- a TypeScript emitter that produces shape types, response types, request aliases, and endpoint result unions
- configurable TypeScript naming for interfaces, enum value aliases, enum
_selfobjects, and endpoint alias suffixes
Docs
Example: serializable enum as object data
If an enum serializes itself as an object, keep the enum as the source of truth and declare _self on the enum.
/** * @phpstan-type _self = array{ * value: value-of<ProjectStatus>, * label: string, * color: string, * } */ enum ProjectStatus: string implements \JsonSerializable { case Draft = 'draft'; case Active = 'active'; /** * @return _self */ public function jsonSerialize(): array { return [ 'value' => $this->value, 'label' => match ($this) { self::Draft => 'Draft', self::Active => 'Active', }, 'color' => match ($this) { self::Draft => 'slate', self::Active => 'green', }, ]; } }
Import that _self where needed:
/** * @phpstan-import-type _self from ProjectStatus as ProjectStatusData * * @phpstan-type _self = array{ * statusDetail: ProjectStatusData, * } */ final class ProjectAdminView { }
The generated TypeScript keeps both forms:
export type ProjectStatus = 'draft' | 'active'; export interface ProjectStatusData { value: ProjectStatus; label: string; color: string; }
Enum-owned _self shapes emit with a suffix (default Data) to avoid colliding with the enum value union. Override via enumShapeSuffix (see TypeScript naming).
When the enum's name belongs to the object it serialises to, name its value union instead with #[ValueOfName]. The _self then takes the enum's own name, as any class's _self does:
/** * @phpstan-type _self = array{code: value-of<Currency>} */ #[ValueOfName('CurrencyCode')] enum Currency: string implements JsonSerializable { … }
export type CurrencyCode = 'AUD' | 'NZD'; export interface Currency { code: CurrencyCode; }
A shape that names the class — currency: Currency — is that interface, and value-of<Currency> is CurrencyCode, wherever they are written.
TypeScript naming
If you need project-specific naming, pass a config file to the generator:
php bin/console typebridge:generate src assets/types --config=type-bridge.php
type-bridge.php should return an array:
<?php return [ 'typescript' => [ 'interfacePrefix' => 'I', 'enumValueSuffix' => 'Id', 'enumShapeSuffix' => '', 'queryAliasSuffix' => 'QueryParams', 'bodyAliasSuffix' => 'Payload', 'pathAliasSuffix' => 'RouteParams', 'endpointMapSuffix' => 'Responses', 'endpointResultSuffix' => 'Outcome', ], 'preserveNull' => [ 'Project.archivedAt', 'ProjectStage.parentId', ], ];
Defaults when unset:
| Key | Default |
|---|---|
interfacePrefix |
'' |
enumValueSuffix |
'' |
enumShapeSuffix |
'Data' |
queryAliasSuffix |
'Query' |
bodyAliasSuffix |
'Body' |
pathAliasSuffix |
'PathParams' |
endpointMapSuffix |
'EndpointMap' |
endpointResultSuffix |
'Result' |
The knobs are intentionally narrow:
interfacePrefixapplies only to declarations emitted asinterfaceenumValueSuffixrenames the backed-value union fromvalue-of<MyEnum>enumShapeSuffixrenames enum-owned_selftypes before any interface prefix is applied- request and endpoint alias suffixes rename the flat transport helpers without changing the underlying source-of-truth PHP names
For example, the config above emits:
export type ProjectStatusId = 'draft' | 'active'; export interface IProjectStatus { value: ProjectStatusId; label: string; color: string; } export type ProjectCreatePayload = ICreateProjectRequestData;
TypeBridge fails fast if a custom naming scheme would emit colliding symbols in the same domain.
Current scope
This first cut is focused on contract collection and code generation:
_selfshape collection with@phpstan-import-typesupport- method-level request contract collection via
#[ApiRequest(...)] - Symfony form-backed request metadata collection, including configured
data_classand built field trees ContractFormType<TData>enforcement for top-level and nested custom contract forms- generated TypeScript request aliases for query/body/path inputs
- response DTO status resolution
- endpoint contract collection
- generated TypeScript endpoint maps and
EndpointResultunions - a generated
Endpointconstant per endpoint: its method and path, typed with its responses and inputs (see Calling an endpoint) - PHPStan rules for:
#[ApiResponses]on routed API controller methods#[ApiRequest]on routed mutating API controller methods- returned/thrown typed response classes being declared in
#[ApiResponses] ContractFormType<TData>syncing withdata_class,_self, mapped fields,property_path, nested custom forms, enums, dates, collections, and common scalar leaf types_selfshape naming: noIdsuffix on string reference fields
For request contracts, query and body point at Symfony form types directly. TypeBridge resolves the form's data_class and uses that class's _self definition as the generated wire contract.
Custom forms participating in request contracts must implement PTGS\TypeBridge\Contract\ContractFormType.
A mutating route that takes no input — a POST that only triggers work — still carries #[ApiRequest], bare. The collector records no request contract for it (the generated input schema is an empty object) and MutatingApiRequestRequiredRule reads the bare attribute as the explicit declaration it asks for, so the absence of input is stated rather than flagged.
The application remains responsible for runtime HTTP emission.
Calling an endpoint
Each endpoint also emits a constant saying how to call it. It is plain data, method and path, typed with the endpoint's response map and the inputs it takes, so a client's own helpers can call any endpoint without restating its URL or its types:
export const UpdateProject: Endpoint<UpdateProjectEndpointMap, { path: UpdateProjectPathParams; body: UpdateProjectBody }> = { method: 'PUT', path: '/api/projects/{id}', };
The inputs are path when the route has placeholders, body when the request has one, and query — query?, which a caller may leave out, unless the query's contract requires a key (product: string), when it is query and a call without it does not compile. A key typed with an alias is what the alias is declared — its own, imported, another class's _self — at any depth, its nested keys and its list's items included: one that admits null — MaybeCode where @phpstan-type MaybeCode = string|null, or a config alias whose TypeScript says so (string | null, unknown, any, another of the config's aliases that does) — may be left out, as string|null written out may. A config alias whose TypeScript can't say without evaluating it — a generic of its own, a conditional, an indexed access — fails where a request's key is typed with it and its null decides something, rather than have the Endpoint and the tool read the key two ways — the tool's manifest for an MCP tool's key, which may be sent null or left out as it says — not one a query may leave out already, a list's item in a query, or a path's. Where no tool reads the key, all its null decides is whether the Endpoint's query may be left out, and it is taken not to: a query required is one any call can send, and AsQuery<T> still says each key. Write the null out, X | null, or NonNullable<X>. An input whose _self is an alias of a shape (@phpstan-type _self = NoteInput) has that shape's keys. One of ?string admits none — it is a key left out when null, and its TypeScript is string — so a key typed with it is one a caller must send. A query form's type is taken as a query string sends it, AsQuery<T>: a key that may be null may be left out, at any depth, and is only ever left out — what it takes when sent is never null, which a client would send as the text null — a primitive — a branded string (string & { __brand }) included — and TypeScript's Date (globalThis.Date, whatever a module names Date) stay as they are, and a list or a tuple stays one, while T itself stays as declared for whatever else uses it. types is never set; it is there for a helper to read the endpoint's types off it: E extends Endpoint<infer M, infer I>. The path is the one Symfony serves when the routing config is given, its prefixes and any class-level #[Route] included. Without it, the route is the one the controller's attributes declare, read by Symfony's own attribute loader: a class-level #[Route]'s path, requirements and methods merged into the method's, and an invokable class's #[Route] its __invoke's — the one it declares, though routing config also routes Class::__invoke. The router is the one the application is deployed with, in the env the routingEnv config names — prod unless it says otherwise (mirror it as typeBridge.routingEnv in phpstan.neon): a route confined to another env (env: 'dev'), and what the routing config imports in another env's section alone (when@dev:), are not served there, and the MCP manifest fails on a tool for one, saying so — production would answer 404 to it — whether the routing config is given or not, and on a tool no #[Route] declares where it isn't, which has nowhere to read its path from; its TypeScript is still generated. Another env's section is never read, so one that can't be (a when@dev import of a bundle's file) is no matter. Its Endpoint is still described by its route in the env it is confined to. The path and its params — {!_format} among them, published as {_format}, as a client fills it — are that route's, in the Endpoint, the tool and the PHPStan rules alike, and so is the HTTP method: of those the route serves, the one the method's own #[Route] names, since Symfony merges a class's in ahead of it; a class whose routes Symfony refuses to read fails, saying why — but for a method whose own #[Route] it takes, read alone, as where it refuses another method's of a controller the router never reads. A method with more than one #[Route] is described by its first — its path, its params' names and their requirements — whatever order the router lists them in (a priority sorts a later one first), and so is the method the PHPStan rules check; where the router doesn't serve its first, confined to another env, by the one it does. A route that leaves utf8 to the router's default — FrameworkBundle's is on — is read as that router compiles it where a Unicode requirement needs it, its mode left unknown. A requirement, a default or an argument mapping written inline is read as the router reads it: /pages/{page<\d+>}/{slug?intro} is the path /pages/{page}/{slug}, page holding to \d+, and /notes/{slug:note} is /notes/{slug}. A param's type is the project's requirementTypes entry for its requirement as the router holds it, anchors off, so an entry keyed ^\d+$ as the attribute writes it still answers. A tool takes it as the JSON type that type stands for — a project-wide alias read through (UuidStr is a string) — a number or a boolean as one, anything else as the string a path segment is, holding to its requirement; a number holds to it too: an integer of at least 0 or 1 where it is written as taking every whole number from there up (\d+, [0-9]+, [1-9]\d*), of any where it is signed (-?\d+) — up to 2^53 - 1 either way, past which a JSON client writes one near it, and from 1e21 in exponent form — and otherwise the string its pattern says (\d{1,4}, \d*[0-46-9], a decimal, which a client may write in exponent form), since no sample of values shows a requirement has no gap; a number only where its pattern can't be carried over (a %…% placeholder). A class on #[ApiRequest(path: …)] types the Endpoint's path; the tool still takes the route's placeholders, as the router reads them, and the class's keys are read by neither. TypeBridge sends nothing itself: how a request is made, and what an error status does, is the client's to decide.
Metadata about a response
A response's public properties are its body, each under its name. One that says something about the response, rather than being part of what was asked for — the page a list was cut at — is marked #[Metadata], and is sent and published under its name behind a $:
final readonly class ListNotesResponse implements HttpOk { public function __construct( /** @var list<NoteData> */ public array $notes, /** @var PageData */ #[Metadata] public array $pagination, ) {} }
export interface ListNotesResponse { notes: NoteView[]; $pagination: PageData; }
No property can be named with a $ itself, so a metadata key never collides with one. Only the key changes: the property is typed, and written out, as any other is, and an include or expand path names it by its key ($pagination.total). A subclass that redeclares the property, by promoting it in its own constructor, keeps the key.
PHPStan types in shapes
A shape is written for PHPStan first, so TypeBridge reads the PHPStan types a codebase actually uses and emits the TypeScript that describes the same JSON:
| PHPStan | TypeScript |
|---|---|
positive-int, non-negative-int, int<0, max> … |
number |
non-empty-string, numeric-string, class-string<T> … |
string |
scalar |
string | number | boolean |
array-key |
string | number |
array<array-key, V>, array<V> |
Record<string, V> | V[] (json_encode writes whichever the keys make it) |
array<mixed, V>, iterable<object, V>, array<int|string, V>, array<numeric-string, V>, array<numeric, V> (a key no PHP array has, or every one) |
Record<string, V> | V[]: an array is keyed by the ints and strings PHP makes of it — a key a template param is bound to, or an alias stands for, too, a project-wide alias read by its TypeScript, through the config's other aliases: string | number alone, Text|int where Text is a string, or what no array is keyed by, boolean say, which PHP makes a key of |
non-empty-list<T>, non-empty-array<K, V> |
T[], Record<K, V> |
array{id: string, ...} (unsealed) |
{ id: string; [key: string]: unknown } |
array{int, string, ...} (unsealed tuple) |
[number, string, ...unknown[]] |
self::STATUS_*, Foo::BAR, parent::BAZ |
the constants' values: 'draft' | 'live'. A null value is an error, since nullability is written as ?T or T|null, and so is one static:: constant of a class that is not final, which PHPStan reads by its declared type |
value-of<self::OPTIONS>, value-of<Status::*> |
the elements of array constants, or the backing values when every constant matched is an enum case. A mix, any other constant, or a match with no value at all (only empty arrays or pure cases: PHPStan's never) is an error |
(A | B), Base & array{...} |
A | B, interface … extends Base |
MoneyInterface, \Acme\Money (a class) |
the JSON it serialises to — see below |
included<T> — a generic listed in includes.types |
T, on a key absent unless asked for — see below |
ref<T> — a generic listed in includes.refTypes |
Ref<T>: an id a request can expand to T — see below |
enum<T> — a generic listed in includes.enumTypes |
T's own type: an enum the normaliser hands over as a marker |
A refinement keeps its spelling in the parsed tree, so a shape rendered back to PHPDoc reads as it was written.
PHPStan reads Base & array{...} the same way: one shape holding the keys of both, which a normaliser returns as [...$base, 'extra' => …] (ShapeIntersectionTypeNodeResolverExtension, auto-loaded through extension.neon). On its own PHPStan reads the intersection of two shapes as a set of values: never when they share no required key, and without the keys of a part whose keys are all optional. The extension reads only the form the parser takes, a type alias naming one closed shape and then a keyed array{...}, open or not. As in an interface extending another, a key the base declares may be declared again only to narrow it (a narrower type, or required in place of optional); any other redeclaration is an invalid type. An open base, and any other form, is PHPStan's own reading.
Keys sent only when asked for
An API can leave parts of a response out unless the request asks for them (?include=checks.debug), and mark those keys in its shapes with a generic of its own — included<T>, which its PHPStan extension reads as T|Optional<T>. Whether such a key is there depends on two things, and the shape says which:
| Shape key | Present on the wire when… | Depends on |
|---|---|---|
debug: included<mixed> |
exactly when the request includes it | the request only |
documentation?: included<string> |
the request includes it and there is a value | the request and the data |
notifiedAt?: DateTimeData |
there is a value | the data only |
name: string |
always | nothing |
The key's ? carries the difference, and PHPStan keeps it honest: a required key whose value could be null fails analysis, since the null would be dropped before the response is sent. A side-loaded collection is in the first row by construction — asked for, it is always there, as an empty list when nothing is referenced.
Tell TypeBridge how the project marks them:
'includes' => [ 'types' => ['included'], // the include generics 'sideLoadAttribute' => SideLoad::class, // the attribute on a side-loaded response property ],
An included key always emits as optional, since it is absent unless asked for. The keys in the first row — required included<> keys, and side-loads — are listed in a …Included union beside the shape or response. WithIncludes<T, P> makes the keys a request's include paths name present, at any depth. It is declared in the shared root module when the output has one (output.rootModule), and in each module that needs it otherwise:
export interface SystemCheckData { name: string; debug?: unknown; documentation?: string; } export type SystemCheckDataIncluded = 'debug'; export interface ListSystemChecksResponse { checks: SystemCheckData[]; definitions?: SystemCheckDefinitionData[]; } // One list drives both the request and the type, so they cannot drift apart. const CHECKS_INCLUDE = ['checks.debug', 'definitions'] as const; type Checks = WithIncludes<ListSystemChecksResponse, typeof CHECKS_INCLUDE>; const response = await api.get<Checks>('/checks', { params: { include: CHECKS_INCLUDE.join(',') } }); response.data.checks[0].debug; // there: the path reaches through the list response.data.definitions.length; // there: a side-load asked for
P is a dotted path, a union of them, or a list. Each is checked against IncludePath<T>, which covers every key path in T to five levels, so a misspelt path ('checks.debgu') does not compile. That check is against the type, not the API's include vocabulary: a path to a key that is always sent still compiles, and it changes nothing.
References a request can expand
A related record can go out as its id and, when the request expands its path (?expand=checks.definition), as the record itself — the server swapping one for the other. A shape marks such a key with a generic of its own, naming the shape the record is sent as: definition?: ref<DefinitionData>.
'includes' => [ 'types' => ['included'], 'refTypes' => ['ref'], // the reference generics ],
It emits as Ref<DefinitionData>: the record's id, typed as the record types its own id, and flavoured with the record under a ~ref key that is never sent. A plain id is still assignable to it and it reads as one, so a ref works as an id anywhere an id is wanted. WithExpands<T, P> swaps it for the record at the paths a request expanded — through lists, and on into the record, so checks.definition.latestResult expands a ref inside an expanded one:
export interface CheckData { name: string; definition?: Ref<DefinitionData>; } export interface DefinitionData { id: string; name: string; latestResult?: Ref<ResultData>; } type Checks = WithExpands<ListChecksResponse, ['checks.definition']>; declare const checks: Checks; checks.checks[0].definition?.name; // the record checks.checks[0].definition?.latestResult; // still an id: not expanded
P is checked against ExpandPath<T> — the refs in T, and the refs inside what they expand to, five levels deep — so a path that names anything but a reference does not compile. Ref, ExpandPath and WithExpands are declared beside WithIncludes, in the root module or in each module that has a ref, and no type may take their names, nor those of the types they declare beside them (see Shared declarations). The two compose: WithIncludes<WithExpands<T, X>, P> includes keys inside expanded records.
A normaliser that hands an enum over as a marker of its own, for its serialiser to write out, says so with a generic listed in includes.enumTypes: status: enum<Status> emits as status: Status, what the marker is sent as.
Any other generic TypeBridge does not know is an error that names includes.types, includes.refTypes and includes.enumTypes.
The query parameters a request asks with are includes.query, each named with its description:
'includes' => [ // … 'query' => [ 'include' => 'Opt-in parts of the response, comma-separated dotted paths.', 'expand' => 'References to send as their records, comma-separated dotted paths.', ], ],
Every endpoint whose success response has a body takes them, so no action declares them on its query form: its query type is IncludeQuery (declared once, beside WithIncludes), intersected with its form's (AsQuery<T>) when it has one, and its MCP tool lists them among its arguments, sent in the query string. An endpoint that answers 204 has nothing to shape and takes none.
The runtime that writes these keys out — optionals, refs and enum markers — is opt-in: see Includes and expands at runtime.
Shared declarations
The config typeAliases (UuidStr, …) and the WithIncludes, WithExpands, AsQuery, IncludeQuery, EndpointResult and Endpoint helpers are the same everywhere, and a config alias is always the emitting module's own — a property inherited from a base in another module included — never an import. With a shared root module (output.rootModule) they are declared there once and each module imports what it uses; without one, each module declares its own copy. Either way no other type of a module — nor of the root module — may take a helper's name, or that of an endpoint's own input, map or result (GetNotePathParams), nor may one of those take another's — an endpoint Endpoint's result is EndpointResult: generation fails, naming both. That is every name a helper declares, the ones it keeps to itself included (ExpandPath, ListItem, IncludePath, …), where it is declared — the expanding helpers in a module with a reference (ref<T>), the including ones in a module with a key present whenever it is asked for (its …Included union) — or, with a root module, in the root module for every module's, whether it has types of its own or not, and Ref in each module that imports it — or every name, in one that declares the expanding helpers beside its endpoint Ref. A module that uses neither names its own types as it likes. A config alias that names another (NoteId: 'UuidStr') is declared with it, though the module's code names only the first; with a root module, the module imports only what its code names. The global generics of TypeScript's the generated code writes — Record, Array, Omit, Exclude, NonNullable, and those a config alias's TypeScript may (Partial, Pick, Readonly, ReturnType, …) — are no module's to declare: a type of its own of one of those names — one a discovered emitter declares or imports included — fails where its code uses the global, naming both, and one it imports is imported under another name (Record as CommonRecord). So is any name a project-wide alias's TypeScript uses but another alias — Date in Stamp: 'Date', a library's type — in a module declaring that alias: it means the same in every one, and an import of one is imported under another name. A discovered emitter's code names what it declares and imports as it is, so none of those names can be given another — what a block declares being the names it states (new EmittedBlock(…, declares: ['Record'])), its code never read for them, and a block that states none held to nothing: one the module declares, imports under any name, or another discovered emitter declares or imports from elsewhere fails, naming both — but the import the module has of it from the same module, which is the one import. A type of such a name imported from another module is imported under another — the module's name and its own, AdminChecksMeta from Admin/Checks — as is one named as an endpoint, whose const the module declares, though a type of its own may share that name: so a helper or a config alias named as one of the module's endpoints is declared in the module, as it is without a root module, not imported from the root module. An enum is declared in its own module whenever anything emitted names it — a property a response in another module inherits from a base in that one included — and that module is written for it if it has nothing else. A module imports only the types it references — a class's @phpstan-import-type that none of its emitted shapes uses is left out, and is no matter wherever it points: a base class may import for a property that is never sent. A class this install can't load — one kept under src/ for tooling, whose declaration needs a require-dev package — is no part of the application: it emits nothing, and a sent type naming one of its aliases fails, saying why.
Modules
Each domain is one module: the directories a class sits in under the source root, output.domainDepth levels deep (default 1). At 1, everything under src/Admin/ is one admin module. At 2, src/Admin/SystemChecks/ is a module of its own, admin/systemChecks, which keeps modules small in a codebase organised by subdomain. Modules import each other by relative path (../../entity/genTypes). A module that both the full pass and a discovered emitter write is written once, with the declarations of both.
Types every domain shares — money, dates, an entity reference — belong beside the config aliases rather than in a module of their own. output.rootSources lists the paths under the source root whose types are declared in the root module: a directory covers everything beneath it, a file only itself. It needs output.rootModule.
'output' => [ 'rootModule' => 'genTypes.ts', 'rootSources' => ['_', 'Entity', 'Event/EntityRef.php'], ],
Moving a class into or out of a root source moves its type on the next generate; the imports that name it follow.
Classes in shapes
PHPStan-typed code often holds objects in an array that json_encode then serialises — array{total: MoneyInterface} — so a shape may name a class, and it means the JSON that class serialises to:
- its
_selfshape, or the nearest parent's or interface's when it declares none (Money implements MoneyInterfacetakesMoneyInterface's), imported from that class's module; - or the type it imports as its
_self, when what it serialises to is declared elsewhere —@phpstan-import-type MoneyData from AbstractV2Normalizer as _self. The shape is thenMoneyData, wherever it is written, and the class emits nothing under its own name, so a client has the one type to use; - otherwise, the type the emitter that claims the class publishes for it — an emitter implementing
TypeSymbolEmitter, as a serialisable enum's does; - otherwise, for a backed enum that doesn't serialise itself (no
JsonSerializable), its values — what json_encode writes, strings or ints, asvalue-of<…>names them — so a nativeErrorCode $code, or a keycode: ErrorCode, is the enum's type, declared in its module. An enum something above gives a type declares no values for its name, so a module's alias of its short name doesn't clash; - otherwise it is an error that says so.
The name resolves as PHP resolves it: through the file's use statements, in its namespace, or fully qualified. An alias of the same name always wins over a name used bare, so nothing that resolved before changes — an alias of the module the name is written in: a property a response inherits, from a base class or a trait in another module, means what it means in that module, whichever module the response is in, and a concrete base's property is one type in its own interface and its children's. A property declared outside the source tree — a library's base class or trait — is read in the library's file, as PHPStan reads it: that file is in no module, so a name there is the class it names, through its own use statements and namespace, never a module's alias. A name it can't resolve to a class fails, as does an alias the library declares or imports itself, which nothing emits. A class with no file to read — declared by PHP, an extension or at run time — has no names of its own: its property is published as its declaration spells it. In a library's file a project-wide alias is still the emitting module's own, and a value-of<…> or id-of<…> names the enum its file does, not whichever enum of the source tree shares its short name: one outside the source tree is emitted as one the source tree names from outside it is (in Common), and a name that is no enum this install can load fails, saying so. A name resolved to a class — written in full, or through a use — is that class, whatever alias the file imports under its short name: an import answers only to a name used bare. A name written in full — \App\Common\Money, or a native type, which Reflection names in full — is that class whatever alias of the module shares its short name too, and a response class is the interface its response is emitted as. The class an import names (from Shapes) is the one the file's use statements name, as PHP resolves it, before one of that name in its namespace. An alias imported from a class that only imports it itself is the type where it is declared, as PHPStan reads it, imported from that one's module — followed alias by alias, so it is the same whichever class is read first. A property a generic base declares (@template T, /** @var list<T> */) is what the response binds it to: each class's @extends Base<…> — or @phpstan-extends — read in its own file and module, so a name it writes is what it means there, not in the base's, through any base between that passes its own param on; a param nothing binds is its default (= …), else its bound (of …), else unknown, a default or a bound naming a param before it (TList = list<TItem>) that param as bound; and a property extending one (T & array{…}) is what T is bound to, extended — a union whole, each of its members. A property a class declares in its own body is read in its own file, though a trait it uses declares it alike — PHP takes a redeclaration that agrees, doc comment and all. One a generic trait declares is what the class using it binds it to — /** @use HasRows<string> */ on its use — read in that class's file, through a trait that uses another and passes its own param on. Template tags are read as PHPStan ranks them: @phpstan- over @psalm- over plain, per param. A property with no docblock is published as its native type says, as the same keyword in a docblock is: a nullable one keeps its null, a class — self and parent included — is the one it names, array and iterable are a list or an object of anything (Record<string, unknown> | unknown[]) — iterable in a union too, which PHP reflects as Traversable|array — and object anything but null (NonNullable<unknown>). In a docblock those keywords are read as PHPStan reads them, in any case (NULL, Boolean, Array<…>, FALSE), none of them null but null, and a keyword a namespace begins with no keyword (Integer\Amount) — list a list of anything, integer, boolean and double an int, a bool and a float, self and static the class the type is read for and parent its parent — and iterable<V> is the array of V it is sent as, as array<array-key, V> is, iterable<K, V> as array<K, V> is. An alias a file imports is the type it imports under the name it imports it as, so a file may declare a Meta of its own beside @phpstan-import-type Meta from CommonShapes as CommonMeta: each is emitted as what the file means by it, the other module's Meta imported under another name where the two meet.
Shapes that type PHP arrays which are never serialised — working data holding DateTimeImmutables or entities — have no JSON to describe. Mark the class that declares them #[PhpStanOnly] and TypeBridge emits none of its aliases — or #[PhpStanOnly(['Draft'])] for only those named, when the class also declares shapes that are sent. A shape that is sent and typed with one, declared or imported, fails, naming it — even where another class emits an alias of the same name. One-argument array<V> is read as PHPStan reads it, array<array-key, V>: write list<V> or array<string, V> where that is what it is, for the tighter type.
Includes and expands at runtime
The sections above type a body the app writes. TypeBridge can also write it: an opt-in runtime turns the markers a normaliser returns into the body the request asked for — ?include=, ?expand= with field lists, and enums whole or as bare ids. Controllers return their response DTO as before and never see any of it.
Turning it on
# config/packages/type_bridge.yaml type_bridge: includes: true # or, with its options: # includes: # enum_format_header: X-Enum-Format # the header whose value `id` asks for bare ids # json_encoding_options: !php/const JSON_UNESCAPED_UNICODE # json_encode() flags; JsonResponse's defaults otherwise
Off, the bundle behaves exactly as before. On, IncludeResponseSubscriber writes every ApiSuccessResponse that has a body, on kernel.view at priority 0, ahead of TypeBridgeResponseSubscriber (which still answers 204s). It reads include and expand from the query string whatever the method, so name those two in includes.query and TypeBridge publishes them on every such endpoint (see References a request can expand).
Marking a shape in the normaliser
A normaliser uses the IncludeMarkers trait — a trait, so it sits beside whatever base class the normaliser already extends:
use PTGS\TypeBridge\Normalizer\IncludeMarkers; /** * @phpstan-type _self = array{ * id: string, * name: string, * status: enum<CheckStatus>, * definition?: ref<DefinitionData>, * debug: included<array<string, mixed>>, * } * * @implements ShapeNormalizer<Check, self> */ final class CheckNormalizer extends AbstractShapeNormalizer implements ShapeNormalizer { use IncludeMarkers; public function normalize(object $check): array { return $this->filterNulls([ 'id' => $check->getId(), 'name' => $check->getName(), 'status' => $this->enum($check->getStatus()), 'definition' => $this->ref($check->getDefinition()), 'debug' => $this->optional(fn () => $check->getDebug()), ]); } }
| Helper | Shape key | Sent as |
|---|---|---|
optional(fn () => …) |
included<T> |
absent unless ?include= names its path; the closure runs only then |
ref($entity), refs($entities) |
ref<RecordData>, list<ref<RecordData>> |
the id, or the record where ?expand= names its path |
enum($case) |
enum<Status> |
an ApiEnum's object, or its id on request; any other backed enum's value |
ref(), refs() and enum() give null for null. ref() names the entity's class and its getId() (a string, an int or a Stringable, sent as a string); override refClass() or refId() for entities that carry their id another way, or write new Ref(Definition::class, $id) for a relation held only as an id. Keep an optional() closure to data in hand: it runs once per row, so one that queries is an N+1 — a related entity is a ref().
Expanding a reference
A normaliser that can send the record a ref points at implements RefNormalizer:
final class DefinitionNormalizer implements ShapeNormalizer, RefNormalizer { // normalize() as for any ShapeNormalizer, and: public static function entityClass(): string { return Definition::class; } public function resolveMany(array $ids): array { return array_map($this->normalize(...), $this->definitions->findBy(['id' => $ids])); } }
The bundle tags every autoconfigured implementation, and RefRegistry matches a ref's class with is_a(), so a Doctrine proxy finds its entity's normaliser. Each record carries its id. Every ref a request reaches at one level is fetched with one resolveMany() per entity, each id once, and the records are walked in turn: a path goes on into them (checks.definition.latestResult), include paths reach inside them, and a reference cycle is followed only as far as a path spells it out. A ref that no RefNormalizer claims, or a record it does not return, is a server bug (LogicException), not a 422.
Refusing an expand
A record a caller may read can reference one they may not, and a path goes on through it. An app whose callers may not see everything a reference leads to registers an ExpandGuard, the service IncludeResolver asks before it expands:
#[AsAlias(ExpandGuard::class)] final readonly class RoleExpandGuard implements ExpandGuard { public function mayExpand(string $entityClass): bool { return $this->currentUser()->mayExpand($entityClass); } }
It is asked about each entity an expand reaches, once a request, before anything of that entity is fetched — with the entity's own class, never a Doctrine proxy. A refusal ends the body: the subscriber answers 403 with the path that reached it ( `checks.owner` cannot be expanded by this caller.), never the entity. Without a guard every reference expands, as before.
Sending an enum whole
An enum that goes out as an object implements PTGS\TypeBridge\Enum\ApiEnum, which asks for id() and jsonSerialize(): array:
enum CheckStatus: string implements ApiEnum { case Ok = 'ok'; case Warning = 'warning'; public function id(): string { return strtoupper($this->name); } public function jsonSerialize(): array { return ['id' => $this->id(), 'name' => ucfirst($this->value)]; } }
status: enum<CheckStatus> goes out as {"id": "WARNING", "name": "Warning"}, or as "WARNING" to a request sending X-Enum-Format: id — what an MCP client wants, since a model reads an id as well as a label and its tools take ids back. An expand naming the enum's path sends it whole even then, or cut to a field list: checks(name,status(name)). A backed enum that is not an ApiEnum goes out as its value either way.
Paths
- Comma-separated dotted paths from the response's root. A path implies its prefixes, and a list's items sit at the list's own path.
include:x.*opens every optional key one level under x — never at the root, never mid-path.expand: no*, since each expansion is a query. A field list narrows what is at a path to those keys and itsid, keeping any key a deeper path goes on into: a record (checks.definition(name)), the rows themselves (checks(name,status)), or nested (checks(name,status(name))). The same path given twice merges its lists, a path without a list asks for the whole thing, and an unknown field is skipped.- A 422 for a root that is not a field of the response, a malformed path, a field list on
include, or an expand that ends at something that is neither a ref, anApiEnumnor narrowed by a list. It is the app's own 422: the subscriber builds it with the boundValidationErrorResponseFactory, its pathincludeorexpand. - A 403 for an expand the app's
ExpandGuardrefuses (see Refusing an expand).
Markers are found in the response's public properties and the arrays beneath them; any other object is left for json_encode(), and not looked into.
PHPStan
includes: - vendor/ptgs/php-type-bridge/includes.neon
It reads included<T> as T|Optional<T>, ref<T> as a Ref and enum<E> as an EnumCase<E>, so PHPStan holds each normaliser to the shape it says it returns. It also registers ShapeValuesRule (typeBridge.shapeValue): a shape written by a normaliser that uses IncludeMarkers — one it declares, or its ShapeNormalizer owner's — holds scalars, lists, shapes and the markers, never an object, so every decision about what goes out is made in the normaliser. The generic names default to included, ref and enum; an app that names them otherwise mirrors its TypeBridge config, replacing the list:
parameters: typeBridgeIncludes: types!: [opt]
PHPStan
Include the packaged rules in your project config:
includes: - vendor/ptgs/php-type-bridge/extension.neon
The rules intentionally target the analyzable subset. If a contract form becomes too dynamic, TypeBridge should fail instead of guessing.
Shape naming allowlist
The _self shape-naming rules flag any string field ending in Id as a reference that should be named after the entity (e.g. project rather than projectId). External-system identifiers can be allow-listed:
parameters: typeBridge: shapeNaming: allowIdSuffix: - stripeCustomerId - xeroInvoiceId
Preserve-null consistency
Nullable fields in @phpstan-type shapes carry two distinct meanings:
?T— the value is optional. Wire payload omits the field when null; TypeScript emitsfield?: T.T|null— null is semantically meaningful (e.g.archivedAt: nullfor "never archived"). Wire payload always sends the key; TypeScript emitsfield: T | null.
To keep the two consistent across a codebase, list every field whose null is meaningful in preserveNull, by the name its shape is collected under — before interfacePrefix or enumShapeSuffix rename it: a class's _self by the class's name, an alias by its own, an enum's _self as {Enum}Data whatever its suffix, or the enum's own name under a #[ValueOfName]. The PHPStan rule, which knows no TypeScript naming, reads the same names. The PHPStan rule enforces that listed fields use T|null and unlisted fields use ?T, on a class's shapes, an enum's, an interface's and a trait's alike:
parameters: typeBridge: preserveNull: - Project.archivedAt - ProjectStage.parentId
Mirror the same list in type-bridge.php so the emitter validates at codegen time too (the emitter throws on the same mismatch).
In a request contract, T|null is an update's "clear this": left out, the field keeps its value; sent as null, it is cleared. An MCP tool publishes such a body key as taking null (type: [T, "null"], or null in its enum), at any depth — a shape's keys, an embedded form's fields, a collection's entries — unless validation refuses it. What it refuses is what a null sent becomes, which is what a key left out becomes too: null for most fields; '' for a text field or an entry whose empty_data is '', which keeps a blank value a string; an empty list for a collection or a multiple choice; false for a checkbox; and a field's own empty_data, through its transformers, where it holds a value — 'n/a', or 0 from '0' on a number. Symfony's validator is asked about that value against the field's constraints — those a Sequentially or a Compound nests included, in the Default group, as a request is validated: one nested there but confined to another group holds nothing — or an entry's (its All, its entry_options — those its type defines, an option of a form extension inspection doesn't load left out — its entry type's own; the Default group's): a NotNull refuses a null, a NotBlank an empty list or '' whether or not it allows null, a Count or a Length too few. The body of a POST — a request that makes something — requires a field whose blank value is refused, though its contract, shared with an update, says the key is optional. How a field left out is read turns on how the application submits a body, which the clearMissing config says. Off — the default — it is not submitted at all, so none of its form's own constraints runs, and its property keeps what a new object holds there — its default, or null — which a POST requires it where the property's constraints refuse, and a query too, whose filter object is new on every request; Symfony checks nothing else of it, so an application submitting a body that way must refuse a create missing a field it can't go without itself, as clearMissing on would have, and one whose own constraints hold a NotBlank or a NotNull at their top, in any group, is read as so refused — what such a processor checks of a field left out, and not one a Sequentially holds: a POST's body requires it too, at any depth. A query's does not, nor anything else an application refuses on its own, which its contract says. On — Symfony's own $form->submit($data), as the bundled RequestFormProcessor submits a body and a query — it is submitted blank whatever the method, a PATCH included, so a PUT or a PATCH requires what refuses that as a POST does, a query's field as much as a body's, and an embedded form's fields are each submitted blank in turn. The Endpoint is typed from the contract alone, so a key the form refuses left out where its contract lets it be is required by the tool and not by a typed client, whose query? it leaves as it is: the contract is what's wrong there, and declaring the key required (product: string) has both say so. (Symfony's handleRequest() leaves it off for a PATCH alone; that isn't read.) A project on the bundled processor turns it on: off is the default only so that no project's tools change when it updates. A key typed with an alias that admits null takes null as T|null does, and so does ?Alias of one: its TypeScript is key?: Alias. A blank a field's transformer fails is refused, as the form is then invalid. An expanded choice is no embedded form: Symfony reads the value sent itself, so it takes null where its contract does — and a collection of them is a list of values, not of objects of their buttons. An embedded form never takes null as a whole: Symfony submits its fields, and a null sent for it clears each one — unless it also takes a record's id (string|array{…}|null), which its form reads before submit: its null is the "none" it declares, submitting none of its fields, so only what the field itself is held to refuses it. A query key never takes null — a query string can't carry one — so a query key that may be null (product: string|null), at any depth, is one a caller may leave out: in the tool's required, and in the Endpoint's query, which is AsQuery<T> of the form's type, whose list items are never null either — T itself, the shape a body or a response may share, says product: string | null. A key valued ?T (product: ?string) may be left out, in the TypeScript, the tool's required and an Endpoint's query alike, and so may a query key typed mixed, whose TypeScript unknown admits null. A key a query or a body inherits through an intersection (Base & array{…}) is read where its base declares it, in the tool as in the Endpoint — and a key both declare is what the intersection makes it, as TypeScript reads Base & {…}: required where either side requires it, taking null only where both allow it, at every level an input extends. The Endpoint and the tool read that one set of keys. A nested key, an embedded form's field or a compound entry's, is required as its contract says, as one at the top is; and a collection's entries are the scalar the contract declares them (list<bool>), as a field is.
A key typed with a class — named as PHP resolves it where it is written, so Input\AddressData from the file's namespace or through a use — is what the class is sent as, as its TypeScript finds it: its _self — its own or one it imports, else its nearest parent's or interface's, never one kept for PHPStan alone — (address?: AddressData, phones?: list<PhoneData>), read where it is declared — an enum's too, which declaring one is sent as that shape — or, for an enum that declares none, its values, but for one a project's emitter publishes a type for, which the tool can't say — an embedded form and a collection's entries are held to those keys. Left out, a required embedded form is what Symfony makes of it — a new object of its data class, which a NotNull takes — and one that isn't is null, as is one a form not required holds, at any depth, whatever its own required says (a filter form's 'required' => false, or a collection's entry_options); one with no data class is the array its fields are written into. Its fields are each submitted blank in turn, so one refusing that makes the form one a POST can't go without: a field's own constraints option always holds, and its property's only where Symfony validates the object it is on — the root's data, and an embedded object only where its property cascades (#[Assert\Valid], or its class's #[Assert\Cascade], as the validator's own metadata says) or its form's own constraints hold a Valid — a collection entry's through its entry_options — which cascades wherever the form is submitted. The same goes for a value sent: an embedded object's own constraints bound it only where they are validated. An alias or a class is read once a contract, whatever names it — one naming itself, cut short there, included — and read back wherever none of what it read through is being read; each contract reads afresh, so whether it is read within the bound turns on it alone. Classes naming one another are read once for each set of them being read where one is named — a read cut short where it named one further out is kept for wherever that one is being read again — not once for every order of them; past a bound no real contract nears (a thousand reads a contract) the read fails, naming the input, rather than leave a key unread, which would publish a tool saying less than its Endpoint: a body's fails its tool's manifest, as only the tool reads a body's keys, and a query's the run, as its Endpoint reads them too. A field its type reads whole — a compound with no fields, or a collection's entries — is the shape its data class or its list declares: an enum's values for value-of<E>, a class's constants' for self::STATUS_*, as the TypeScript reads them — as a field, or a list's entries, declared as literals of one type, written out or an alias of them, takes them — a project-wide alias's where its TypeScript says one — string, number or boolean, literals of them ('en' | 'fr' an enum), a union of those, a | null left to the key — an object where a part of it can't be said. A map every int may key — array<int, V>, array<float, V>, array<array-key, V>, array<int|string, V>, array<int|'total', V>, a project-wide alias's whose TypeScript is a number or every key, iterable<V> — takes a list as well as an object (anyOf), as the array a JSON list decodes to, keyed 0..n, is one. A key of literals, or an enum's values, takes only some of those ints, if any, and its TypeScript is a Record of them, which no list is: it takes an object. Its key is read through the data class's aliases, as a value is; one named by something the builder can't read here may be an int, so it takes a list too. An argument goes to one place, as the manifest tells a client to send it, whatever the method: the path where it names a path param, the query string where the tool lists it in query, the body otherwise. So it takes what that place takes, and a field of the name another place takes is never sent: it is left out of the tool, and generation fails, naming both, where the server refuses that field left out — no call could succeed. One only its contract requires (a PUT body's id: string beside {id}, with nothing refusing it missing) is left to the argument the other place takes.
A field's Length, Range, Count and comparisons with a number bound it in the tool's schema (minLength, maximum, minItems, …), the tighter of two on one side; one read off another property, or a length counted in anything but characters, is left out. A minimum length on a field whose blank the server takes lets the blank through too, as the Length does the null it is submitted as: anyOf: [{maxLength: 0}, {minLength: 3}]. One whose blank the server refuses takes at least one character, as "" is submitted as that blank — unless its pattern refuses "" already, or its value is one of a list — and so does a collection's entry; a list whose blank [] is refused (a NotBlank on a collection or a multiple choice) takes at least one item. A collection's entry is an object only where its type is a form of fields; a file input or a scalar type with a data class is the value it reads.
Patterns in a tool's schema
A string argument publishes a pattern from its route requirement or its one Regex constraint — beside its others, or in a Sequentially or a Compound; with another anywhere, an AtLeastOneOf's or a When's alternatives included, it has none — only where JSON Schema's dialect — ECMA-262 in Unicode mode, as Ajv compiles it — accepts exactly the values the server does; otherwise it has none. The fragment is read against a grammar both dialects agree on (ASCII literals, \d \w \b, classes of literal ranges, plain and (?: groups, quantifiers with counts PCRE compiles — 65535 at most; no dot, \s or \v), under PCRE's mode: byte by byte without u (no negated class, \D, \W), Unicode with it, and both when a route leaves utf8 to the router's default. Read as Unicode, PHP's \d and \w take more than ECMA's ASCII ones: they are published as those ASCII sets, [0-9] and [A-Za-z0-9_], which take fewer, so a value a client sends is never one the server refuses — except in a negated class, where fewer refused is more taken, which has none; \D \W \b \B have none either. The requirement and utf8 are read from the route the router serves when the routing config is loaded, since an import's requirements and utf8 override the attribute's. A Regex carries over only as a whole-value rule (/^…$/, flags D and u at most, no normaliser) on a value the form does not transform — a model transformer, a view transformer other than TextType's own, or a listener that rewrites what was sent before it is validated (UrlType's default_protocol, a project's own) — the field's own, or one of a form holding it, which may rewrite any of its fields — hands the rule something other than what was sent; a type extension the application registers isn't loaded, so its listeners aren't seen — with what reaches it: on a trimmed field (trim, Symfony's default) the rule on the trimmed value — refusing padding the server would take off, rather than allowing it with \p{…}, which only Unicode-mode regex reads, so every pattern compiles in plain JavaScript and Python too; a blank value, unless what it reaches validation as — null, or '' where empty_data is '' — is refused, as above — and where it is refused though the rule matches it (^[A-Z]*$ under a NotBlank), refused by a minLength of 1 beside the pattern, not a lookahead, which RE2 and JSON Schema's interoperable subset don't read; and PCRE's $ before a final newline when untrimmed and without D. An escaped delimiter is read as PCRE reads it: #~!@%;:'"=& and a backtick as the character, any other as written (-[a\-z]- stays a class of three). A requirement holding a %…% placeholder has none.
Forms that nest themselves
A collection whose entries are a form already being read above it — a step's own steps, a section's sections — nests that form. Declare it as any collection, with 'prototype' => false so Symfony builds its entries only as deep as a request goes:
$builder->add('steps', CollectionType::class, ['entry_type' => self::class, 'allow_add' => true, 'prototype' => false]);
The tool's schema describes it to any depth: the form is defined once under the schema's $defs, named for its data class (StepData), and each collection of it is {"type": "array", "items": {"$ref": "#/$defs/StepData"}}. A form embedded whole rather than listed is still written out where it is, and defined beside it for the collections under it to refer to; a body or query form whose own type nests is defined as its fields. A schema with nothing nesting has no $defs. A collection nests a form only where its entries are built exactly as it is — its type, and its options as resolved: a comment whose replies are comments built with with_replies: false is read level by level as it is built, and its replies take no replies of their own.
Testing
vendor/bin/phpunit