createFromContext example

static::assertSame($data['mainVariantId']$result['mainVariantId']);
        static::assertSame($data['configuratorGroupConfig']$result['configuratorGroupConfig']);
    }

    public function testEncodeThrowExceptionOnWrongField(): void
    {
        $field = new JsonField('variant_listing_config', 'variantListingConfig');
        $existence = new EntityExistence('test', ['someId' => 'foo'], true, false, false, []);
        $keyPair = new KeyValuePair('someId', null, false);
        $bag = new WriteParameterBag(
            new ProductDefinition(),
            WriteContext::createFromContext(Context::createDefaultContext()),
            '',
            new WriteCommandQueue()
        );

        try {
            iterator_to_array($this->serializer->encode($field$existence$keyPair$bag));
            static::fail('encode with incorrect field');
        } catch (DataAbstractionLayerException $e) {
            static::assertSame(DataAbstractionLayerException::INVALID_FIELD_SERIALIZER_CODE, $e->getErrorCode());
        }
    }

    
$this->getContainer()->get(SetNullOnDeleteParentDefinition::class),
            [
                [
                    'id' => $ids->get('parent'),
                    'productNumber' => Uuid::randomHex(),
                    'name' => 'test',
                    'setNulls' => [
                        ['id' => $ids->get('child'), 'name' => 'test child'],
                    ],
                ],
            ],
            WriteContext::createFromContext(Context::createDefaultContext())
        );

        $parents = $this->connection->fetchAllAssociative('SELECT * FROM set_null_on_delete_parent');
        static::assertCount(1, $parents);

        $children = $this->connection->fetchAllAssociative('SELECT * FROM set_null_on_delete_child');
        static::assertCount(1, $children);

        $result = $this->writer->delete(
            $this->getContainer()->get(SetNullOnDeleteParentDefinition::class),
            [
                [

    final public static function encodePrimaryKey(EntityDefinition $definition, array $primaryKey, Context $context): array
    {
        $fields = $definition->getPrimaryKeys();

        $mapped = [];

        $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);

            
'zipcode' => '48624',
                    'city' => 'Schöppingen',
                ],
            ],
        ];

        $this->getContainer()
            ->get(EntityWriter::class)
            ->upsert(
                $this->getContainer()->get(CustomerDefinition::class),
                [$customer],
                WriteContext::createFromContext($this->context)
            );

        return $customerId;
    }
}
/** * @param array<array<int, mixed>> $content */
    private function sync(array $content): void
    {
        $operations = [];
        foreach ($content as $entity => $data) {
            $operations[] = new SyncOperation($entity$entity, 'upsert', $data);
        }

        $this->writer->sync($operations, WriteContext::createFromContext(Context::createDefaultContext()));
    }

    private function getLocaleIdOfSystemLanguage(): string
    {
        return $this->connection
            ->fetchOne(
                'SELECT LOWER(HEX(locale_id)) FROM language WHERE id = UNHEX(:systemLanguageId)',
                ['systemLanguageId' => Defaults::LANGUAGE_SYSTEM]
            );
    }

    
if (\count($behavior->getSkipIndexers())) {
            $context->addExtension(EntityIndexerRegistry::EXTENSION_INDEXER_SKIP, new ArrayEntity(['skips' => $behavior->getSkipIndexers()]));
        }

        if (
            $behavior->getIndexingBehavior() !== null
            && \in_array($behavior->getIndexingBehavior()[EntityIndexerRegistry::DISABLE_INDEXING, EntityIndexerRegistry::USE_INDEXING_QUEUE], true)
        ) {
            $context->addState($behavior->getIndexingBehavior());
        }

        $result = $this->writer->sync($operations, WriteContext::createFromContext($context));

        $writes = EntityWrittenContainerEvent::createWithWrittenEvents($result->getWritten()$context[]);
        $deletes = EntityWrittenContainerEvent::createWithDeletedEvents($result->getDeleted()$context[]);

        if ($deletes->getEvents() !== null) {
            $writes->addEvent(...$deletes->getEvents()->getElements());
        }

        $this->eventDispatcher->dispatch($writes);

        $ids = $this->getWrittenEntities($result->getWritten());

        

class PromotionValidatorTest extends TestCase
{
    private WriteContext $context;

    private PromotionDefinition $promotionDefinition;

    private PromotionDiscountDefinition $discountDefinition;

    protected function setUp(): void
    {
        $this->context = WriteContext::createFromContext(Context::createDefaultContext());

        $this->promotionDefinition = new PromotionDefinition();
        $this->discountDefinition = new PromotionDiscountDefinition();
    }

    /** * This test verifies that we do not allow a promotion that has * been configured to use a code, but the code is empty. * So we set useCodes to TRUE, provide an empty code and expect * a corresponding exception. * * @group promotions */

        $context->getConsole()->progressStart($numberOfItems);

        $payload = [];
        for ($i = 0; $i < $numberOfItems; ++$i) {
            $payload[] = [
                'id' => Uuid::randomHex(),
                'name' => $context->getFaker()->format('productName') . ' Tag',
            ];
        }

        $writeContext = WriteContext::createFromContext($context->getContext());

        foreach (array_chunk($payload, 100) as $chunk) {
            $this->writer->upsert($this->tagDefinition, $chunk$writeContext);
            $context->getConsole()->progressAdvance(\count($chunk));
        }

        $context->getConsole()->progressFinish();
    }
}
'productNumber' => Uuid::randomHex(),
                    'name' => 'test',
                    'manyToOne' => [
                        'id' => $id,
                        'name' => 'test child',
                    ],
                    'cascades' => [
                        ['id' => $id, 'name' => 'test child'],
                    ],
                ],
            ],
            WriteContext::createFromContext(Context::createDefaultContext())
        );

        $parents = $this->connection->fetchAllAssociative('SELECT * FROM delete_cascade_parent');
        static::assertCount(1, $parents);

        $children = $this->connection->fetchAllAssociative('SELECT * FROM delete_cascade_child');
        static::assertCount(1, $children);

        $this->writer->delete(
            $this->getContainer()->get(DeleteCascadeParentDefinition::class),
            [
                [
return OrderDefinition::class;
    }

    public function generate(int $numberOfItems, DemodataContext $context, array $options = []): void
    {
        $this->faker = $context->getFaker();
        $salesChannelIds = $this->connection->fetchFirstColumn('SELECT LOWER(HEX(id)) FROM sales_channel');
        $productIds = $this->connection->fetchFirstColumn('SELECT LOWER(HEX(id)) as id FROM `product` ORDER BY RAND() LIMIT 1000');
        $promotionCodes = $this->connection->fetchFirstColumn('SELECT `code` FROM `promotion` ORDER BY RAND() LIMIT 1000');
        $customerIds = $this->connection->fetchFirstColumn('SELECT LOWER(HEX(id)) as id FROM customer LIMIT 10');
        $tags = $this->getIds('tag');
        $writeContext = WriteContext::createFromContext($context->getContext());

        $context->getConsole()->progressStart($numberOfItems);

        $productLineItems = array_map(
            fn ($productId) => (new LineItem($productId, LineItem::PRODUCT_LINE_ITEM_TYPE, $productId$this->faker->randomDigit() + 1))
                ->setStackable(true)
                ->setRemovable(true),
            $productIds
        );
        $promotionLineItems = array_map(
            function D$promotionCode) {
                
$stockStorage = $this->createMock(StockStorage::class);
        $stockStorage->expects(static::never())->method('alter');

        $stockSubscriber = new OrderStockSubscriber(
            $this->createMock(Connection::class),
            $stockStorage,
            false
        );

        $event = EntityWriteEvent::create(
            WriteContext::createFromContext($context),
            [],
        );

        $stockSubscriber->beforeWriteOrderItems($event);
        $event->success();
    }

    public function testBeforeWriteOnlyReactsToLiveVersions(): void
    {
        $context = Context::createDefaultContext()->createWithVersionId($this->ids->create('version'));

        

#[Package('checkout')] class ShippingMethodValidatorTest extends TestCase
{
    private WriteContext $context;

    private ShippingMethodDefinition $shippingMethodDefinition;

    protected function setUp(): void
    {
        $this->context = WriteContext::createFromContext(Context::createDefaultContext());

        $this->shippingMethodDefinition = new ShippingMethodDefinition();
    }

    /** * @dataProvider shippingMethodTaxProvider */
    public function testShippingMethodValidator(?string $taxType, ?string $taxId, bool $success): void
    {
        $commands = [];
        $commands[] = new InsertCommand(
            

    public function testGetDeletedPrimaryKeys(PostWriteValidationEvent $event, array $assertions): void
    {
        foreach ($assertions as $entity => $ids) {
            static::assertEquals($ids$event->getDeletedPrimaryKeys($entity), \sprintf('Deleted primary keys for entity %s not match', $entity));
        }
    }

    public static function getDeletedPrimaryKeysProvider(): \Generator
    {
        $context = WriteContext::createFromContext(Context::createDefaultContext());

        $ids = new IdsCollection();

        yield 'Test single delete' => [
            new PostWriteValidationEvent($context[self::delete('product', ['id' => $ids->get('p1')])]),
            [
                'product' => [['id' => $ids->get('p1')]],
            ],
        ];

        yield 'Test multi insert' => [
            
$this->getWriter()->insert($definition[$data]$context);

        $data = $this->connection->fetchAllAssociative('SELECT * FROM `_test_nullable_translation`');

        static::assertCount(1, $data);
        static::assertEquals(Uuid::fromHexToBytes($id)$data[0]['_test_nullable_id']);
        static::assertEquals('foobar', $data[0]['system_protected']);
    }

    protected function createWriteContext(): WriteContext
    {
        return WriteContext::createFromContext(Context::createDefaultContext());
    }

    private function getWriter(): EntityWriterInterface
    {
        return $this->getContainer()->get(EntityWriter::class);
    }

    private function getValidationExceptionMessage(WriteException $ex, string $field = 'protected'): string
    {
        $message = '';

        

        static::assertEquals([
            'product_review.written' => 'createReview',
            EntityDeleteEvent::class => 'detectChangeset',
            'product_review.deleted' => 'onReviewDeleted',
        ]$this->productReviewSubscriber->getSubscribedEvents());
    }

    public function testDetectChangesetWithReviewDeleteEvent(): void
    {
        $event = EntityDeleteEvent::create(
            WriteContext::createFromContext(Context::createDefaultContext()),
            [
                new DeleteCommand(
                    new ProductReviewDefinition(),
                    [
                        'id' => 'foo',
                    ],
                    new EntityExistence(ProductReviewDefinition::ENTITY_NAME, ['id' => 'foo'], true, false, false, [])
                ),
            ]
        );

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