KeyValuePair example

/** * @dataProvider serializerProvider */
    public function testSerialize(StringField $field, ?string $value, ?string $expected, bool $expectError, EntityExistence $existence): void
    {
        $field->compile($this->getContainer()->get(DefinitionInstanceRegistry::class));

        $actual = null;
        $exception = null;

        try {
            $kv = new KeyValuePair($field->getPropertyName()$value, true);

            $params = new WriteParameterBag($this->getContainer()->get(ProductDefinition::class), WriteContext::createFromContext(Context::createDefaultContext()), '', new WriteCommandQueue());

            $actual = $this->getContainer()->get(StringFieldSerializer::class)
                ->encode($field$existence$kv$params)->current();
        } catch (\Throwable $e) {
            $exception = $e;
        }

        // error cases         if ($expectError) {
            
static::assertSame(10.0, $price->getListPrice()->getGross());
        static::assertSame(10.0, $price->getRegulationPrice()->getNet());
        static::assertSame(10.0, $price->getRegulationPrice()->getGross());

        static::assertNull($price->getPercentage());
    }

    private function encode(array $data): string
    {
        $field = new PriceField('test', 'test');
        $existence = new EntityExistence('test', ['someId' => true], true, false, false, []);
        $keyPair = new KeyValuePair('someId', $data, false);
        $bag = new WriteParameterBag(
            $this->getContainer()->get(ProductDefinition::class),
            WriteContext::createFromContext(Context::createDefaultContext()),
            '',
            new WriteCommandQueue()
        );

        $data = iterator_to_array($this->serializer->encode($field$existence$keyPair$bag), true);

        return $data['test'];
    }
}
$kvPair = $stack->pop($nestedField->getPropertyName());

            if ($kvPair === null) {
                // The writer updates the whole field, so there is no possibility to update                 // "some" fields. To enable a merge, we have to respect the $existence state                 // for correct constraint validation. In addition the writer has to be rewritten                 // in order to handle merges.                 if (!$nestedField->is(Required::class)) {
                    continue;
                }

                $kvPair = new KeyValuePair($nestedField->getPropertyName(), null, true);
            }

            $nestedParams = new WriteParameterBag(
                $parameters->getDefinition(),
                $parameters->getContext(),
                $parameters->getPath() . '/' . $field->getPropertyName(),
                $parameters->getCommandQueue()
            );

            /* * Don't call `encode()` or `validateIfNeeded()` on nested JsonFields if they are not typed. * This also allows directly storing non-array values like strings. */
