epalshin / object-to-graphql
Utility helper for generating GraphQL types with webonyx/graphql-php
Fund package maintenance!
palshin
Requires
- php: ^8.0
- webonyx/graphql-php: ^14.6
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.0
- phpunit/phpunit: ^9.5
- spatie/ray: ^1.10
- vimeo/psalm: ^4.3
This package is auto-updated.
Last update: 2024-05-04 19:16:51 UTC
README
I noticed that in my own code (I use Lighthouse PHP for implementation GraphQL API) quite often I first describe the input type in the schema, then I describe the object for this type (DTO). It creates a sense of repetition and makes type system maintenance more difficult, so I decided to add the ability to programmatically generate types for the schema by its type declaration in code. So in my project I expanded this recommendation for third case: DTO for custom resolvers.
Installation
You can install the package via composer:
composer require epalshin/object-to-graphql
Usage
use GraphQL\Type\Definition\ObjectType; use Palshin\ObjectToGraphQL\ObjectToGraphQL; use Palshin\ObjectToGraphQL\Attributes\GraphQLArrayType; use Palshin\ObjectToGraphQL\Attributes\GraphQLObjectType; #[GraphQLObjectType(typeCategory: ObjectToGraphQL::TYPE_CATEGORY_INPUT)] class ProductCreateDTO { public string $name; public string $description; public float $price; public bool $isPublic; #[GraphQLArrayType(ObjectToGraphQL::STRING, allowsNull: false)] public array $photoUrls; public ?ProductCategoryCreateDTO $category; } class ProductCategoryCreateDTO { public string $name; public string $description; public int $sortOrder; } $objectToGraphQL = new ObjectToGraphQL(); [ $productCreateDto, $productCategoryCreateDto ] = $objectToGraphQL->getObjectTypes(ProductCreateDTO::class); // and now you can register $objectType in your schema $mutationType = new ObjectType([ 'name' => 'Mutation', 'fields' => [ 'productCreate' => [ 'type' => $product, 'args' => [ 'input' => $productCreateDto, ], 'resolve' => function($rootValue, $args) { // TODO } ] ] ]);
The resulting GraphQL schema will be:
input ProductCreateDTOInput { name: String! description: String! price: Float! isPublic: Boolean! photoUrls: [String!]! category: ProductCategoryCreateDTOInput } input ProductCategoryCreateDTOInput { name: String! description: String! sortOrder: Int! }
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
TODO
- Add cyclic addition of types to schema
- Add processing for union types
- Add processing for type category and suffixes parameters passing through attribute
- Add strict mode for early error detection
- Add custom exceptions
- Write more tests
- Add possibility for adding description for generated types
License
The MIT License (MIT). Please see License File for more information.