Skip to content

Conversation

@damienfern
Copy link
Contributor

Q A
Branch? 8.1
Bug fix? no
New feature? yes
Deprecations? no
License MIT

From the docs, if you want to map an array, you need to use the MapCollection class :

use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\ObjectMapper\Transform\MapCollection;

class ProductListInput
{
    #[Map(transform: new MapCollection())]
    /** @var ProductInput[] */
    public array $products;
}

But when doing so, the MapCollection class doesn't use the ObjectMapper registered in the container and instantiate a new one.

With this PR, you will map iterable like this :

use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\ObjectMapper\Transform\MapCollection;

class ProductListInput
{
    #[Map(transform: 'object_mapper.transform.map_collection')]
    /** @var ProductInput[] */
    public array $products;
}

A current workaround is to register the service in your own services.yaml :

    object_mapper.transform.map_collection:
        class: Symfony\Component\ObjectMapper\Transform\MapCollection
        arguments:
            - '@object_mapper'

I didn't know how to add tests for this, so any suggestion is welcome :)

All credit goes to @soyuka who gave the idea in the Symfony Slack !

Copy link
Contributor

@soyuka soyuka left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

missing a test in the framework bundle

->tag('object_mapper.transform_callable')
->args([
service('object_mapper'),
])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should probably add an alias to MapCollection::class so that we can use it instead of the service name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants