Download the PHP package futuretek/openapi-gen-server-yii2 without Composer
On this page you can find all versions of the php package futuretek/openapi-gen-server-yii2. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download futuretek/openapi-gen-server-yii2
More information about futuretek/openapi-gen-server-yii2
Files in futuretek/openapi-gen-server-yii2
Package openapi-gen-server-yii2
Short Description OpenAPI server stub generator for Yii2
License MIT
Informations about the package openapi-gen-server-yii2
PHP OpenAPI Server Generator
A code generator that transforms an OpenAPI 3.0.x specification into a fully typed PHP server implementation for Yii2, with automatic request/response handling, body deserialization, and middleware support.
Key Features
- Schema DTOs — Generates typed data classes with
futuretek/data-mapperattributes (#[ArrayType],#[MapType],#[Format]) and fluent setters for every property - Backed Enums — PHP 8.4 string/int backed enums from OpenAPI enums, with
x-enum-descriptionssupport - Controller Interfaces & Abstract Controllers — Generated into a
contractsnamespace (notcontrollers) to avoid conflicts with the Yii2 default controller namespace where your implementations live - Yii2 Route File — Ready-to-use URL rules with type-based regex constraints (
\d+for int/float,[^/]+for string, always scoped to a single path segment) - Ambiguous Route Detection — Warns when a parametric route would shadow a static route in Yii2's ordered URL matching, including cases where the routes have a different number of path segments
- File Upload Handling — Single files and file arrays (
format: binary) mapped to PSR-7UploadedFileInterface, with a built-inPsr7Streamimplementation forgetStream() - Binary/Plain Response Types —
application/octet-streamresponses returnUploadedFileInterface,text/plainreturnsstring— no spurious DTO classes generated - Array Request Bodies — Typed array body parameters (
arrayof DTOs) with@param ItemClass[]PHPDoc andbodyIsArray+bodyItemClassinoperationMeta - Route Prefix — Optional
routePrefixfor module-style routes (e.g.api/pet/list-pets) - Discriminator Mapping — Polymorphic body deserialization via
oneOf/anyOfwith discriminator - Pluggable Middleware — Authentication, authorization, logging, and file handling with sensible defaults
- Namespace = Directory — Files are placed according to their namespace, following Yii2 conventions
- Strict Mode —
--strictflag treats warnings as errors (non-zero exit), suitable for CI pipelines
Requirements
- PHP ≥ 8.4
- Composer
Installation
Quick Start
1. Generate code from your OpenAPI spec
This uses defaults: --base-dir=., --namespace=app\api, route file at config/routes.api.php.
2. With custom namespaces
The --route-prefix option prepends a prefix to route targets, useful for Yii2 module-style routing (e.g. api/pet/list-pets instead of pet/list-pets).
3. Implement the generated interfaces
4. Include the generated routes
Directory Layout
Generated files follow the Yii2 namespace = directory convention. The --base-dir points to your application root (@app), and namespaces are converted to directory paths by stripping the first segment (e.g. app).
The first namespace segment (app) maps to --base-dir. Remaining segments become subdirectories:
| Namespace | Directory (relative to base-dir) |
|---|---|
app\api\schemas |
api/schemas/ |
app\modules\api\schemas |
modules/api/schemas/ |
app\modules\v2\api\schemas |
modules/v2/api/schemas/ |
How It Works
Request Flow
- Yii2 routes the request to your controller action
AbstractApiController::bindActionParams()intercepts parameter binding:- Deserializes the request body (JSON / multipart) into the typed DTO
- Extracts path, query, header, and cookie parameters with type casting
- Resolves enum parameters via
::tryFrom() - Handles discriminator mapping for polymorphic bodies
- Your action receives fully typed parameters and returns a DTO
AbstractApiController::afterAction()serializes the response to JSON (or streams raw bytes forUploadedFileInterfacereturns)
Body Handling
- JSON — Parsed from raw body, mapped to DTO via DataMapper
- Multipart — Form fields + file uploads, with
UploadedFileInterface(PSR-7) for files - Discriminator — Reads the discriminator property, resolves the concrete subclass, then deserializes
Response Handling
- DTO — Serialized to JSON array via DataMapper
UploadedFileInterface— Response is streamed as raw binary (application/octet-stream), withContent-DispositionandContent-Lengthheaders set automaticallystring— Returned as-is (e.g. fortext/plainresponses)void— No response body; Yii2 format is not changed
File Upload Handling
File properties (type: string, format: binary) are converted to PSR-7 UploadedFileInterface instances. Both single files and arrays of files are supported:
Generated schemas use the correct types and attributes:
The built-in Psr7UploadedFile and Psr7Stream classes provide a complete PSR-7 implementation. Use getStream() to read file contents:
Binary / Plain Response Types
Non-JSON response content types are mapped to simple PHP types — no DTO class is generated:
| Content-Type | format |
Return type |
|---|---|---|
application/octet-stream |
binary / byte |
UploadedFileInterface |
text/plain |
any | string |
application/json |
— | Generated DTO class |
Array Request Bodies
When a request body is an array of DTOs, the generator creates the correct parameter signature:
Schema Setters
Every generated DTO class includes a fluent setter for each property, allowing builder-style construction:
Setters accept ?Type for optional/nullable properties and Type for required ones. They return static for subclass compatibility.
Security
Security schemes are captured in operationMeta. The abstract controller calls AuthenticationInterface and AuthorizationInterface middleware in beforeAction(). Default implementations pass through — override the factory methods to plug in your auth:
Route Prefix
When using Yii2 modules, route targets need a prefix matching the module ID. Use --route-prefix (or Config::$routePrefix) to prepend it:
Route Regex Constraints
Path parameters in generated URL rules include a type-based regex constraint so Yii2 can distinguish them from static segments. Every constraint is scoped to a single path segment (it never matches /), so a parametric route can't accidentally swallow a deeper route's extra segments:
| Parameter type | Regex | Example rule |
|---|---|---|
integer / number |
\d+ |
GET items/<id:\d+> |
string and all others |
[^/]+ |
GET items/<slug:[^/]+> |
Ambiguous Route Detection
The generator warns when a parametric route is listed before a static route it would shadow for the same HTTP method — either because they sit at the same depth and the parametric segment matches the static one, or because a shorter parametric route's trailing segment could otherwise consume a longer, more specific route's extra segments. In this situation Yii2 evaluates the parametric rule first and the static rule is never reached.
Fix options:
- Reorder: put static routes before parametric ones in the spec
- Type-constrain: declare the path parameter as
type: integerto use\d+(which won't matchcreate)
CLI Options
Output Order
The generator always outputs in this order:
- Errors — fatal problems that prevented generation (exit code 1)
- Generated files — list of all written
.phpfiles - Warnings — non-fatal issues displayed last so they are easy to spot
With --strict, any warnings also cause a non-zero exit code after being displayed — useful for enforcing clean specs in CI.
Spec Quality Checks
The generator performs several spec quality checks during parsing and emits warnings for:
| Issue | Warning |
|---|---|
Duplicate operationId |
Duplicate operationId 'X' at METHOD /path |
type: object schema with no properties and no allOf |
Schema 'X' is declared as type:object but has no properties — likely a spec error |
Inline enum missing x-enum name |
Inline enum on property 'X' has no x-enum name |
| Parametric route shadowing a static route (same or differing depth) | Ambiguous routes: METHOD /a will shadow METHOD /b |
Empty object schemas (no properties, no allOf) are skipped — no PHP file is generated. This catches the common mistake of using type: object for responses that should be a scalar type (string, integer, etc.).
Use --strict to turn any of these warnings into a build failure.
Vendor Extensions
| Extension | Level | Description |
|---|---|---|
x-controller |
path / operation | Override the controller name |
x-enum |
inline enum schema | Name override for inline enums (warns if missing) |
x-enum-descriptions |
enum schema | Array of per-value descriptions, aligned with enum values |
Example
Schema Generation Details
Type Mapping
| OpenAPI Type | PHP Type |
|---|---|
string |
string |
integer |
int |
number |
float |
boolean |
bool |
string + format: date |
DateTimeInterface |
string + format: date-time |
DateTimeInterface |
string + format: binary |
UploadedFileInterface |
array + items: {type: string, format: binary} |
array with #[ArrayType(UploadedFileInterface::class)] + @var UploadedFileInterface[] |
array + items |
array with #[ArrayType] + @var T[] PHPDoc |
object + additionalProperties |
object with #[MapType] |
enum |
PHP backed enum |
allOf |
Class inheritance (extends) |
oneOf / anyOf |
Union types (A\|B) |
PHPDoc Annotations
Array and map properties are annotated with @var for IDE autocompletion:
Controller Interface Conventions
- Body first — Request body is always the first parameter
- Array bodies — When the request body is
type: array, the parameter isarray $bodywith@param ItemClass[]PHPDoc - Then path params — Required path parameters
- Then query/header/cookie — Required first, then optional with defaults
- Return type — Success response DTO,
arrayfor array responses,UploadedFileInterfacefor binary downloads,stringfor plain text,voidfor no-content - Hyphenated names — Converted to camelCase (
X-Request-Id→$xRequestId)
Discriminator Support
Both explicit and auto-derived discriminator mappings are supported:
At runtime, the abstract controller reads the discriminator property from the raw JSON and deserializes into the correct concrete class.
Development
Running Tests
Project Structure
License
MIT License. See LICENSE for details.
All versions of openapi-gen-server-yii2 with dependencies
futuretek/data-mapper Version ^1.3.0
cebe/php-openapi Version ^1.8.0
symfony/console Version ^7.0
psr/http-message Version ^1.0 || ^2.0