1+ <?php
2+
3+ /*
4+ * This file is part of the Sylius package.
5+ *
6+ * (c) Sylius Sp. z o.o.
7+ *
8+ * For the full copyright and license information, please view the LICENSE
9+ * file that was distributed with this source code.
10+ */
11+
12+ declare (strict_types=1 );
13+
14+ namespace Sylius \ImportExport \Denormalizer ;
15+
16+ use Doctrine \ORM \EntityManagerInterface ;
17+ use Symfony \Component \PropertyAccess \PropertyAccessorInterface ;
18+ use Symfony \Component \Serializer \SerializerInterface ;
19+
20+ class DefaultResourceDenormalizer implements ResourceDenormalizerInterface
21+ {
22+ public function __construct (
23+ private SerializerInterface $ serializer ,
24+ private PropertyAccessorInterface $ propertyAccessor ,
25+ private RelationResolverInterface $ relationResolver ,
26+ private EntityManagerInterface $ entityManager ,
27+ ) {
28+ }
29+
30+ public function denormalize (array $ data , string $ resourceClass ): object
31+ {
32+ $ metadata = $ this ->entityManager ->getClassMetadata ($ resourceClass );
33+ $ processedData = [];
34+
35+ foreach ($ data as $ field => $ value ) {
36+ if (null === $ value || '' === $ value ) {
37+ continue ;
38+ }
39+
40+ if ($ metadata ->hasAssociation ($ field )) {
41+ $ associationMapping = $ metadata ->getAssociationMapping ($ field );
42+ $ targetEntity = $ associationMapping ['targetEntity ' ];
43+
44+ if ($ metadata ->isCollectionValuedAssociation ($ field )) {
45+ $ identifiers = is_array ($ value ) ? $ value : explode (', ' , (string ) $ value );
46+ $ processedData [$ field ] = $ this ->relationResolver ->resolveCollection (
47+ $ targetEntity ,
48+ array_filter (array_map ('trim ' , $ identifiers ))
49+ );
50+ } else {
51+ $ processedData [$ field ] = $ this ->relationResolver ->resolveEntity ($ targetEntity , $ value );
52+ }
53+ } else {
54+ $ processedData [$ field ] = $ value ;
55+ }
56+ }
57+
58+ return $ this ->serializer ->denormalize ($ processedData , $ resourceClass );
59+ }
60+
61+ public function supports (string $ resourceClass ): bool
62+ {
63+ return true ; // Default denormalizer supports all resources
64+ }
65+ }
0 commit comments