From 4437f206af035a28ec6ab685b68dd1dc509c94bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan=20B=C3=B6hmer?= Date: Mon, 13 Mar 2023 00:44:05 +0100 Subject: [PATCH] Allow alternative names for import for parts --- src/Serializer/PartNormalizer.php | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/Serializer/PartNormalizer.php b/src/Serializer/PartNormalizer.php index 54846684..1be29c9e 100644 --- a/src/Serializer/PartNormalizer.php +++ b/src/Serializer/PartNormalizer.php @@ -30,8 +30,13 @@ use Symfony\Component\Serializer\Normalizer\ObjectNormalizer; class PartNormalizer implements NormalizerInterface, DenormalizerInterface, CacheableSupportsMethodInterface { + private const DENORMALIZE_KEY_MAPPING = [ + 'notes' => 'comment', + 'quantity' => 'instock', + 'amount' => 'instock', + ]; - private NormalizerInterface $normalizer; + private ObjectNormalizer $normalizer; private StructuralElementFromNameDenormalizer $locationDenormalizer; public function __construct(ObjectNormalizer $normalizer, StructuralElementFromNameDenormalizer $locationDenormalizer) @@ -68,8 +73,23 @@ class PartNormalizer implements NormalizerInterface, DenormalizerInterface, Cach return is_array($data) && is_a($type, Part::class, true); } + private function normalizeKeys(array &$data): array + { + //Rename keys based on the mapping, while leaving the data untouched + foreach ($data as $key => $value) { + if (isset(self::DENORMALIZE_KEY_MAPPING[$key])) { + $data[self::DENORMALIZE_KEY_MAPPING[$key]] = $value; + unset($data[$key]); + } + } + + return $data; + } + public function denormalize($data, string $type, string $format = null, array $context = []) { + $this->normalizeKeys($data); + $object = $this->normalizer->denormalize($data, $type, $format, $context); if (!$object instanceof Part) {