{"id":16750005,"url":"https://github.com/hakobyansen/phpdto","last_synced_at":"2025-03-21T22:32:04.164Z","repository":{"id":56954930,"uuid":"196476890","full_name":"hakobyansen/phpdto","owner":"hakobyansen","description":"CLI tool for PHP Data Transfer Object generation.","archived":false,"fork":false,"pushed_at":"2024-03-23T20:32:17.000Z","size":140,"stargazers_count":2,"open_issues_count":10,"forks_count":1,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-03-18T05:51:10.873Z","etag":null,"topics":["cli","dto","php"],"latest_commit_sha":null,"homepage":"","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/hakobyansen.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":"2019-07-11T23:24:54.000Z","updated_at":"2023-06-06T07:26:58.000Z","dependencies_parsed_at":"2024-03-23T21:29:12.801Z","dependency_job_id":"2b9abd98-5438-4e52-bbc4-5578a8e9a675","html_url":"https://github.com/hakobyansen/phpdto","commit_stats":{"total_commits":98,"total_committers":2,"mean_commits":49.0,"dds":0.08163265306122447,"last_synced_commit":"50c5928922f7252be24f4223b8a75650566ddbcc"},"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakobyansen%2Fphpdto","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakobyansen%2Fphpdto/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakobyansen%2Fphpdto/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hakobyansen%2Fphpdto/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hakobyansen","download_url":"https://codeload.github.com/hakobyansen/phpdto/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244880412,"owners_count":20525507,"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":["cli","dto","php"],"created_at":"2024-10-13T02:26:43.745Z","updated_at":"2025-03-21T22:32:03.792Z","avatar_url":"https://github.com/hakobyansen.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Latest Stable Version](https://poser.pugx.org/codebot/phpdto/v/stable)](https://packagist.org/packages/codebot/phpdto)\n[![Build Status](https://travis-ci.com/c0d3b0t/phpdto.svg?branch=master)](https://travis-ci.com/c0d3b0t/phpdto)\n[![Total Downloads](https://poser.pugx.org/codebot/phpdto/downloads)](https://packagist.org/packages/codebot/phpdto)\n[![License](https://poser.pugx.org/codebot/phpdto/license)](https://packagist.org/packages/codebot/phpdto)\n\n## About\n\n\u003e A CLI tool for PHP Data Transfer Objects generation.\n\nThis utility gives an ability to generate PHP 8 DTO classes based on json pattern.\n\n## Installation\n\nInstall the package via composer:\n\n`composer require --dev codebot/phpdto 0.3.*`\n\n**Please consider that the minimum PHP version required by this package is 8.0.**\n\n## Initialization\n\n`vendor/bin/phpdto init`\n\nThe current working directory is the directory from where you are invoking `phpdto` command.\n\nThis command will initialize the phpdto and create **phpdto.json** configuration file and **phpdto_patterns** directory\nin your current working directory.\n\n## Configuration\n\n**phpdto.json** configuration file contains following variables:\n\n*PHP_DTO_PATTERNS_DIR* - the directory, where you must store json patterns for DTOs.\n\n*PHP_DTO_NAMESPACE* - the namespace of generated DTO classes.\n\n*PHP_DTO_CLASS_POSTFIX* - postfix of DTO classes, e.g. Item (no postfix), ItemDto (the postfix is \"Dto\").\n\n***These variables are stored as environment variables.***\n\n## Usage\n\nTo generate DTO class you must create a pattern, which is a json file that contains information about the generated class.\n\n##### DTO JSON Pattern\n\nAn example of DTO pattern:\n\n```json\n{\n  \"class\": \"item\",\n  \"namespace_postfix\": \"\",\n  \"props\": {\n    \"id\": \"int\",\n    \"count\": \"?int\",\n    \"name\": \"string\",\n    \"description\": \"?string\",\n    \"is_active\": \"bool\"\n  }\n}\n```\n\n**class**\n\nA class name that will be combined with *PHP_DTO_CLASS_POSTFIX* specified in `phpdto.json` config file.\n\nSo, if the class name is `item`, and the class postfix config value is `Dto`, then the generated class name will be `\nItemDto`.\n\n**namespace_postfix**\n\nA postfix of the generated DTO class namespace that will be combined with *PHP_DTO_NAMESPACE* specified in `phpdto.json`\nconfig file.\n\nSo, if the namespace postfix is `\\User`, and the default DTO namespace is `App\\Dto`, then the namespace of the generated \nclass will be `App\\Dto\\User`.\n\nYou can leave namespace postfix empty.\n\n**props**\n\nThis object contains information about DTO class properties and methods. Keys will be cast to class properties. Values\ncontain information about getters return types.\n\n`\"description\" : \"?string\"` - due to this pair `$_description` property will be added to DTO class with \n`private ?string $_description` property and `getDescription(): ?string` method, that expects return type \n\"string\" and allows null.\n\n##### Generating DTO\n\nGiven you have already created pattern as json file named `item.json` in the `phpdto_patterns` folder.\n\nRun `vendor/bin/phpdto -f=item` to have your DTO class generated. It will be stored under namespace specified in\nthe `phpdto.json` config file combined with namespace postfix specified in your pattern.\n\nGiven you are generating DTO class from the pattern shown in \"DTO JSON Pattern\" section, then you will have following class\ngenerated.\n\n```php\n\u003c?php\n\nnamespace App\\Dto;\n\nuse PhpDto\\Dto;\nuse PhpDto\\DtoSerialize;\nuse PhpDto\\ToArray;\n\nclass ItemDto extends Dto\n{\n\tuse DtoSerialize, ToArray;\n\n\tprivate int $_id;\n\tprivate ?int $_count;\n\tprivate string $_name;\n\tprivate ?string $_description;\n\tprivate bool $_isActive;\n\n\tpublic function __construct( array $item )\n\t{\n\t    $this-\u003e_id = $item['id'];\n\t    $this-\u003e_count = $item['count'];\n\t    $this-\u003e_name = $item['name'];\n\t    $this-\u003e_description = $item['description'];\n\t    $this-\u003e_isActive = $item['is_active'];\n\t}\n\n\tpublic function getId(): int\n\t{\n\t    return $this-\u003e_id;\n\t}\n\n\tpublic function getCount(): ?int\n\t{\n\t    return $this-\u003e_count;\n\t}\n\n\tpublic function getName(): string\n\t{\n\t    return $this-\u003e_name;\n\t}\n\n\tpublic function getDescription(): ?string\n\t{\n\t    return $this-\u003e_description;\n\t}\n\n\tpublic function getIsActive(): bool\n\t{\n\t    return $this-\u003e_isActive;\n\t}\n}\n```\n\n##### How to use\n\nThere are 2 mapper methods:\n\n`static function mapArray(array $items, bool $shouldSerialize = false): array`\n\n`static function mapSingle(array $item, bool $shouldSerialize = false): Dto|stdClass`\n\nUse `mapArray` when you need to map multidimensional array, otherwise use `mapSingle`.\n\nMapping example:\n\n###### Single\n\n```php\n$itemData = [\n    'id' =\u003e 1,\n    'name' =\u003e 'Dummy Item',\n    'description' =\u003e 'Some dummy description.',\n    'count' =\u003e 10,\n    'is_active' =\u003e true,\n    'meta' =\u003e [\n        'meta_title' =\u003e 'Dummy meta title',\n        'meta_description' =\u003e 'Dummy meta description',\n    ],\n    'tags' =\u003e 'TagOne, TagTwo, TagThree'\n];\n\n$item = ItemDto::mapSingle( $itemData );\n\n// Now you are able to access DTO properties via getters\n\n$item-\u003egetId();\n$item-\u003eName();\n$item-\u003egetDescription();\n$item-\u003egetCount();\n$item-\u003egetIsActive();\n```\n\n###### Multidimensional\n\n```php\n$itemData = [\n    [\n        'id' =\u003e 1,\n            'name' =\u003e 'Dummy Item',\n            'description' =\u003e 'Some dummy description.',\n            'count' =\u003e 10,\n            'is_available' =\u003e true, \n            'meta' =\u003e [\n                'meta_title' =\u003e 'Dummy meta title',\n                'meta_description' =\u003e 'Dummy meta description',\n            ],\n            'tags' =\u003e 'TagOne, TagTwo, TagThree'\n    ],\n    // more items\n];\n\n$items = ItemDto::mapArray( $itemData ); // array of instance of ItemDto class\n\nforeach( $items as $item )\n{\n    $item-\u003egetId();\n    // ... \n}\n```\n\n***CONSIDER REFACTORING THE CONSTRUCTOR OF GENERATED DTO CLASS DEPENDING ON THE DATA STRUCTURE OF THE ARRAY YOU\nWANT TO MAP.***\n\nSometimes you may want to have DTOs as objects that you could pass in AJAX response or whatever you need for.\n\nThe second parameter of the mapper methods is a flag that decides if the data should be serialized.\n\n`ItemDto::mapSingle( $itemData, true )` - this will return you the DTO as a serialized object:\n\n```\n{\n  \"id\": 1\n  \"name\": \"Dummy Item\"\n  \"description\": \"Some dummy description.\"\n  \"count\": 10\n  \"isActive\": true\n}\n```\n\nSame is true for `mapArray` method.\n\n##### DTO Faker\n\nYou can generate fake data for your DTOs easily using `PhpDto\\Services\\DtoFaker` class.\n\n```php\n$fakeData = DtoFaker::fakeSingle( ItemDto::class ); // array that contains fake data for ItemDto\n$item = ItemDto::mapSingle( $fakeData );\n```\n\nNow your item looks like this:\n\n```\n{\n    \"id\": 993\n    \"count\": 340\n    \"name\": \"2R9ifLLxfG965wikJWrr\"\n    \"description\": \"MluADBj2rwmAjBC6ZyH4\"\n    \"isActive\": false\n}\n```   \n\nAll the values are randomly generated, even the boolean value for isActive field.\n\nYou can fake multidimensional array via `DtoFaker::fakeArray` method.\n\nIn the example below we want to fake data for 10 items.\n\n```php\n$fakeData = DtoFaker::fakeArray( ItemDto::class, 10 );\n$items = ItemDto::mapArray( $fakeData );\n```\n\nSecond parameter of the `Dto::fakeArray` method is the count of generated items.\n\n`Dto::fakeSingle` and `Dto::fakeArray` methods are using PHP Reflection API to get information about properties and\ngetters.\n\nAlternatively you can use `Dto::fakeSingeFromPattern` and `Dto::fakeArrayFromPattern` methods. You must pass them full\npath to your json pattern:  \n`Dto::fakeArrayFromPattern('/full/path/to/pattern.json')`.\n\n###### `ToArray` trait and `toArray(): array` method.\n\nWhen you need to cast your DTO object to array, you can use the `toArray` method.\n\n```php\n\u003c?php\n\nnamespace App\\Dto;\n\nuse PhpDto\\Dto;\nuse PhpDto\\ToArray;\n\nclass MockDto extends Dto\n{\n    use ToArray;\n    \n    private ?string $_name;\n    private int $_count;\n    private bool $_isTrue;\n    \n    public function __construct( array $data )\n    {\n        $this-\u003e_name   = $data['name'];\n        $this-\u003e_count  = $data['count'];\n        $this-\u003e_isTrue = $data['is_true'];\n    }\n    \n    public function getName(): ?string\n    {\n        return $this-\u003e_name;\n    }\n    \n    public function getCount(): int\n    {\n        return $this-\u003e_count;\n    }\n\n    public function getIsTrue(): bool\n    {\n        return $this-\u003e_isTrue;\n    }\n}\n\n$mockData = [\n    'name' =\u003e 'Mock name',\n\t'count'   =\u003e 4,\n\t'is_true' =\u003e true\n];\n\n$dto = new MockDto($mockData);\n\n$arr = $dto-\u003etoArray();\n\nvar_dump($arr);\n```\n\nThe output will be:\n```\narray(3) {\n  'name' =\u003e\n  string(9) \"Mock name\"\n  'count' =\u003e\n  int(4)\n  'is_true' =\u003e\n  bool(true)\n}\n```\n\n`toArray` method accepts two parameters: `toSnakeCase` and `includeNulls`:\n\nIf you want to keep array keys format to be same as class fields, you can pass `toSnakeCase: false` parameter:\n`$arr = $dto-\u003etoArray(toSnakeCase: false);`\n\nIf you want to include keys with `null` values, you can pass `includeNulls: true` parameter:\n`$arr = $dto-\u003etoArray(includeNulls: true);`\n\nThe output then will be:\n```\narray(3) {\n  'name' =\u003e\n  string(9) \"Mock name\"\n  'count' =\u003e\n  int(4)\n  'isTrue' =\u003e\n  bool(true)\n}\n```\nSo, now the `isTrue` key is camelCase. \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhakobyansen%2Fphpdto","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhakobyansen%2Fphpdto","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhakobyansen%2Fphpdto/lists"}