1616use ApiPlatform \Doctrine \Odm \State \Options as OdmOptions ;
1717use ApiPlatform \Doctrine \Orm \State \Options ;
1818use ApiPlatform \Metadata \Operation ;
19+ use ApiPlatform \Metadata \Util \CloneTrait ;
1920use ApiPlatform \State \Pagination \ArrayPaginator ;
2021use ApiPlatform \State \Pagination \PaginatorInterface ;
2122use ApiPlatform \State \ProviderInterface ;
2728 */
2829final class ObjectMapperProvider implements ProviderInterface
2930{
31+ use CloneTrait;
32+
3033 /**
31- * @param ProviderInterface<mixed > $decorated
34+ * @param ProviderInterface<object > $decorated
3235 */
3336 public function __construct (
34- private readonly ObjectMapperInterface $ objectMapper ,
37+ private readonly ? ObjectMapperInterface $ objectMapper ,
3538 private readonly ProviderInterface $ decorated ,
3639 ) {
3740 }
@@ -40,10 +43,11 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
4043 {
4144 $ data = $ this ->decorated ->provide ($ operation , $ uriVariables , $ context );
4245
43- if (!\is_object ($ data )) {
46+ if (!$ this -> objectMapper || ! \is_object ($ data )) {
4447 return $ data ;
4548 }
4649
50+ $ request = $ context ['request ' ] ?? null ;
4751 $ entityClass = null ;
4852 if (($ options = $ operation ->getStateOptions ()) && $ options instanceof Options && $ options ->getEntityClass ()) {
4953 $ entityClass = $ options ->getEntityClass ();
@@ -53,14 +57,21 @@ public function provide(Operation $operation, array $uriVariables = [], array $c
5357 $ entityClass = $ options ->getDocumentClass ();
5458 }
5559
56- if (!$ entityClass || !(new \ReflectionClass ($ entityClass ))->getAttributes (Map::class)) {
60+ $ entityClass ??= $ data ::class;
61+
62+ if (!(new \ReflectionClass ($ entityClass ))->getAttributes (Map::class)) {
5763 return $ data ;
5864 }
5965
6066 if ($ data instanceof PaginatorInterface) {
61- return new ArrayPaginator (array_map (fn ($ v ) => $ this ->objectMapper ->map ($ v ), iterator_to_array ($ data )), 0 , \count ($ data ));
67+ $ data = new ArrayPaginator (array_map (fn ($ v ) => $ this ->objectMapper ->map ($ v ), iterator_to_array ($ data )), 0 , \count ($ data ));
68+ } else {
69+ $ data = $ this ->objectMapper ->map ($ data );
6270 }
6371
64- return $ this ->objectMapper ->map ($ data );
72+ $ request ?->attributes->set ('data ' , $ data );
73+ $ request ?->attributes->set ('previous_data ' , $ this ->clone ($ data ));
74+
75+ return $ data ;
6576 }
6677}
0 commit comments