PHPackages                             helmich/schema2class - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. helmich/schema2class

ActiveProject[Utility &amp; Helpers](/categories/utility)

helmich/schema2class
====================

Build PHP classes from JSON schema definitions

v3.3.13(9mo ago)36145.8k↑28.2%15[5 issues](https://github.com/martin-helmich/php-schema2class/issues)[6 PRs](https://github.com/martin-helmich/php-schema2class/pulls)MITPHPPHP ^8.2CI passing

Since Apr 15Pushed 2w ago2 watchersCompare

[ Source](https://github.com/martin-helmich/php-schema2class)[ Packagist](https://packagist.org/packages/helmich/schema2class)[ Fund](https://donate.helmich.me)[ GitHub Sponsors](https://github.com/martin-helmich)[ RSS](/packages/helmich-schema2class/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (9)Dependencies (10)Versions (59)Used By (0)

JSONSchema to PHP class converter
=================================

[](#jsonschema-to-php-class-converter)

Build PHP classes from [JSON schemas](http://json-schema.org/) automatically.

Example
-------

[](#example)

Consider a simple JSON schema (ironically stored in YAML format), stored in a file `example.yaml`:

```
required:
  - givenName
  - familyName
properties:
  givenName:
    type: string
  familyName:
    type: string
  hobbies:
    type: array
    items:
      type: string
  location:
    properties:
      country:
        type: string
      city:
        type: string
```

Using this converter, you can automatically generate PHP classes from this schema with accessor and conversion functions:

```
$ vendor/bin/s2c generate:fromschema --class User ./example.yaml src/Target
```

This command will automatically try to infer a PHP target namespace from your `composer.json` file and automatically create the appropriate PHP classes:

```
$ find src/Target
src/Target
src/Target/User.php
src/Target/UserLocation.php
```

Then, use the classes in your code:

```
$userData = json_decode("user.json", true);
$user = \MyNamespace\Target\User::buildFromInput($userData);

echo "Hello, " . $user->getGivenName() . "\n";
```

Compatibility
-------------

[](#compatibility)

This tool requires PHP 8.5 or newer to run.

The generated code can be backwards-compatible up until PHP 5.6. Use the `--target-php` flag to set the desired PHP version that the generated code should be compatible with. When [using a configuration file](#using-configuration-files), use the `targetPHPVersion` property.

Creation result
---------------

[](#creation-result)

The generated classes have these features:

- The class namespace can either be specified via command-line (`--target-namespace`), specification file (`targetNamespace`). If neither is specified, the generator will inspect the `composer.json` of your project, look for any PSR-4 configuration and infer the namespace from there.
- The main object's name is defined by the command-line (`--class`) or the specification file.
- Sub-object's names are taken from the property name.
- Array items are suffixed 'Item'.
- `OneOf` alternatives are suffixed 'AlternativeX', with `X` being an incremented integer.
- The constructor has arguments for all required properties in the schema.
- All properties are private, with getter methods for access, and explicit type declarations for the return value (in PHP5 mode, only PHPDoc is used).
- Static function `buildFromInput(array $data)` accepts an array (using `json_decode('{}', true)`), validates it according to the schema and creates the full object tree as return value. An additional mapping step is not required.
- Function `toJson()` returns a plain array ready for `json_encode()`.
- Writing to any object's properties is done immutably by using `withX()` (or `withoutX()` for optional values). This will return a new instance of that object with the value changed.

As an example, a shortened version with all comments removed, from the above schema shows the location, only containing the city (country is behaving the same, but with a different name)

```
class UserLocation
{
    private static array $schema = array(
        'properties' => array(
            'city' => array(
                'type' => 'string',
            ),
        ),
    );

    private ?string $country = null;

    private ?string $city = null;

    public function __construct()
    {
    }

    public function getCity() : ?string
    {
        return $this->city;
    }

    public function withCity(string $city) : self
    {
        $validator = new \JsonSchema\Validator();
        $validator->validate($city, static::$schema['properties']['city']);
        if (!$validator->isValid()) {
            throw new \InvalidArgumentException($validator->getErrors()[0]['message']);
        }

        $clone = clone $this;
        $clone->city = $city;

        return $clone;
    }

    public function withoutCity() : self
    {
        $clone = clone $this;
        unset($clone->city);

        return $clone;
    }

    public static function buildFromInput(array $input) : UserLocation
    {
        static::validateInput($input);

        $city = null;
        if (isset($input['city'])) {
            $city = $input['city'];
        }

        $obj = new static();
        $obj->city = $city;
        return $obj;
    }

    public function toJson() : array
    {
        $output = [];
        if (isset($this->city)) {
            $output['city'] = $this->city;
        }

        return $output;
    }

    public static function validateInput(array $input, bool $return = false) : bool
    {
        $validator = new \JsonSchema\Validator();
        $validator->validate($input, static::$schema);

        if (!$validator->isValid() && !$return) {
            $errors = array_map(function($e) {
                return $e["property"] . ": " . $e["message"];
            }, $validator->getErrors());
            throw new \InvalidArgumentException(join(", ", $errors));
        }

        return $validator->isValid();
    }

    public function __clone()
    {
    }
}
```

Installation
------------

[](#installation)

Install using Composer:

```
$ composer require --dev helmich/schema2class
```

Using configuration files
-------------------------

[](#using-configuration-files)

In many projects, you're going to want to keep an evolving JSON schema in sync with the generated PHP classes continuously. For this reason, S2C allows you to create a configuration file `.s2c.yaml` that stores the most common conversion options:

```
targetPHPVersion: "7.4"
files:
- input: src/Spec/Spec.yaml
  className: Specification
  targetDirectory: src/Spec
```

You can store your local configuration in this yaml file and start the generation process by calling

```
s2c generate:fromspec
```

This will scan for `.s2c.yaml` in the current directory and use it's parameters. If you need to have different files for multiple schemas, you can provide a config file as a parameter.

###  Health Score

62

—

FairBetter than 99% of packages

Maintenance76

Regular maintenance activity

Popularity45

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity89

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 91.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~91 days

Total

32

Last Release

144d ago

Major Versions

v1.0.1 → v2.0.02019-12-23

v2.1.3 → v3.0.02023-09-04

v3.3.13 → v4.0.0-beta12026-01-16

PHP version history (5 changes)v1.0.1PHP ^5.6|^7.0

v2.0.0PHP ^7.4

v2.1.0PHP ^7.4|^8.0

v3.0.0PHP ^8.2

v4.0.0-beta1PHP ^8.5

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/38724147?v=4)[helmich](/maintainers/helmich)[@helmich](https://github.com/helmich)

---

Top Contributors

[![martin-helmich](https://avatars.githubusercontent.com/u/2538958?v=4)](https://github.com/martin-helmich "martin-helmich (225 commits)")[![SvenRtbg](https://avatars.githubusercontent.com/u/416600?v=4)](https://github.com/SvenRtbg "SvenRtbg (8 commits)")[![simivar](https://avatars.githubusercontent.com/u/828020?v=4)](https://github.com/simivar "simivar (4 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (3 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (2 commits)")[![HankieCodes](https://avatars.githubusercontent.com/u/3521186?v=4)](https://github.com/HankieCodes "HankieCodes (1 commits)")[![dominiquegerber](https://avatars.githubusercontent.com/u/18481454?v=4)](https://github.com/dominiquegerber "dominiquegerber (1 commits)")[![andrew-demb](https://avatars.githubusercontent.com/u/12499813?v=4)](https://github.com/andrew-demb "andrew-demb (1 commits)")[![stevenlafl](https://avatars.githubusercontent.com/u/2539092?v=4)](https://github.com/stevenlafl "stevenlafl (1 commits)")

---

Tags

code-generationcode-generatorjson-schemaphp

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/helmich-schema2class/health.svg)

```
[![Health](https://phpackages.com/badges/helmich-schema2class/health.svg)](https://phpackages.com/packages/helmich-schema2class)
```

###  Alternatives

[composer/composer

Composer helps you declare, manage and install dependencies of PHP projects. It ensures you have the right stack everywhere.

29.4k193.1M3.0k](/packages/composer-composer)[matomo/matomo

Matomo is the leading Free/Libre open analytics platform

21.6k38.2k](/packages/matomo-matomo)[drupal/core

Drupal is an open source content management platform powering millions of websites and applications.

21764.8M1.6k](/packages/drupal-core)[friendsoftypo3/content-blocks

TYPO3 CMS Content Blocks - Content Types API | Define reusable components via YAML

101466.4k44](/packages/friendsoftypo3-content-blocks)[drupal/core-recommended

Locked core dependencies; require this project INSTEAD OF drupal/core.

6941.5M395](/packages/drupal-core-recommended)[kimai/kimai

Kimai - Time Tracking

4.7k8.7k1](/packages/kimai-kimai)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
