{"id":15524764,"url":"https://github.com/martin-helmich/php-schema2class","last_synced_at":"2025-04-05T03:09:35.019Z","repository":{"id":47313086,"uuid":"129610945","full_name":"martin-helmich/php-schema2class","owner":"martin-helmich","description":"Generate PHP classes from JSON schemas","archived":false,"fork":false,"pushed_at":"2025-01-22T09:15:51.000Z","size":433,"stargazers_count":33,"open_issues_count":9,"forks_count":15,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-03-29T02:06:11.200Z","etag":null,"topics":["code-generation","code-generator","json-schema","php"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/martin-helmich.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-04-15T13:06:44.000Z","updated_at":"2025-03-26T22:13:53.000Z","dependencies_parsed_at":"2023-12-22T13:27:18.921Z","dependency_job_id":"5e3fecb0-f45e-479d-9718-c151384d90a9","html_url":"https://github.com/martin-helmich/php-schema2class","commit_stats":{"total_commits":44,"total_committers":6,"mean_commits":7.333333333333333,"dds":"0.31818181818181823","last_synced_commit":"6584bab79e0a367f4188a57488debc372d850d2f"},"previous_names":[],"tags_count":28,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martin-helmich%2Fphp-schema2class","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martin-helmich%2Fphp-schema2class/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martin-helmich%2Fphp-schema2class/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/martin-helmich%2Fphp-schema2class/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/martin-helmich","download_url":"https://codeload.github.com/martin-helmich/php-schema2class/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247280272,"owners_count":20912967,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["code-generation","code-generator","json-schema","php"],"created_at":"2024-10-02T10:53:04.745Z","updated_at":"2025-04-05T03:09:35.000Z","avatar_url":"https://github.com/martin-helmich.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# JSONSchema to PHP class converter\n\nBuild PHP classes from [JSON schemas][jsonschema] automatically.\n\n## Example\n\nConsider a simple JSON schema (ironically stored in YAML format), stored in a file `example.yaml`:\n\n```yaml\nrequired:\n  - givenName\n  - familyName\nproperties:\n  givenName:\n    type: string\n  familyName:\n    type: string\n  hobbies:\n    type: array\n    items:\n      type: string\n  location:\n    properties:\n      country:\n        type: string\n      city:\n        type: string \n```\n\nUsing this converter, you can automatically generate PHP classes from this schema\nwith accessor and conversion functions:\n\n```bash\n$ vendor/bin/s2c generate:fromschema --class User ./example.yaml src/Target\n```\n\nThis command will automatically try to infer a PHP target namespace from your `composer.json` file and automatically create the appropriate PHP classes:\n\n```bash\n$ find src/Target\nsrc/Target\nsrc/Target/User.php\nsrc/Target/UserLocation.php\n```\n\nThen, use the classes in your code:\n\n```php\n$userData = json_decode(\"user.json\", true);\n$user = \\MyNamespace\\Target\\User::buildFromInput($userData);\n\necho \"Hello, \" . $user-\u003egetGivenName() . \"\\n\";\n```\n\n## Compatibility\n\nThis tool requires PHP 8.2 or newer to run.\n\nThe 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. \n\n## Creation result\n\nThe generated classes have these features:\n\n- 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.\n- The main object's name is defined by the command-line (`--class`) or the specification file.\n- Sub-object's names are taken from the property name.\n- Array items are suffixed 'Item'.\n- `OneOf` alternatives are suffixed 'AlternativeX', with `X` being an incremented integer.\n- The constructor has arguments for all required properties in the schema.\n- All properties are private, with getter methods for access, and explicit type declarations for the return value (in PHP5 mode, only PHPDoc is used).\n- 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.\n- Function `toJson()` returns a plain array ready for `json_encode()`.\n- 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.\n\nAs 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)\n\n```php\nclass UserLocation\n{\n    private static array $schema = array(\n        'properties' =\u003e array(\n            'city' =\u003e array(\n                'type' =\u003e 'string',\n            ),\n        ),\n    );\n\n    private ?string $country = null;\n\n    private ?string $city = null;\n\n    public function __construct()\n    {\n    }\n\n    public function getCity() : ?string\n    {\n        return $this-\u003ecity;\n    }\n\n    public function withCity(string $city) : self\n    {\n        $validator = new \\JsonSchema\\Validator();\n        $validator-\u003evalidate($city, static::$schema['properties']['city']);\n        if (!$validator-\u003eisValid()) {\n            throw new \\InvalidArgumentException($validator-\u003egetErrors()[0]['message']);\n        }\n\n        $clone = clone $this;\n        $clone-\u003ecity = $city;\n\n        return $clone;\n    }\n\n    public function withoutCity() : self\n    {\n        $clone = clone $this;\n        unset($clone-\u003ecity);\n\n        return $clone;\n    }\n\n    public static function buildFromInput(array $input) : UserLocation\n    {\n        static::validateInput($input);\n\n        $city = null;\n        if (isset($input['city'])) {\n            $city = $input['city'];\n        }\n\n        $obj = new static();\n        $obj-\u003ecity = $city;\n        return $obj;\n    }\n\n    public function toJson() : array\n    {\n        $output = [];\n        if (isset($this-\u003ecity)) {\n            $output['city'] = $this-\u003ecity;\n        }\n\n        return $output;\n    }\n\n    public static function validateInput(array $input, bool $return = false) : bool\n    {\n        $validator = new \\JsonSchema\\Validator();\n        $validator-\u003evalidate($input, static::$schema);\n\n        if (!$validator-\u003eisValid() \u0026\u0026 !$return) {\n            $errors = array_map(function($e) {\n                return $e[\"property\"] . \": \" . $e[\"message\"];\n            }, $validator-\u003egetErrors());\n            throw new \\InvalidArgumentException(join(\", \", $errors));\n        }\n\n        return $validator-\u003eisValid();\n    }\n\n    public function __clone()\n    {\n    }\n}\n```\n\n## Installation\n\nInstall using Composer:\n\n```bash\n$ composer require --dev helmich/schema2class\n```\n\n## Using configuration files\n\nIn 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:\n\n```yaml\ntargetPHPVersion: \"7.4\"\nfiles:\n- input: src/Spec/Spec.yaml\n  className: Specification\n  targetDirectory: src/Spec\n```\n\nYou can store your local configuration in this yaml file and start the generation process by calling\n\n```bash\ns2c generate:fromspec\n```\n\nThis 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.\n\n[jsonschema]: http://json-schema.org/\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmartin-helmich%2Fphp-schema2class","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmartin-helmich%2Fphp-schema2class","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmartin-helmich%2Fphp-schema2class/lists"}