Search by

msstc4php / dto-generator

maxim.shamaev@gmail.com

Generates immutable or mutable PHP DTO classes from OpenAPI 3.0–3.2 and Swagger 2.0 schemas, tailored to the target PHP version.

Package info

github.com/msstc4php/dto-generator

Type:composer-plugin

pkg:composer/msstc4php/dto-generator

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 0

v1.18.1 2026-11-27 11:23 UTC

README

Build Status PHP Version Generated code PHPStan Last commit License: MIT

Generates PHP DTO classes from the components/schemas of an OpenAPI 3.0, 3.1 or 3.2 document (or the definitions of a Swagger 2.0 one), written for the PHP version your project runs on — from 7.4 to 8.5.

Point it at a YAML or JSON spec and it writes one class per schema: typed constructor, immutable with*() methods or setters, PHP enums (or constant classes before 8.1), precise PHPStan types in PHPDoc, and attributes or Doctrine annotations from extensions. The output is deterministic and committed with your code; a --check run in CI tells you when it is out of date.

Features

  • Target-aware code. The same spec gives final readonly class with promoted properties on PHP 8.2, getters and clone-based withers on 7.4, and the shapes in between. target.php: auto reads the version from your composer.json.
  • Immutable or mutable DTOs, per project or per schema; getters or public properties.
  • Read and write models for readOnly/writeOnly on request: PetRead without the write-only properties, PetWrite without the read-only ones, per project or per schema; classes that do not depend on them stay shared.
  • OpenAPI 3.1 and 3.2 / JSON Schema 2020-12: objects, arrays, maps (additionalProperties), enums, nullable types, defaults, format, internal and cross-file $ref (recursive types included), allOf as inheritance or merge, oneOf/anyOf with a discriminator (abstract base class) or as a union type, inline property schemas lifted into named classes.
  • Collection objects instead of arrays on request: TagList $tags or ArrayCollection<int, Tag>, with #[TypedCollection] on the item classes for dto-collection-generator — see dto.collections.
  • Precise PHPDoc — list<T>, array<array-key, T>, non-empty-string, int<1, 100>, Status::* — in @phpstan-* tags, with portable @var/@param tags for other readers.
  • x- keywords to rename classes and properties, map to your own types, skip schemas and add arbitrary attributes — see docs/x-extensions.md.
  • Extensions add attributes and formats through a small SPI; the Symfony bridge writes Validator constraints and Serializer attributes.
  • Remote $refs to the URLs you allow, fetched once into a cache you can commit.
  • Safe writes: a manifest per output directory, deletion of classes whose schemas are gone, and no overwriting of files the generator did not write.
  • Three ways to run: the CLI, a Composer plugin that regenerates after composer install/update, and a Docker image.

Requirements

  • PHP >= 7.4 to run the generator (any version from 7.4 to 8.5 can be the target).
  • Composer 2.
  • symfony/console (^5.4.47), symfony/yaml (^5.4.52) — or 6.4, 7.x, 8.x of both; nikic/php-parser ^5.1.

Installation

The package is not on Packagist yet, so register its GitHub repository first:

composer config repositories.msstc4php-dto-generator vcs https://github.com/msstc4php/dto-generator
composer require --dev msstc4php/dto-generator

Install it as a dev dependency: the generated classes are plain PHP and need nothing at runtime. Composer asks whether to trust the plugin; answer yes to get regeneration on install, or no to use only the CLI.

Quick start

Create dto-generator.yaml next to composer.json (paths are relative to the config file):

version: 1
target:
  php: auto            # the lowest version allowed by require.php in composer.json; 7.4 without one
sources:
  - spec: openapi/api.yaml
    namespace: App\Dto
    outputDir: src/Dto

Given this schema:

components:
  schemas:
    Customer:
      description: A customer of the shop.
      type: object
      required: [id, email]
      properties:
        id: {type: string, format: uuid}
        email: {type: string, format: email, maxLength: 254}
        first_name: {type: string, minLength: 1}
        status: {type: string, enum: [active, blocked], default: active}
        registered_at: {type: string, format: date-time}

vendor/bin/dto-generator generate writes src/Dto/Customer.php and src/Dto/CustomerStatus.php. For PHP 8.2:

<?php

