### Example GET Request with Query Parameters to Fetch User (Conceptual) Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This `curl` command illustrates how query parameters can be used for GET requests, conceptually similar to how the bundle might handle them if configured. Note: The provided controller example is for POST; this shows query parameter syntax. ```bash curl -X GET "http://localhost/api/users?name=John%20Doe&email=john@example.com&age=25&tags[]=developer&tags[]=symfony" ``` -------------------------------- ### Example POST Request with Form Data to Create User Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This `curl` command demonstrates sending a POST request with `x-www-form-urlencoded` data to create a user. This format is suitable for traditional HTML forms. ```bash curl -X POST http://localhost/api/users \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "name=John Doe&email=john@example.com&age=25&tags[0]=developer&tags[1]=symfony" ``` -------------------------------- ### Install Request DTO Resolver Bundle via Composer Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This command installs the Request DTO Resolver Bundle using Composer, a dependency manager for PHP. It adds the bundle to your project's dependencies. ```bash composer require macpaw/request-dto-resolver ``` -------------------------------- ### Install Request DTO Resolver Bundle Source: https://github.com/macpaw/request-dto-resolver/blob/develop/README.md Installs the Request DTO Resolver bundle using Composer. This command adds the bundle to your project and handles dependency management. The bundle should auto-register; if not, manual registration in `config/bundles.php` is shown. ```console composer require macpaw/request-dto-resolver ``` ```php // config/bundles.php return [ RequestDtoResolver\RequestDtoResolverBundle::class => ['all' => true], // ... ]; ``` -------------------------------- ### Example POST Request with JSON Body to Create User Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This `curl` command shows how to send a POST request with a JSON body to the `/api/users` endpoint to create a new user. The request body should match the structure of the `UserDto`. ```bash curl -X POST http://localhost/api/users \ -H "Content-Type: application/json" \ -d '{ "name": "John Doe", "email": "john@example.com", "age": 25, "tags": ["developer", "symfony"] }' ``` -------------------------------- ### Request Example with Data from Multiple Sources Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This bash script shows a cURL request to the `/api/search` endpoint. It includes query parameters (`page`, `query`), a JSON body, and an API key header. The `SearchDto` resolves data from these sources, with the JSON body's 'query' and 'page' values overriding those provided in the query parameters, demonstrating the resolver's data source priority. ```bash # JSON body has priority over query params curl -X POST "http://localhost/api/search?page=1&query=override" \ -H "Content-Type: application/json" \ -H "X-API-Key: secret123" \ -d '{ "query": "symfony", "page": 5 }' # Result uses: # - query: "symfony" (from JSON body, overrides query param) ``` -------------------------------- ### Example Request with Custom Field Mapping Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This bash script demonstrates a cURL request to an API endpoint for products. It sends a JSON payload with custom field names ('product-id', 'product-name') and an API key in the header ('X-API-Key'). The Request DTO Resolver maps these custom names to the corresponding DTO properties (productId, productName, apiKey) based on the form type configuration. ```bash curl -X POST http://localhost/api/products \ -H "Content-Type: application/json" \ -H "X-API-Key: secret123" \ -d '{ "product-id": "12345", "product-name": "Widget" }' # The resolver maps: # - "product-id" → productId # - "product-name" → productName # - "X-API-Key" header → apiKey ``` -------------------------------- ### Example Validation Error Response from API Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This bash script shows a cURL request to an API endpoint for users, sending invalid data (short name, invalid email, age below minimum, missing required tag). The server responds with a HTTP 400 status code and a JSON body detailing the validation failures, including specific messages for each violated DTO property, as handled by the `ExceptionListener`. ```bash curl -X POST http://localhost/api/users \ -H "Content-Type: application/json" \ -d '{ "name": "Jo", "email": "invalid-email", "age": 15 }' # Response (HTTP 400): { "error": "Validation failed", "dto": "App\\DTO\\UserDto", "violations": { "name": "This value is too short. It should have 3 characters or more.", "email": "This value is not a valid email address.", "age": "This value should be 18 or more.", "tags": "This collection should contain 1 element or more." } } ``` -------------------------------- ### POST /api/products - Product Creation with Custom Field Mapping Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This endpoint allows for the creation of products. It demonstrates how to use custom field names in the request body, which are mapped to the DTO properties via the form type configuration. It also shows how to pass API keys via headers. ```APIDOC ## POST /api/products ### Description Creates a new product with custom field mapping and API key authentication. ### Method POST ### Endpoint /api/products ### Parameters #### Query Parameters None #### Request Body - **product-id** (string) - Required - The unique identifier for the product. - **product-name** (string) - Required - The name of the product. #### Headers - **X-API-Key** (string) - Required - The API key for authentication. ### Request Example ```bash curl -X POST http://localhost/api/products \ -H "Content-Type: application/json" \ -H "X-API-Key: secret123" \ -d '{ "product-id": "12345", "product-name": "Widget" }' ``` ### Response #### Success Response (201 Created) - **id** (string) - The ID of the created product. - **name** (string) - The name of the created product. #### Response Example ```json { "id": "12345", "name": "Widget" } ``` #### Error Response (400 Bad Request) - **error** (string) - Indicates a validation failure. - **dto** (string) - The class name of the DTO that failed validation. - **violations** (object) - A map of validation errors, where keys are property paths and values are error messages. #### Error Response Example ```json { "error": "Validation failed", "dto": "App\DTO\ProductDto", "violations": { "product-id": "This is a required field." } } ``` ``` -------------------------------- ### Custom Field Mapping Configuration (PHP) Source: https://github.com/macpaw/request-dto-resolver/blob/develop/README.md Demonstrates how to configure a Form Type to map an incoming request key (e.g., 'user-id') to a different DTO property name (e.g., 'userId') using the 'lookupKey' option. This is useful for handling inconsistent naming conventions in requests. ```php add('userId', TextType::class, [ 'attr' => ['lookupKey' => 'user-id'], ]); // ... ``` -------------------------------- ### POST /api/users - User Registration with Validation Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This endpoint is for user registration. It enforces validation rules on user properties like name, email, and age. If validation fails, it returns a detailed error response. ```APIDOC ## POST /api/users ### Description Registers a new user with provided details, enforcing validation rules. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters None #### Request Body - **name** (string) - Required - The user's name (minimum 3 characters). - **email** (string) - Required - The user's email address (must be valid). - **age** (integer) - Required - The user's age (must be 18 or more). - **tags** (array) - Required - A list of tags associated with the user (minimum 1 element). ### Request Example ```bash curl -X POST http://localhost/api/users \ -H "Content-Type: application/json" \ -d '{ "name": "Jo", "email": "invalid-email", "age": 15, "tags": [] }' ``` ### Response #### Success Response (201 Created) - **id** (string) - The ID of the created user. - **message** (string) - A success message. #### Response Example ```json { "id": "user123", "message": "User created successfully." } ``` #### Error Response (400 Bad Request) - **error** (string) - Indicates a validation failure. - **dto** (string) - The class name of the DTO that failed validation. - **violations** (object) - A map of validation errors, where keys are property paths and values are error messages. #### Error Response Example ```json { "error": "Validation failed", "dto": "App\DTO\UserDto", "violations": { "name": "This value is too short. It should have 3 characters or more.", "email": "This value is not a valid email address.", "age": "This value should be 18 or more.", "tags": "This collection should contain 1 element or more." } } ``` ``` -------------------------------- ### Configure Target DTO Interface Source: https://github.com/macpaw/request-dto-resolver/blob/develop/README.md Defines a marker interface for DTOs and configures the bundle to recognize it. This allows the resolver to identify which arguments in controllers should be processed as DTOs. The configuration is done via a YAML file. ```php // src/DTO/RequestDtoInterface.php namespace App\DTO; interface RequestDtoInterface { } ``` ```yaml # config/packages/request_dto_resolver.yaml request_dto_resolver: target_dto_interface: App\DTO\RequestDtoInterface ``` -------------------------------- ### POST /api/search - Search with Data Resolution Priority Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This endpoint performs a search operation. It demonstrates how the resolver prioritizes data sources for DTO population, checking the JSON body first, then query parameters and form data, and finally request headers. ```APIDOC ## POST /api/search ### Description Executes a search query, populating the DTO from multiple sources with specific resolution priorities. ### Method POST ### Endpoint /api/search ### Parameters #### Query Parameters - **page** (integer) - Optional - The page number for search results. - **query** (string) - Optional - The search term. #### Request Body - **query** (string) - Required - The search term (takes priority over query parameters). - **page** (integer) - Optional - The page number for search results (takes priority over query parameters). #### Headers - **X-API-Key** (string) - Optional - An API key. ### Request Example ```bash # JSON body has priority over query params curl -X POST "http://localhost/api/search?page=1&query=override" \ -H "Content-Type: application/json" \ -H "X-API-Key: secret123" \ -d '{ "query": "symfony", "page": 5 }' ``` ### Response #### Success Response (200 OK) - **query** (string) - The resolved search query. - **page** (integer) - The resolved page number. - **apiKey** (string) - The resolved API key. #### Response Example ```json { "query": "symfony", "page": 5, "apiKey": "secret123" } ``` #### Error Response (415 Unsupported Media Type) - **error** (string) - Indicates an unsupported media type. - **message** (string) - Details about the error. #### Error Response Example ```json { "error": "Unsupported media type", "message": "Unsupported Media Type" } ``` ``` -------------------------------- ### Create User DTO with Validation Constraints Source: https://github.com/macpaw/request-dto-resolver/blob/develop/README.md Defines a User DTO that implements the `RequestDtoInterface`. It uses Symfony's Validator components to specify constraints such as 'NotBlank', 'Length', and 'Email' for its properties. This DTO will be hydrated with validated request data. ```php // src/DTO/UserDto.php namespace App\DTO; use Symfony\Component\Validator\Constraints as Assert; class UserDto implements RequestDtoInterface { #[Assert\NotBlank] #[Assert\Length(min: 3)] public string $name; #[Assert\NotBlank] #[Assert\Email] public string $email; /** @var string[] */ #[Assert\Count(min: 1)] #[Assert\All([ new Assert\NotBlank, new Assert\Length(min: 2) ])] public array $tags = []; } ``` -------------------------------- ### Use DTO Resolver in Symfony Controller Source: https://github.com/macpaw/request-dto-resolver/blob/develop/README.md Demonstrates how to use the Request DTO Resolver in a Symfony controller. By type-hinting an action argument with a DTO (`UserDto`) and decorating the action with `#[FormType(UserFormType::class)]`, the request data is automatically resolved, validated, and hydrated into the DTO object. ```php // src/Controller/UserController.php namespace App\Controller; use App\DTO\UserDto; use App\Form\UserFormType; use RequestDtoResolver\Attribute\FormType; use Symfony\Component\HttpFoundation\JsonResponse; class UserController { #[FormType(UserFormType::class)] public function __invoke(UserDto $dto): JsonResponse { // $dto is now a validated and populated object return new JsonResponse([ 'name' => $dto->name, 'email' => $dto->email, 'tags' => $dto->tags, ]); } } ``` -------------------------------- ### Symfony FOSRestBundle Configuration for JSON Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This configuration snippet enables the JSON decoder for FOSRestBundle, allowing it to automatically parse incoming JSON request bodies. The RequestDtoResolver can then leverage this pre-parsed data. ```yaml fos_rest: body_listener: enabled: true decoders: json: fos_rest.decoder.json ``` -------------------------------- ### PHP Request Body Parsing Detection Source: https://context7.com/macpaw/request-dto-resolver/llms.txt Illustrates how the RequestDtoResolver detects and utilizes pre-parsed request data from bundles like FOSRestBundle. This prevents redundant parsing of the request body, improving efficiency. ```php // The bundle automatically detects pre-parsed request data // If $request->request is already populated by another bundle, // it uses that data instead of parsing the body again // The RequestDtoResolver will detect FOSRestBundle's parsed data // and use it directly, avoiding double-parsing ``` -------------------------------- ### Integrate DTO Resolution in a Symfony Controller Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This PHP code demonstrates how to use the Request DTO Resolver Bundle in a Symfony controller. The `#[FormType]` attribute links the controller action to the `UserFormType`, and the `UserDto` argument is automatically populated and validated. ```php // src/Controller/UserController.php namespace App\Controller; use App\DTO\UserDto; use App\Form\UserFormType; use RequestDtoResolver\Attribute\FormType; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; class UserController { #[Route('/api/users', methods: ['POST'])] #[FormType(UserFormType::class)] public function createUser(UserDto $dto): JsonResponse { // $dto is automatically validated and populated return new JsonResponse([ 'success' => true, 'user' => [ 'name' => $dto->name, 'email' => $dto->email, 'age' => $dto->age, 'tags' => $dto->tags, ] ], 201); } } ``` -------------------------------- ### Configure Target DTO Interface for Request DTO Resolver Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This YAML configuration specifies the marker interface that the Request DTO Resolver Bundle will use to identify DTOs. All request DTOs should implement this interface. ```yaml # config/packages/request_dto_resolver.yaml request_dto_resolver: target_dto_interface: App\DTO\RequestDtoInterface ``` -------------------------------- ### Create User Form Type for DTO Mapping Source: https://github.com/macpaw/request-dto-resolver/blob/develop/README.md Defines a Symfony Form Type that maps incoming request data to the `UserDto`. It specifies the fields ('name', 'email', 'tags') and their corresponding types. The `configureOptions` method links this form type to the `UserDto` class. ```php // src/Form/UserFormType.php namespace App\Form; use App\DTO\UserDto; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class UserFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('name', TextType::class) ->add('email', EmailType::class) ->add('tags', CollectionType::class, [ 'entry_type' => TextType::class, 'allow_add' => true, ]); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => UserDto::class, ]); } } ``` -------------------------------- ### Register Request DTO Resolver Bundle in Symfony Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This PHP code snippet shows how to register the Request DTO Resolver Bundle within your Symfony application's configuration file (config/bundles.php). ```php // config/bundles.php return [ RequestDtoResolver\RequestDtoResolverBundle::class => ['all' => true], // other bundles... ]; ``` -------------------------------- ### Define Request DTO Interface in PHP Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This PHP code defines the marker interface for request DTOs. Any class intended to be resolved by the Request DTO Resolver Bundle must implement this interface. ```php // src/DTO/RequestDtoInterface.php namespace App\DTO; interface RequestDtoInterface { } ``` -------------------------------- ### Handle DTO Validation and Request Errors in Symfony Controller Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This PHP code is a Symfony Event Listener designed to catch and handle specific exceptions thrown during the request processing. It formats error responses as JSON for `InvalidParamsDtoException` (validation errors), `BadRequestHttpException`, and `UnsupportedMediaTypeHttpException`, returning appropriate HTTP status codes (400, 415). ```php // src/EventListener/ExceptionListener.php namespace App\EventListener; use RequestDtoResolver\Exception\InvalidParamsDtoException; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException; class ExceptionListener { public function onKernelException(ExceptionEvent $event): void { $exception = $event->getThrowable(); if ($exception instanceof InvalidParamsDtoException) { $violations = $exception->getViolations(); $errors = []; foreach ($violations as $violation) { $errors[$violation->getPropertyPath()] = $violation->getMessage(); } $response = new JsonResponse([ 'error' => 'Validation failed', 'dto' => $exception->getDtoClassName(), 'violations' => $errors ], 400); $event->setResponse($response); return; } if ($exception instanceof BadRequestHttpException) { $response = new JsonResponse([ 'error' => 'Invalid request format', 'message' => $exception->getMessage() ], 400); $event->setResponse($response); return; } if ($exception instanceof UnsupportedMediaTypeHttpException) { $response = new JsonResponse([ 'error' => 'Unsupported media type', 'message' => $exception->getMessage() ], 415); $event->setResponse($response); } } } ``` -------------------------------- ### Create User Form Type for DTO Mapping Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This PHP class defines a Symfony Form Type for the User DTO. It maps form fields to the DTO properties and configures the data class for the form. ```php // src/Form/UserFormType.php namespace App\Form; use App\DTO\UserDto; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CollectionType; use Symfony\Component\Form\Extension\Core\Type\EmailType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class UserFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('name', TextType::class) ->add('email', EmailType::class) ->add('age', IntegerType::class) ->add('tags', CollectionType::class, [ 'entry_type' => TextType::class, 'allow_add' => true, ]); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => UserDto::class, ]); } } ``` -------------------------------- ### Symfony Controller Resolving DTO from Mixed Sources Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This PHP code defines a Symfony controller action that resolves a `SearchDto` using the `RequestDtoResolver`. The `#[FormType(SearchFormType::class)]` attribute indicates that a form type should be used for validation and data mapping. The resolver prioritizes data sources in the order: JSON body, query parameters/form data, and request headers. ```php // src/Controller/SearchController.php namespace App\Controller; use App\DTO\SearchDto; use App\Form\SearchFormType; use RequestDtoResolver\Attribute\FormType; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Routing\Annotation\Route; class SearchController { #[Route('/api/search', methods: ['POST'])] #[FormType(SearchFormType::class)] public function search(SearchDto $dto): JsonResponse { // The resolver checks in this order: // 1. JSON body (if Content-Type: application/json) // 2. Query parameters and form data // 3. Request headers return new JsonResponse([ 'query' => $dto->query, 'page' => $dto->page, 'apiKey' => $dto->apiKey ]); } } ``` -------------------------------- ### Define Custom Field Mapping in Symfony Form Type Source: https://context7.com/macpaw/request-dto-resolver/llms.txt This PHP code defines a Symfony Form Type for a ProductDto. It uses `TextType` fields and customizes the HTML attributes with `lookupKey` to map external request data keys (like 'product-id') to internal DTO property names (like productId). This allows for flexible data binding from requests. ```php // src/Form/ProductFormType.php namespace App\Form; use App\DTO\ProductDto; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ProductFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options): void { $builder ->add('productId', TextType::class, [ 'attr' => ['lookupKey' => 'product-id'] ]) ->add('productName', TextType::class, [ 'attr' => ['lookupKey' => 'product-name'] ]) ->add('apiKey', TextType::class, [ 'attr' => ['lookupKey' => 'X-API-Key'] ]); } public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => ProductDto::class, ]); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.