Skip to content

Conversation

@romanandcode
Copy link

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

According to the documentation, \Symfony\Component\ObjectMapper\Attribute\Map can be applied to methods:

namespace App\ObjectMapper;

use App\Dto\LegacyUser;
use App\Dto\UserDto;
use App\ObjectMapper\Metadata\MapStructMapperMetadataFactory;
use Symfony\Component\ObjectMapper\Attribute\Map;
use Symfony\Component\ObjectMapper\ObjectMapper;
use Symfony\Component\ObjectMapper\ObjectMapperInterface;

// define the source-to-target mapping at the class level
#[Map(source: LegacyUser::class, target: UserDto::class)]
class LegacyUserMapper implements ObjectMapperInterface
{
    private readonly ObjectMapperInterface $objectMapper;

    // inject the standard ObjectMapper or necessary dependencies
    public function __construct(?ObjectMapperInterface $objectMapper = null)
    {
        // create an ObjectMapper instance configured with *this* mapper's rules
        $metadataFactory = new MapStructMapperMetadataFactory(self::class);
        $this->objectMapper = $objectMapper ?? new ObjectMapper($metadataFactory);
    }

    // define property-specific mapping rules on the map method
    #[Map(source: 'fullName', target: 'name')] // Map LegacyUser::fullName to UserDto::name
    #[Map(source: 'creationTimestamp', target: 'registeredAt', transform: [\DateTimeImmutable::class, 'createFromFormat'])]
    #[Map(source: 'status', if: false)] // Ignore the 'status' property from LegacyUser
    public function map(object $source, object|string|null $target = null): object
    {
        // delegate the actual mapping to the configured ObjectMapper
        return $this->objectMapper->map($source, $target);
    }
}

But it causes an exception:

Attribute \"Symfony\\Component\\ObjectMapper\\Attribute\\Map\" cannot target method (allowed targets: class, property)

This PR makes \Symfony\Component\ObjectMapper\Attribute\Map applicable to methods.

@nicolas-grekas
Copy link
Member

I would expect a test case where mapping on methods is exercised.
/cc @soyuka WDYT?

@soyuka
Copy link
Contributor

soyuka commented Nov 25, 2025

Mhh indeed the doc is slightly misleading, especially that the metadata factory returns a Mapping instance.

Either we revise the documentation and change the Map attribute of this section to a user-land namespace, or we add this TARGET_METHOD although the problem is that the ObjectMapper doesn't look at methods (only properties) therefore I'm afraid it would also be misleading.

@nicolas-grekas
Copy link
Member

Shall we close then? Doc PR instead?

@OskarStark OskarStark changed the title [ObjectMapper] Add Attribute::TARGET_METHOD to Map [ObjectMapper] Add Attribute::TARGET_METHOD to Map Dec 7, 2025
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.

4 participants