// @generated by msstc4php/dto-generator — DO NOT EDIT

declare(strict_types=1);

namespace App\Dto;

/**
 * A customer of the shop.
 */
final readonly class Customer
{
    public function __construct(
        public string $id,
        public string $email,
        /**
         * @phpstan-var ?non-empty-string
         */
        public ?string $firstName = null,
        public ?CustomerStatus $status = CustomerStatus::ACTIVE,
        public ?\DateTimeImmutable $registeredAt = null,
    ) {
    }

    public function withId(string $id): self
    {
        return new self($id, $this->email, $this->firstName, $this->status, $this->registeredAt);
    }

    // withEmail(), withFirstName(), withStatus(), withRegisteredAt()
}
enum CustomerStatus: string
{
    case ACTIVE = 'active';

    case BLOCKED = 'blocked';
}

With target.php: '7.4' the same schema becomes a final class with private typed properties, getX() and clone-based withX() methods, and CustomerStatus becomes a class of constants (@phpstan-var CustomerStatus::*).

Commit the generated files together with .dto-generator.manifest.json in each output directory.

Usage

CLI

vendor/bin/dto-generator generate                       # write the classes
vendor/bin/dto-generator generate --check               # write nothing; exit 1 when the output is out of date (CI)
vendor/bin/dto-generator generate --dry-run             # write nothing; show what would change
vendor/bin/dto-generator generate --format=json         # machine-readable report on stdout
vendor/bin/dto-generator generate --output-root=var/dto # every outputDir under var/dto, at its path relative to the config
vendor/bin/dto-generator generate --refresh-remote      # fetch every remote document the run reads again
vendor/bin/dto-generator generate --config=api/dto.yaml # default: dto-generator.yaml, then dto-generator.json
Exit code Meaning
0 Success; with --check, the output is up to date
1 --check: the output is out of date
2 Errors in the schemas, a conflict with an existing file, a write that failed, or an unexpected failure (a PHP fatal error included; 255 on PHP 7.4, and 1 when some Linux builds of PHP 7.4–8.1 run out of memory, as they end before any shutdown function)
3 An invalid config or invalid options

Every error is reported at once, on stderr, with its place in the schema:

error openapi/api.yaml#/components/schemas/Customer/properties/status/enum: The enum mixes strings and integers, which no PHP enum can back.
Generation failed: 1 error(s).

A warning that recurs word for word (an unknown format on hundreds of properties) is shown once, at its first place, with how many more there are; -v lists every place. The JSON report always lists every one.

When the config or a schema has errors, or a file conflicts, nothing is written. If a write fails halfway (permissions, a full disk), the files already written stay; the next run brings the output to the expected state.

--format=json prints {"status": …, "diagnostics": [{severity, location, message}], "changes": [{kind, path}]}, where status is ok, out-of-date, generation-failed or config-failed and kind is create, update or delete. changes lists only the files that change, the manifests included.

The CLI raises a memory_limit below 1G to 1G; set DTO_GENERATOR_MEMORY_LIMIT=512M (or any other limit) to choose another one.

Composer plugin

After every composer install, update and dump-autoload the plugin regenerates the DTOs, if the project's composer.json names the config:

{
    "config": {"allow-plugins": {"msstc4php/dto-generator": true}},
    "extra": {"dto-generator": {"config": "dto-generator.yaml", "failOnError": false}}
}

The plugin runs vendor/bin/dto-generator in its own process, so the result is the CLI's. Generation errors are printed as warnings and do not fail the Composer command, unless failOnError is true. --no-plugins and --no-scripts turn the plugin off. Keep the generator in require-dev, or a composer install --no-dev on deploy would run it too.

PHP API

use MSSTC4PHP\DtoGenerator\Application\Service\Generate\Input;
use MSSTC4PHP\DtoGenerator\Application\Service\Generate\Mode;
use MSSTC4PHP\DtoGenerator\DtoGenerator;

// The config path must be absolute.
$output = DtoGenerator::generator()(new Input('/path/to/dto-generator.yaml', Mode::from(Mode::WRITE)));
$output->status()->value();   // ok | out-of-date | generation-failed | config-failed
$output->diagnostics()->all();

