Skip to content

Commit 450d891

Browse files
committed
Merge branch '7.3' into 7.4
* 7.3: Minor tweaks [ObjectMapper] target method attribute
2 parents 87503c6 + 14b4809 commit 450d891

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

object_mapper.rst

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,26 @@ your DTOs/Entities, you can implement a custom mapping strategy using the
691691
This allows defining mapping rules within dedicated mapper services, similar
692692
to the approach used by libraries like MapStruct in the Java ecosystem.
693693

694+
.. note::
695+
696+
Symfony's built-in ``#[Map]`` attribute only supports ``TARGET_CLASS`` and
697+
``TARGET_PROPERTY`` targets. If you want to use ``#[Map]`` on methods (as in
698+
the MapStruct-like example below), create a custom attribute that extends
699+
Symfony's ``Map`` attribute and adds ``TARGET_METHOD`` support::
700+
701+
// src/ObjectMapper/Attribute/Map.php
702+
namespace App\ObjectMapper\Attribute;
703+
704+
use Symfony\Component\ObjectMapper\Attribute\Map as BaseMap;
705+
706+
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
707+
class Map extends BaseMap
708+
{
709+
}
710+
711+
Then, use this custom ``App\ObjectMapper\Attribute\Map`` attribute instead of
712+
Symfony's built-in one in your mapper classes.
713+
694714
First, create your custom metadata factory. The following example reads mapping
695715
rules defined via ``#[Map]`` attributes on a dedicated mapper service class,
696716
specifically on its ``map`` method for property mappings and on the class itself
@@ -753,14 +773,15 @@ for the source-to-target relationship::
753773
Next, define your mapper service class. This class implements ``ObjectMapperInterface``
754774
but typically delegates the actual mapping back to a standard ``ObjectMapper``
755775
instance configured with the custom metadata factory. Mapping rules are defined
756-
using ``#[Map]`` attributes on this class and its ``map`` method::
776+
using your custom ``#[Map]`` attribute (not Symfony's built-in one) on this class
777+
and its ``map`` method::
757778

758779
namespace App\ObjectMapper;
759780

760781
use App\Dto\LegacyUser;
761782
use App\Dto\UserDto;
783+
use App\ObjectMapper\Attribute\Map;
762784
use App\ObjectMapper\Metadata\MapStructMapperMetadataFactory;
763-
use Symfony\Component\ObjectMapper\Attribute\Map;
764785
use Symfony\Component\ObjectMapper\ObjectMapper;
765786
use Symfony\Component\ObjectMapper\ObjectMapperInterface;
766787

0 commit comments

Comments
 (0)