new JsonField('data', 'data', []['foo' => ['bar' => 'baz']]), null, Json::encode(['foo' => ['bar' => 'baz']])],
        ];
    }

    /** * @dataProvider encodeProvider */
    public function testEncode(JsonField $field$input$expected): void
    {
        $field->compile($this->getContainer()->get(DefinitionInstanceRegistry::class));

        $kvPair = new KeyValuePair('password', $input, true);
        $actual = $this->serializer->encode($field$this->existence, $kvPair$this->parameters)->current();

        static::assertEquals($expected$actual);
    }

    public static function decodeProvider(): array
    {
        return [
            [new JsonField('data', 'data'), Json::encode(['foo' => 'bar'])['foo' => 'bar']],

            [new JsonField('data', 'data'), Json::encode(['foo' => 1])['foo' => 1]],
            [
throw new InvalidSerializerFieldException(SeoUrlAssociationField::class$field);
        }

        $seoUrls = $data->getValue();
        foreach ($seoUrls as $i => $seoUrl) {
            $seoUrl['routeName'] = $field->getRouteName();
            $seoUrl['isModified'] = true;

            $seoUrls[$i] = $seoUrl;
        }

        $data = new KeyValuePair($data->getKey()$seoUrls$data->isRaw());

        return parent::encode($field$existence$data$parameters);
    }
}
/** * @dataProvider stringFieldDataProvider * * @param bool|string|null $input * @param Flag[] $flags */
    public function testStringFieldSerializer(string $type$input, ?string $expected, array $flags = []): void
    {
        $serializer = $this->getContainer()->get(StringFieldSerializer::class);

        $name = 'string_' . Uuid::randomHex();
        $data = new KeyValuePair($name$input, false);

        if ($type === 'writeException') {
            $this->expectException(WriteConstraintViolationException::class);

            try {
                $serializer->encode(
                    $this->getStringField($name$flags),
                    EntityExistence::createEmpty(),
                    $data,
                    $this->getWriteParameterBagMock()
                )->current();
            }
$this->definitionInstanceRegistry = $this->createMock(DefinitionInstanceRegistry::class);
        $this->validator = $this->createMock(ValidatorInterface::class);

        $this->intervalFieldSerializer = new CronIntervalFieldSerializer(
            $this->validator,
            $this->definitionInstanceRegistry
        );
    }

    public function testEncodeMethodWithCorrectDataWillReturnCronIntervalString(): void
    {
        $data = new KeyValuePair('key', new CronExpression(self::COMPLEX_CRON), false);

        $cronExpression = $this->intervalFieldSerializer->encode(
            new CronIntervalField('fake', 'fake'),
            $this->createStub(EntityExistence::class),
            $data,
            $this->createMock(WriteParameterBag::class)
        )->current();

        static::assertIsString($cronExpression);
        static::assertEquals(self::COMPLEX_CRON, $cronExpression);
    }

    
public function testEncodeNotPasswordField(): void
    {
        if (Feature::isActive('v6.6.0.0')) {
            static::expectException(DataAbstractionLayerException::class);
        } else {
            static::expectException(InvalidSerializerFieldException::class);
        }

        $existence = new EntityExistence('product', [], false, false, false, []);
        $field = new StringField('password', 'password');

        $kv = new KeyValuePair($field->getPropertyName(), null, true);

        $params = new WriteParameterBag(new ProductDefinition(), WriteContext::createFromContext(Context::createDefaultContext()), '', new WriteCommandQueue());

        $this->serializer->encode($field$existence$kv$params)->getReturn();
    }

    /** * @dataProvider encodeProvider * * @param array<int, Constraint> $constraints */
    
new \DateTime('2020-05-16 00:00:00', new \DateTimeZone('UTC')),
                ],
            ],
        ];
    }

    /** * @dataProvider serializerProvider */
    public function testSerializer($input): void
    {
        $kvPair = new KeyValuePair('date', $input[0], true);
        $encoded = $this->serializer->encode($this->field, $this->existence, $kvPair$this->parameters)->current();
        $decoded = $this->serializer->decode($this->field, $encoded);

        static::assertEquals($input[1]$decoded, 'Output should be ' . print_r($input[1], true));
    }

    public function testSerializerValidatesRequiredField(): void
    {
        $kvPair = new KeyValuePair('date', null, true);
        $this->field->removeFlag(Required::class);

        
foreach ($primaryKey as $key => $value) {
                /** * Primary key fields are always storage aware. * * @var Field&StorageAware $field */
                $field = $definition->getFields()->get($key);

                $mappedBytes[$field->getStorageName()] = $field->getSerializer()->encode(
                    $field,
                    EntityExistence::createForEntity($definition->getEntityName()[$key => $value]),
                    new KeyValuePair($key$value, true),
                    $parameters,
                )->current();
            }

            $existence = $this->gateway->getExistence($definition$mappedBytes[]$commandQueue);

            if ($existence->exists()) {
                $commandQueue->add($definitionnew DeleteCommand($definition$mappedBytes$existence));

                continue;
            }

            
/** * @param array<string, mixed> $originalData */
    public function __construct(array $originalData)
    {
        if (\array_key_exists('extensions', $originalData)) {
            $originalData = array_merge($originalData$originalData['extensions']);
            unset($originalData['extensions']);
        }

        foreach ($originalData as $key => $value) {
            $this->data[$key] = new KeyValuePair($key$value, true);
        }
    }

    public function has(string $key): bool
    {
        return isset($this->data[$key]);
    }

    public function pop(string $key): ?KeyValuePair
    {
        if (!$this->has($key)) {
            
function Dstring $pkFieldStorageName) use ($definition$existence$parameters): mixed {
                        $pkFieldValue = $existence->getPrimaryKey()[$pkFieldStorageName];
                        /** @var Field|null $field */
                        $field = $definition->getFields()->getByStorageName($pkFieldStorageName);
                        if (!$field) {
                            return $pkFieldValue;
                        }

                        return $field->getSerializer()->encode(
                            $field,
                            $existence,
                            new KeyValuePair($field->getPropertyName()$pkFieldValue, true),
                            $parameters,
                        )->current();
                    },
                    array_keys($existence->getPrimaryKey()),
                ),
            );

            $jsonUpdateCommand = new JsonUpdateCommand(
                $definition,
                $storageName,
                $attributes,
                

    use KernelTestBehaviour;

    /** * @dataProvider validTimeZones */
    public function testTimeZoneSerializerTest(string $timeZone): void
    {
        $serializer = $this->getContainer()->get(TimeZoneFieldSerializer::class);

        $name = 'string_' . Uuid::randomHex();
        $data = new KeyValuePair($name$timeZone, false);

        $val = $serializer->encode(
            new TimeZoneField($name$name),
            new EntityExistence(null, [], true, false, false, []),
            $data,
            $this->createMock(WriteParameterBag::class)
        );

        $array = iterator_to_array($val);

        static::assertSame($timeZone$array[$name]);
    }
 \Generator {
        if (!$field instanceof TranslationsAssociationField) {
            throw DataAbstractionLayerException::invalidSerializerField(TranslationsAssociationField::class$field);
        }

        $value = $data->getValue();

        if ($value === null) {
            $value = [
                $parameters->getContext()->getContext()->getLanguageId() => [],
            ];
            $data = new KeyValuePair($data->getKey()$value$data->isRaw());

            return $this->map($field$data$parameters$existence);
        }

        $data = new KeyValuePair($data->getKey()$value$data->isRaw());

        return $this->map($field$data$parameters$existence);
    }

    public function decode(Field $field, mixed $value): never
    {
        
$existence = new EntityExistence($definition->getEntityName()[], true, false, false, []);

        $params = new WriteParameterBag($definition, WriteContext::createFromContext($context), '', new WriteCommandQueue());

        foreach ($fields as $field) {
            if ($field instanceof VersionField || $field instanceof ReferenceVersionField) {
                $value = $context->getVersionId();
            } else {
                $value = $primaryKey[$field->getPropertyName()];
            }

            $kvPair = new KeyValuePair($field->getPropertyName()$value, true);

            $encoded = $field->getSerializer()->encode($field$existence$kvPair$params);

            foreach ($encoded as $key => $value) {
                $mapped[$key] = $value;
            }
        }

        return $mapped;
    }

    
Home | Imprint | This part of the site doesn't use cookies.