deserialize example

public function __construct(private readonly EntityRepository $salutationRepository)
    {
    }

    /** * @param array|\Traversable $entity * * @return array|\Traversable */
    public function deserialize(Config $config, EntityDefinition $definition$entity)
    {
        $deserialized = parent::deserialize($config$definition$entity);

        $deserialized = \is_array($deserialized) ? $deserialized : iterator_to_array($deserialized);

        if (!isset($deserialized['id']) && isset($deserialized['salutationKey'])) {
            $id = $this->getSalutationId($deserialized['salutationKey']);

            // if we dont find it by salutationKey, only set the id to the fallback if we dont have any other data             if (!$id && \count($deserialized) === 1) {
                $id = $this->getSalutationId('not_specified');
                unset($deserialized['salutationKey']);
            }

            
public function deserialize(Config $config, Field $toOne$records)
    {
        if (!$toOne instanceof ManyToOneAssociationField && !$toOne instanceof OneToOneAssociationField) {
            throw new \InvalidArgumentException('Expected *ToOneField');
        }

        $definition = $toOne->getReferenceDefinition();
        $entitySerializer = $this->serializerRegistry->getEntity($definition->getEntityName());
        /** @var \Traversable<mixed> $records */
        $records = $this->primaryKeyResolver->resolvePrimaryKeyFromUpdatedBy($config$definition$records);

        $result = $entitySerializer->deserialize($config$definition$records);

        if (!\is_array($result)) {
            $result = iterator_to_array($result);
        }
        if (empty($result)) {
            return null;
        }

        return $result;
    }

    
foreach ($entity as $key => $value) {
            if ($key === '_error' && $value instanceof \Throwable) {
                yield '_error' => $value;
            }

            $field = $fields->get($key);
            if ($field === null) {
                continue;
            }

            $serializer = $this->serializerRegistry->getFieldSerializer($field);
            $value = $serializer->deserialize($config$field$value);

            if ($value === null) {
                continue;
            }

            if (is_iterable($value) && !\is_array($value)) {
                $value = iterator_to_array($value);
            }

            // ToOneSerializer may return records with errors             if (\is_array($value) && isset($value['_error']) && $value['_error'] instanceof \Throwable) {
                
 {
    }

    /** * @param array<mixed>|\Traversable<mixed> $entity * * @return array<mixed>|\Traversable<mixed> */
    public function deserialize(Config $config, EntityDefinition $definition$entity)
    {
        $entity = \is_array($entity) ? $entity : iterator_to_array($entity);
        $deserialized = parent::deserialize($config$definition$entity);
        $deserialized = \is_array($deserialized) ? $deserialized : iterator_to_array($deserialized);

        $url = $entity['url'] ?? null;

        if (empty($url)) {
            return $deserialized;
        }

        if (!filter_var($url, \FILTER_VALIDATE_URL)) {
            $deserialized['_error'] = new InvalidMediaUrlException($url);

            
$definition,
            $updateByFieldPath,
            $criteria
        );

        if (!$updateByField) {
            return $record;
        }

        if ($field = $definition->getField($updateByField)) {
            // deserialize for bool, date, int fields...             $updateByValue = $this->fieldSerializer->deserialize($config$field$updateByValue);
        }

        $criteria->addFilter(new EqualsFilter(
            $updateByField,
            $updateByValue
        ));

        $repository = $this->definitionInstanceRegistry->getRepository($definition->getEntityName());
        $id = $repository->searchIds($criteria, Context::createDefaultContext())->firstId();

        if ($id) {
            
public function testIntField(): void
    {
        $intField = new IntField('foo', 'foo');

        $fieldSerializer = new FieldSerializer();
        $config = new Config([][][]);

        static::assertNull($this->first($fieldSerializer->serialize($config$intField, null)));
        static::assertSame('0', $this->first($fieldSerializer->serialize($config$intField, 0)));
        static::assertSame('3123412344321', $this->first($fieldSerializer->serialize($config$intField, 3123412344321)));

        static::assertEmpty($fieldSerializer->deserialize($config$intField, ''));
        static::assertSame(0, $fieldSerializer->deserialize($config$intField, '0'));
        static::assertSame(3123412344321, $fieldSerializer->deserialize($config$intField, '3123412344321'));
    }

    public function testPriceField(): void
    {
        $priceField = new PriceField('price', 'price');

        $fieldSerializer = new PriceSerializer($this->getContainer()->get('currency.repository'));
        $config = new Config([][][]);

        
static::assertSame($product->getId()$serialized['id']);
        static::assertSame($product->getTranslations()->first()->getName()$serialized['translations']['DEFAULT']['name']);
        static::assertSame((string) $product->getStock()$serialized['stock']);
        static::assertSame($product->getProductNumber()$serialized['productNumber']);
        static::assertSame('1', $serialized['active']);
        static::assertStringContainsString('shopware-logo.png', $serialized['cover']['media']['url']);
        static::assertStringContainsString('shopware-icon.png', $serialized['media']);
        static::assertStringContainsString('shopware-background.png', $serialized['media']);
        static::assertStringNotContainsString('shopware-logo.png', $serialized['media']);

        $deserialized = iterator_to_array($serializer->deserialize(new Config([][][])$productDefinition$serialized));

        static::assertSame($product->getId()$deserialized['id']);
        static::assertSame($product->getTranslations()->first()->getName()$deserialized['translations'][Defaults::LANGUAGE_SYSTEM]['name']);
        static::assertSame($product->getStock()$deserialized['stock']);
        static::assertSame($product->getProductNumber()$deserialized['productNumber']);
        static::assertSame($product->getActive()$deserialized['active']);
    }

    public function testSupportsOnlyProduct(): void
    {
        $serializer = new ProductSerializer(
            


    public function supports(string $entity): bool
    {
        return $entity === PromotionIndividualCodeDefinition::ENTITY_NAME;
    }

    public function deserialize(Config $config, EntityDefinition $definition$entity)
    {
        $entity = \is_array($entity) ? $entity : iterator_to_array($entity);

        $deserialized = parent::deserialize($config$definition$entity);

        $deserialized = \is_array($deserialized) ? $deserialized : iterator_to_array($deserialized);

        // set promotion id from promotion name if possible         if (empty($deserialized['promotion']['id']) && isset($entity['promotion']['translations']['DEFAULT']['name'])) {
            $promoId = $this->getPromoIdFromName($entity['promotion']['translations']['DEFAULT']['name']);

            if ($promoId) {
                $deserialized['promotion']['id'] = $promoId;
            }
        }

        
$stamps = $this->decodeStamps($encodedEnvelope);
        $stamps[] = new SerializedMessageStamp($encodedEnvelope['body']);

        $serializerStamp = $this->findFirstSerializerStamp($stamps);

        $context = $this->context;
        if (null !== $serializerStamp) {
            $context = $serializerStamp->getContext() + $context;
        }

        try {
            $message = $this->serializer->deserialize($encodedEnvelope['body']$encodedEnvelope['headers']['type']$this->format, $context);
        } catch (ExceptionInterface $e) {
            throw new MessageDecodingFailedException('Could not decode message: '.$e->getMessage()$e->getCode()$e);
        }

        return new Envelope($message$stamps);
    }

    public function encode(Envelope $envelope): array
    {
        $context = $this->context;
        /** @var SerializerStamp|null $serializerStamp */
        
public function testSimple(): void
    {
        $this->createCountry();

        $config = new Config([][][]);
        $country = [
            'iso' => 'XX',
        ];

        $serialized = iterator_to_array($this->serializer->serialize($config$this->countryRepository->getDefinition()$country));

        $deserialized = iterator_to_array($this->serializer->deserialize($config$this->countryRepository->getDefinition()$serialized));

        static::assertSame($this->countryId, $deserialized['id']);
    }

    public function testSupportsOnlyCountry(): void
    {
        $serializer = new CountrySerializer($this->getContainer()->get('country.repository'));

        $definitionRegistry = $this->getContainer()->get(DefinitionInstanceRegistry::class);
        foreach ($definitionRegistry->getDefinitions() as $definition) {
            $entity = $definition->getEntityName();

            
$propertyNormalizer = new PropertyNormalizer(null, null, $extractor);
        $serializer = new Serializer([
            new ArrayDenormalizer(),
            new MimeMessageNormalizer($propertyNormalizer),
            new ObjectNormalizer(null, null, null, $extractor),
            $propertyNormalizer,
        ][new JsonEncoder()]);

        $serialized = $serializer->serialize($e, 'json');
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));

        $n = $serializer->deserialize($serialized, Message::class, 'json');
        $this->assertEquals($expected$n);

        $serialized = $serializer->serialize($e, 'json');
        $this->assertStringMatchesFormat($expectedJsonjson_encode(json_decode($serialized), \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
    }
}
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
        $discriminator = new ClassDiscriminatorFromClassMetadata($classMetadataFactory);

        $normalizers = [new StructNormalizer()new ObjectNormalizer($classMetadataFactory, null, null, null, $discriminator)new ArrayDenormalizer()];
        $serializer = new Serializer($normalizers[new JsonEncoder()]);

        $context = Context::createDefaultContext();

        $context->addExtension('foo', new ArrayEntity());

        $serialized = $serializer->serialize($context, 'json');
        $deserialized = $serializer->deserialize($serialized, Context::class, 'json');

        static::assertInstanceOf(Context::class$deserialized);

        static::assertEmpty($deserialized->getVars()['extensions']);
    }
}
static::assertNotEmpty($serialized);

        $assignedProducts = $crossSelling->getAssignedProducts();
        $assignedProducts->sort(fn (ProductCrossSellingAssignedProductsEntity $a, ProductCrossSellingAssignedProductsEntity $b) => $a->getPosition() <=> $b->getPosition());
        $productsIds = $assignedProducts->map(fn (ProductCrossSellingAssignedProductsEntity $assignedProductsEntity) => $assignedProductsEntity->getProductId());

        static::assertSame($crossSelling->getId()$serialized['id']);
        static::assertSame($crossSelling->getProductId()$serialized['productId']);
        static::assertSame(implode('|', $productsIds)$serialized['assignedProducts']);

        $deserialized = $serializer->deserialize(new Config([][][])$productCrossSellingDefinition$serialized);

        static::assertSame($crossSelling->getId()$deserialized['id']);
        static::assertSame($crossSelling->getProductId()$deserialized['productId']);
        static::assertSame(array_values($productsIds)array_column($deserialized['assignedProducts'], 'productId'));
    }

    private function getProductCrossSelling(): ProductCrossSellingEntity
    {
        $ids = new TestDataCollection();

        $data = [
            (
public function __construct(private readonly EntityRepository $countryRepository)
    {
    }

    /** * @param array|\Traversable $entity * * @return array|\Traversable */
    public function deserialize(Config $config, EntityDefinition $definition$entity)
    {
        $deserialized = parent::deserialize($config$definition$entity);

        $deserialized = \is_array($deserialized) ? $deserialized : iterator_to_array($deserialized);

        if (!isset($deserialized['id']) && isset($deserialized['iso'])) {
            $id = $this->getCountryId($deserialized['iso']);

            if ($id) {
                $deserialized['id'] = $id;
            }
        }

        
$before = new IndexerOffset(
            ['foo', 'bar'],
            ['product', 'product_manufacturer'],
            (new \DateTime())->getTimestamp()
        );
        $data = $serialize->serialize(
            $before,
            'json'
        );

        $after = $serialize->deserialize($data, IndexerOffset::class, 'json', [
            AbstractNormalizer::DEFAULT_CONSTRUCTOR_ARGUMENTS => [
                IndexerOffset::class => ['mappingDefinitions' => []],
            ],
        ]);

        static::assertEquals($before$after);
    }
}
Home | Imprint | This part of the site doesn't use cookies.