### Install JoliCode AutoMapper Source: https://github.com/silpo-tech/mapperbundle/blob/main/README.md Install the JoliCode AutoMapper library using Composer. ```sh composer require jolicode/automapper ``` -------------------------------- ### Manual Setup with JoliCodeAdapter Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Manually configure the MapperBundle using the JoliCodeAdapter for custom setups. Usage is identical regardless of the adapter. ```php convert($sourceArray, TargetDto::class); $array = $mapper->convertToArray($sourceObject); $collection = $mapper->convertCollection($items, ItemDto::class); ``` -------------------------------- ### Install Mapper Bundle with Composer Source: https://github.com/silpo-tech/mapperbundle/blob/main/README.md Use this command to install the Mapper Bundle via Composer. ```sh composer require silpo-tech/mapper-bundle ``` -------------------------------- ### Register Mapper Bundle Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Add the bundle to your config/bundles.php file to enable it in the application. ```php ['all' => true], AutoMapperPlus\AutoMapperPlusBundle\AutoMapperPlusBundle::class => ['all' => true], ]; ``` -------------------------------- ### Run Mapper Bundle Tests Source: https://github.com/silpo-tech/mapperbundle/blob/main/README.md Execute the tests for the Mapper Bundle using the provided Composer script. ```shell composer test:run ``` -------------------------------- ### Mapping Nested Objects and Collections Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Demonstrates defining DTOs with nested objects and typed collections, and performing the conversion from an array to the DTO structure. ```php [ 'name' => 'John Doe', 'email' => 'john@example.com', ], 'shippingAddress' => [ 'street' => '123 Main St', 'city' => 'New York', 'zipCode' => '10001', ], 'items' => [ ['productName' => 'Widget', 'quantity' => 2, 'price' => 29.99], ['productName' => 'Gadget', 'quantity' => 1, 'price' => 49.99], ], 'createdAt' => '2023-06-15 10:30:00', 'updatedAt' => '2023-06-15 14:45:00', ]; $orderDto = $mapper->convert($orderData, OrderDto::class); // Result: Fully hydrated OrderDto with nested CustomerDto, AddressDto, // and array of OrderItemDto objects, plus DateTime instances ``` -------------------------------- ### Register MapperBundle and AutoMapperPlusBundle Source: https://github.com/silpo-tech/mapperbundle/blob/main/README.md Register the necessary bundles in your application's bundles.php file for AutoMapperPlus. ```php ['all' => true], AutoMapperPlus\AutoMapperPlusBundle\AutoMapperPlusBundle::class => ['all' => true] ]; ``` -------------------------------- ### Update Existing Objects with Mapper::convertToObject() Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Use convertToObject to apply data changes to an existing object instance, preserving its identity. ```php repository->find($id); // Map update data onto existing entity $this->mapper->convertToObject($updateData, $product); // $product is now updated with values from $updateData return $product; } } // Usage $updateData = [ 'name' => 'Updated Product Name', 'price' => 29.99, 'description' => 'New description', ]; $updatedProduct = $productService->updateProduct(123, $updateData); ``` -------------------------------- ### Configure AutoMapper with PreLoading Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Extend `AutoMapperConfig` to enable preloading for optimized Doctrine collection mapping. Custom member mappings can also be registered within the configuration closure. ```php setUsePreLoad(true); // Register custom mappings $config->registerMapping(User::class, UserDto::class) ->forMember('fullName', function (User $user) { return $user->getFirstName() . ' ' . $user->getLastName(); }); }); // Check if preloading is enabled if ($config->usePreLoad()) { echo "Preloading is enabled for collection optimization"; } ``` -------------------------------- ### Perform Data Conversion with Mapper::convert() Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Use the convert method to map data from arrays or objects into new destination types, including nested structures. ```php [ 'street' => '123 Main St', 'city' => 'New York', ], 'orders' => [], 'createdAt' => '2023-01-01 00:00:00', 'updatedAt' => '2023-06-15 14:30:00', ]; $userDto = $mapper->convert($sourceData, UserDto::class); // Result: UserDto with nested AddressDto and DateTime objects // Object to Object conversion $sourceUser = new SourceUser(); $sourceUser->name = 'John Doe'; $sourceUser->email = 'john@example.com'; $destinationDto = $mapper->convert($sourceUser, UserDto::class); ``` -------------------------------- ### Configure AutoMapper with DoctrineProxyPropertyAccessor Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Configure AutoMapper to use DoctrineProxyPropertyAccessor for seamless handling of Doctrine proxy objects, preventing LazyLoadingException errors. ```php getOptions()->setPropertyAccessor(new DoctrineProxyPropertyAccessor()); }); // Now mapping works correctly with Doctrine proxy objects $order = $orderRepository->find(1); // $order->user may be a Doctrine Proxy (lazy-loaded) $orderDto = $mapper->convert($order, OrderDto::class); // DoctrineProxyPropertyAccessor automatically calls $proxy->__load() // before accessing properties, ensuring data is available ``` -------------------------------- ### Convert Collection to DTOs using Mapper::convertCollection() Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Employ `convertCollection()` for efficient mapping of an iterable collection of source objects to a collection of destination objects. This method supports automatic preloading for optimized data fetching. ```php orderRepository->findByUser($userId); // Convert entire collection to DTOs $orderDtos = $this->mapper->convertCollection($orders, OrderDto::class); return iterator_to_array($orderDtos); } } // Batch conversion from array data $sourceItems = [ ['name' => 'Product A', 'price' => 10.00, 'createdAt' => '2023-01-01'], ['name' => 'Product B', 'price' => 20.00, 'createdAt' => '2023-01-02'], ['name' => 'Product C', 'price' => 30.00, 'createdAt' => '2023-01-03'], ]; $productDtos = $mapper->convertCollection($sourceItems, ProductDto::class); // Result: iterable of ProductDto objects ``` -------------------------------- ### Register MapperBundle and AutoMapperBundle for JoliCode Source: https://github.com/silpo-tech/mapperbundle/blob/main/README.md Register the MapperBundle and the JoliCode AutoMapper bundle in your application's bundles.php file. ```php ['all' => true], AutoMapper\Symfony\Bundle\AutoMapperBundle::class => ['all' => true], ]; ``` -------------------------------- ### Flexible Date Parsing with FlexibleDateTimeTransformerFactory Source: https://context7.com/silpo-tech/mapperbundle/llms.txt The JoliCodeAdapter automatically includes FlexibleDateTimeTransformerFactory, enabling flexible parsing of various date/time string formats into DateTime objects. ```php '2023-01-15', // Y-m-d 'date2' => '2023-01-15 14:30:00', // Y-m-d H:i:s 'date3' => '15-01-2023', // d-m-Y 'date4' => 'January 15, 2023', // Natural language 'date5' => '2023-01-15T14:30:00+00:00', // ISO 8601 ]; class EventDto { public \DateTime $date1; public \DateTime $date2; public \DateTimeImmutable $date3; public \DateTimeInterface $date4; public \DateTime $date5; } $event = $mapper->convert($data, EventDto::class); // All date formats are correctly parsed to DateTime objects ``` -------------------------------- ### Mapper::convertToObject() - Map to Existing Instance Source: https://context7.com/silpo-tech/mapperbundle/llms.txt The `convertToObject()` method maps source data to an existing object instance, useful for update operations where you want to preserve the target object identity. ```APIDOC ## Mapper::convertToObject() The `convertToObject()` method maps source data to an existing object instance, useful for update operations where you want to preserve the target object identity. ### Parameters - **source** (mixed) - Required - The data to be converted (can be an array or an object). - **destination** (object) - Required - The existing object instance to map the data onto. ### Returns - (object) - The modified destination object. ### Request Example ```php repository->find($id); // Map update data onto existing entity $this->mapper->convertToObject($updateData, $product); // $product is now updated with values from $updateData return $product; } } // Usage $updateData = [ 'name' => 'Updated Product Name', 'price' => 29.99, 'description' => 'New description', ]; // Assuming $productService is an instance of ProductService and product with ID 123 exists // $updatedProduct = $productService->updateProduct(123, $updateData); ``` ``` -------------------------------- ### Configure AutoMapperPlus Mappings Source: https://github.com/silpo-tech/mapperbundle/blob/main/README.md Configure AutoMapperPlus mappings by defining an AutoMapperConfiguratorInterface implementation and overriding the AutoMapperConfig service. ```yaml # this config only applies to the services created by this file _instanceof: AutoMapperPlus\AutoMapperPlusBundle\AutoMapperConfiguratorInterface: tags: ['automapper_plus.configurator'] # and add to override implementation of AutoMapperConfig automapper_plus.configuration: class: MapperBundle\Configuration\AutoMapperConfig ``` -------------------------------- ### Mapper::convert() - Universal Data Conversion Source: https://context7.com/silpo-tech/mapperbundle/llms.txt The `convert()` method is the primary method for mapping data between types. It automatically determines whether to create a new object or map to an existing one based on the destination parameter type. ```APIDOC ## Mapper::convert() The `convert()` method is the primary method for mapping data between types. It automatically determines whether to create a new object or map to an existing one based on the destination parameter type. ### Parameters - **source** (mixed) - Required - The data to be converted (can be an array or an object). - **destinationType** (string) - Required - The fully qualified class name of the target type. ### Returns - (mixed) - The converted object or array. ### Request Example ```php [ 'street' => '123 Main St', 'city' => 'New York', ], 'orders' => [], 'createdAt' => '2023-01-01 00:00:00', 'updatedAt' => '2023-06-15 14:30:00', ]; $userDto = $mapper->convert($sourceData, UserDto::class); // Result: UserDto with nested AddressDto and DateTime objects // Object to Object conversion $sourceUser = new SourceUser(); // Assuming SourceUser is a defined class $sourceUser->name = 'John Doe'; $sourceUser->email = 'john@example.com'; $destinationDto = $mapper->convert($sourceUser, UserDto::class); ``` ``` -------------------------------- ### ORMPreLoader - Doctrine Optimization Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Optimizes Doctrine ORM collection mapping by batch-loading related entities to prevent N+1 query issues. ```APIDOC ## ORMPreLoader ### Description Automatically detects lazy-loaded collections and batch-loads them to optimize performance during mapping. ### Usage - Enable via `AutoMapperConfig::setUsePreLoad(true)`. - Use `convertCollectionWithPreLoader()` to trigger batch loading for relations. ``` -------------------------------- ### Configure AutoMapper with MergePropertyAccessor for Null-Safe Updates Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Configure AutoMapper to use MergePropertyAccessor for partial updates (PATCH-style), ensuring that null values from the source are ignored and existing properties are retained. ```php getOptions()->setPropertyAccessor(new MergePropertyAccessor()); }); // Partial update - null values are ignored $existingUser = new User(); $existingUser->name = 'John Doe'; $existingUser->email = 'john@example.com'; $existingUser->phone = '555-1234'; $updateData = [ 'name' => 'Jane Doe', // Will be updated 'email' => null, // Will NOT be updated (null is ignored) 'phone' => '555-5678', // Will be updated ]; $mapper->convertToObject($updateData, $existingUser); // Result: name='Jane Doe', email='john@example.com', phone='555-5678' ``` -------------------------------- ### Mapper::convertCollection() Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Maps an iterable collection of source items to a collection of destination objects, supporting batch processing. ```APIDOC ## Mapper::convertCollection() ### Description Converts an iterable collection of source items into a collection of target objects. ### Parameters - **source** (iterable) - Required - The collection of items to convert. - **targetClass** (string) - Required - The fully qualified class name of the destination objects. ### Response - **iterable** - A collection of mapped destination objects. ``` -------------------------------- ### Use MapperInterface in Controller Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Inject MapperInterface to handle data conversion between arrays and objects within a controller. ```php mapper->convert($requestData, UserDto::class); } public function updateUser(array $requestData, User $existingUser): User { // Convert array to existing object instance (updates in place) return $this->mapper->convertToObject($requestData, $existingUser); } public function serializeUser(User $user): array { // Convert object to array for JSON response return $this->mapper->convertToArray($user); } } ``` -------------------------------- ### MapperInterface - Core Mapping Interface Source: https://context7.com/silpo-tech/mapperbundle/llms.txt The MapperInterface defines the primary API for all data conversion operations, including converting single objects, arrays, and collections. ```APIDOC ## MapperInterface - Core Mapping Interface The `MapperInterface` defines the primary API for all data conversion operations. It provides methods for converting single objects, arrays, and collections between different types with full generics support. ### Methods - **convert(mixed $source, string $destinationType): mixed** Converts source data to the specified destination type. Automatically determines whether to create a new object or map to an existing one. - **convertToObject(mixed $source, object $destination): object** Maps source data to an existing object instance, useful for update operations. - **convertToArray(object $source): array** Converts an object to an array. ### Example Usage ```php mapper->convert($requestData, UserDto::class); } public function updateUser(array $requestData, User $existingUser): User { // Convert array to existing object instance (updates in place) return $this->mapper->convertToObject($requestData, $existingUser); } public function serializeUser(User $user): array { // Convert object to array for JSON response return $this->mapper->convertToArray($user); } } ``` ``` -------------------------------- ### Configure MapperBundle to use JoliCode AutoMapper Source: https://github.com/silpo-tech/mapperbundle/blob/main/README.md Set the 'automapper' configuration option to 'jolicode' in your mapper.yaml configuration file to use JoliCode AutoMapper. ```yaml mapper: automapper: jolicode ``` -------------------------------- ### Convert Object to Array using Mapper::convertToArray() Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Use `convertToArray()` to serialize an object into an associative array, suitable for API responses. Ensure the MapperInterface is injected into your class. ```php mapper->convertToArray($user); return [ 'success' => true, 'data' => $data, ]; } } // Input object $user = new User(); $user->id = 1; $user->name = 'Jane Doe'; $user->email = 'jane@example.com'; $user->createdAt = new \DateTime('2023-01-01'); $array = $mapper->convertToArray($user); // Result: ['id' => 1, 'name' => 'Jane Doe', 'email' => 'jane@example.com', 'createdAt' => '2023-01-01T00:00:00+00:00'] ``` -------------------------------- ### Register MapperBundle and AutoMapperBundle Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Register the JoliCode MapperBundle and AutoMapperBundle in your Symfony application's bundles configuration. ```php ['all' => true], AutoMapper\Symfony\Bundle\AutoMapperBundle::class => ['all' => true], ]; ``` -------------------------------- ### ORMPreLoader for Doctrine Collection Optimization Source: https://context7.com/silpo-tech/mapperbundle/llms.txt The `ORMPreLoader` automatically optimizes Doctrine ORM collection mapping by batch-loading related entities, preventing N+1 query issues. It's auto-configured when Doctrine ORM is present. ```php setUsePreLoad(true); // When mapping collections, relations are batch-loaded $orders = $orderRepository->findAll(); // Orders with lazy User relations $orderDtos = $mapper->convertCollectionWithPreLoader($orders, OrderDto::class); // All User relations are loaded in a single batch query ``` -------------------------------- ### Mapper::convertToArray() Source: https://context7.com/silpo-tech/mapperbundle/llms.txt Converts an object into an associative array, typically used for preparing data for JSON API responses. ```APIDOC ## Mapper::convertToArray() ### Description Converts a source object into an associative array representation. ### Parameters - **source** (object) - Required - The object to be converted. ### Response - **array** - An associative array containing the object properties. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.