helmich / schema2class
Build PHP classes from JSON schema definitions
Fund package maintenance!
martin-helmich
donate.helmich.me
Installs: 95 810
Dependents: 0
Suggesters: 0
Security: 0
Stars: 30
Watchers: 4
Forks: 14
Open Issues: 8
Type:project
Requires
- php: ^8.2
- ext-json: *
- composer/semver: ^3.0
- justinrainbow/json-schema: ^6.0
- laminas/laminas-code: ^4.12
- symfony/console: ~3.0|~4.0|~5.0|~6.0|~7.0
- symfony/yaml: ~3.0|~4.0|~5.0|~6.0|~7.0
Requires (Dev)
- phpspec/prophecy: ^1.17
- phpspec/prophecy-phpunit: ^2.0
- phpunit/phpunit: ^10.5
- vimeo/psalm: ^5.26
- dev-master
- v3.3.6
- v3.3.5
- v3.3.4
- v3.3.3
- v3.3.2
- v3.3.1
- v3.3.0
- v3.2.0
- v3.1.3
- v3.1.2
- v3.1.1
- v3.1.0
- v3.0.1
- v3.0.0
- v2.1.3
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.3
- v2.0.2
- v2.0.1
- v2.0.0
- v1.0.1
- v1.0.0
- dev-bugfix/fix-default-enums
- dev-bugfix/fix-naming-props-w-default
- dev-bugfix/capitalize-names-correctly
- dev-bugfix/duplicate-property-names
- dev-refact/cleanup-2024
- dev-dependabot/composer/phpunit/phpunit-tw-11.2
- dev-feature-custom-validator
- dev-feature/custom-validator
- dev-task/bump-deps
- dev-bugfix-enum-case-int-prefix
- dev-default-as-optional
- dev-feature/dynamic-objects
This package is auto-updated.
Last update: 2024-11-13 09:55:55 UTC
README
Build PHP classes from JSON schemas automatically.
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
This tool requires PHP 8.2 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, use the targetPHPVersion
property.
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 thecomposer.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', withX
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 (usingjson_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 forjson_encode()
. - Writing to any object's properties is done immutably by using
withX()
(orwithoutX()
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
Install using Composer:
$ composer require --dev helmich/schema2class
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.