Mode::CHECK and Mode::DRY_RUN match --check and --dry-run; $input->withRefreshedRemote() matches --refresh-remote.

To build the DTOs somewhere the project's sources never see, such as a framework's build directory, move every output directory under one root and keep the network out of the build:

$output = DtoGenerator::generator()(
    (new Input($config, Mode::from(Mode::WRITE)))
        ->withOutputRoot('/app/var/build/dto')   // src/Dto in the config's directory becomes /app/var/build/dto/src/Dto
        ->withoutFetching(),                     // remote documents from remoteRefs.cacheDir only
);
$output->classes();     // fully qualified class name => file, for an autoloader
$output->documents();   // the config and every local document the run read
$output->remoteCache(); // remoteRefs.cacheDir when remote documents were read, else null

An output directory outside the config's directory cannot move, nor can one hold the root: both are config errors. Paths are compared as written, so reach the config by the same path as its output directories (no symbolic link in between).

For a console command that wraps the generator, DtoGenerator::guard($input, $output, $run) maps exceptions to the CLI's exit codes (3 for invalid options, 2 otherwise); the Symfony bundle uses it. Call DtoGenerator::prepareProcess($output) first to give the command the CLI's process settings: memory_limit (raised to at least 1G, or DTO_GENERATOR_MEMORY_LIMIT), errors on stderr and exit code 2 on a PHP fatal error. It changes the whole process, so call it only from a one-off command.

Docker

The image runs the generator on a mounted project, with the Symfony bridge installed:

docker run --rm -u "$(id -u):$(id -g)" -v "$PWD:/app" ghcr.io/msstc4php/dto-generator:1 --config=dto-generator.yaml [--check]

Every release is published for linux/amd64 and linux/arm64 as ghcr.io/msstc4php/dto-generator:X.Y.Z; X.Y, X and latest follow the newest release of their line. To build the image yourself: docker build -f docker/Dockerfile -t dto-generator .

Pass the environment variables that remoteRefs.headers names and any proxy variables with -e (-e GITLAB_TOKEN -e https_proxy). The container does not run your project's code: verifyClasses: auto is off in it (DTO_GENERATOR_VERIFY_CLASSES=0); only an explicit verifyClasses: true loads the project's autoloader. Only the extensions installed in the image are available. target.php: auto and the bridge's Symfony versions are read from the mounted composer.json and composer.lock. Build arguments: VERSION (the generator version the image reports to Composer, 1.18.0 by default; the bridge 1.5 requires at least 1.6.0), BRIDGE_REPOSITORY and BRIDGE_VERSION (where the bridge comes from, ^1.0 by default). make docker-build builds dto-generator:local with the latest tag as VERSION and the sibling bridge checkout, if there is one.

How the output is managed

  • Each outputDir holds .dto-generator.manifest.json, the list of generated files with their hashes. Commit it.
  • A class whose schema was removed is deleted, but only when the file still starts with the @generated header and its content matches the manifest.
  • A file is overwritten only when it starts with the @generated header (right after <?php).
  • Anything else is a conflict: a stale file edited by hand, a file without the header where a class goes, an unreadable file, two classes in one file. A conflict is an error (exit 2) and nothing is written until you move or delete the file.
  • A corrupt manifest stops the run instead of guessing.
  • Unchanged files are not touched. Generated files always use LF; --check accepts a CRLF checkout (git core.autocrlf), but <outputDir>/** text eol=lf in .gitattributes keeps them stable.
  • Runs on the same outputDir wait for each other (a lock file in the system temporary directory).

Documentation

Development

make install       # package and tool (tools/) dependencies
make check         # composer audit, PHPStan, CS-Fixer, Rector, deptrac, PHP 7.4 lint
make test          # PHPUnit on the local PHP
make test-74       # PHPUnit in php:7.4-cli (Docker)
make test-targets  # the generated code: php -l, a smoke run and PHPStan max on php:7.4 … 8.5-cli (Docker)
make bc-check      # compare the public API with the latest release (Roave)
make infection     # mutation testing
make docker-smoke  # build the image and generate the golden project with it
make fix           # apply Rector and CS-Fixer

Running the generator needs only PHP 7.4; developing it needs PHP 8.x and Docker.

Security

See SECURITY.md.

License

MIT, see LICENSE.