EntityWriteResult example

$this->appendNewResponse(new Response(200));

        $id = Uuid::randomHex();

        $event = new EntityWrittenContainerEvent(
            $context,
            new NestedEventCollection([
                new EntityWrittenEvent(
                    ProductDefinition::ENTITY_NAME,
                    [
                        new EntityWriteResult(
                            $id,
                            [
                                'id' => $id,
                                'name' => 'testProduct',
                                'productNumber' => 'SWC-1000',
                                'stock' => 100,
                                'manufacturer' => [
                                    'name' => 'app creator',
                                ],
                                'price' => [
                                    [
                                        
static::assertEquals($expectedProperties$properties);
    }

    public function testRefresh(): void
    {
        $c = $this->getContainer()->get(Connection::class);
        static::assertEmpty($c->fetchAllAssociative('SELECT `index` FROM `admin_elasticsearch_index_task`'));

        $this->registry->refresh(new EntityWrittenContainerEvent(Context::createDefaultContext()new NestedEventCollection([
            new EntityWrittenEvent('promotion', [
                new EntityWriteResult(
                    'c1a28776116d4431a2208eb2960ec340',
                    [],
                    'promotion',
                    EntityWriteResult::OPERATION_INSERT
                ),
            ], Context::createDefaultContext()),
        ])[]));

        $index = $c->fetchOne('SELECT `index` FROM `admin_elasticsearch_index_task`');

        static::assertNotFalse($index);

        
$notAllowedPermissions
        ));
    }

    private function getEntityWrittenEvent(string $entityId): EntityWrittenEvent
    {
        $context = Context::createDefaultContext();

        return new EntityWrittenEvent(
            ProductDefinition::ENTITY_NAME,
            [
                new EntityWriteResult(
                    $entityId,
                    [],
                    ProductDefinition::ENTITY_NAME,
                    EntityWriteResult::OPERATION_DELETE,
                    null,
                    null
                ),
            ],
            $context
        );
    }
}


        $payload = $writeResult->getPayload();
        foreach ($translationResults as $translationResult) {
            $payload = array_merge($payload$this->getMergeableTranslationPayload($translationResult));
        }

        if (empty($payload)) {
            return null;
        }

        return new EntityWriteResult(
            $writeResult->getPrimaryKey(),
            $payload,
            $writeResult->getEntityName(),
            $writeResult->getOperation(),
            $writeResult->getExistence(),
            $writeResult->getChangeSet()
        );
    }

    /** * @param EntityWriteResult[] $writeResults * @param string|array<string, string> $entityKey * * @return EntityWriteResult[] */
/** * @internal * * @covers \Shopware\Core\Framework\Api\Sync\SyncService */
class SyncServiceTest extends TestCase
{
    public function testSyncSingleOperation(): void
    {
        $writeResult = new WriteResult(
            [
                'product' => [new EntityWriteResult('deleted-id', [], 'product', EntityWriteResult::OPERATION_DELETE)],
            ],
            [],
            [
                'product' => [new EntityWriteResult('created-id', [], 'product', EntityWriteResult::OPERATION_INSERT)],
            ]
        );

        $writer = $this->createMock(EntityWriterInterface::class);
        $writer
            ->expects(static::once())
            ->method('sync')
            
public function testGetSubscribedEvents(): void
    {
        static::assertEquals([
            NewsletterEvents::NEWSLETTER_RECIPIENT_WRITTEN_EVENT => 'setDefaultSalutation',
        ]$this->salutationSubscriber->getSubscribedEvents());
    }

    public function testSkip(): void
    {
        $writeResults = [
            new EntityWriteResult(
                'created-id',
                ['id' => Uuid::randomHex(), 'salutationId' => Uuid::randomHex()],
                'newsletter_recipient',
                EntityWriteResult::OPERATION_INSERT
            ),
        ];

        $event = new EntityWrittenEvent(
            'newsletter_recipient',
            $writeResults,
            Context::createDefaultContext(),
            [],
$connection,
            $this->createMock(MessageBusInterface::class),
            $this->createMock(EventDispatcherInterface::class),
            $client,
            $searchHelper,
            [],
            []
        );

        $index->refresh(new EntityWrittenContainerEvent(Context::createDefaultContext()new NestedEventCollection([
            new EntityWrittenEvent('promotion', [
                new EntityWriteResult(
                    'c1a28776116d4431a2208eb2960ec340',
                    [],
                    'promotion',
                    EntityWriteResult::OPERATION_INSERT
                ),
            ], Context::createDefaultContext()),
        ])[]));
    }

    public function testHandle(): void
    {
        
static::assertNotNull($data[0]['deliveries'][0]);
                static::assertSame($data[0]['deliveries'][0]['stateId']$orderEntity->getDeliveries()?->first()?->getStateId());

                static::assertSame($context->getTaxState(), CartPrice::TAX_STATE_FREE);

                /** @var CartPrice $price */
                $price = $data[0]['price'];

                static::assertSame($price->getTaxStatus(), CartPrice::TAX_STATE_FREE);

                return new EntityWrittenContainerEvent(Context::createDefaultContext()new NestedEventCollection([
                    new EntityWrittenEvent('order', [new EntityWriteResult('created-id', [], 'order', EntityWriteResult::OPERATION_INSERT)], Context::createDefaultContext()),
                ])[]);
            });

        $this->orderConverter
            ->expects(static::once())
            ->method('assembleSalesChannelContext')
            ->willReturnCallback(function DOrderEntity $order, Context $context) {
                $context->setTaxState($order->getTaxStatus());

                $salesChannel = new SalesChannelEntity();
                $salesChannel->setId(Uuid::randomHex());

                
$subscriber->onLanguageWritten($event);
    }

    public function testOnLanguageWrittenWithoutEsDefinition(): void
    {
        Feature::skipTestIfInActive('ES_MULTILINGUAL_INDEX', $this);

        $esHelper = $this->createMock(ElasticsearchHelper::class);
        $esHelper->expects(static::once())->method('allowIndexing')->willReturn(true);

        $writeResult = new EntityWriteResult(Uuid::randomHex()[], OrderDefinition::ENTITY_NAME, EntityWriteResult::OPERATION_UPDATE);

        $subscriber = new LanguageSubscriber(
            $esHelper,
            $this->createMock(ElasticsearchRegistry::class),
            $this->createMock(Client::class),
            $this->createMock(ProductDefinition::class),
            $this->createMock(MessageBusInterface::class)
        );

        $event = $this->createMock(EntityWrittenEvent::class);
        $event
            
public function testOnEntityWritten(): void
    {
        $context = Context::createDefaultContext();

        $idA = Uuid::randomHex();
        $idB = Uuid::randomBytes();
        $idC = Uuid::randomBytes();
        $idD = Uuid::randomBytes();

        $event = new EntityWrittenContainerEvent($contextnew NestedEventCollection([
            new EntityWrittenEvent('many_to_one', [
                new EntityWriteResult($idA[], 'many_to_one', EntityWriteResult::OPERATION_INSERT),
            ]$context[]),
            new EntityWrittenEvent('one_to_many', [
                new EntityWriteResult($idA['ruleId' => $idA], 'one_to_many', EntityWriteResult::OPERATION_INSERT),
                new EntityWriteResult($idA[], 'one_to_many', EntityWriteResult::OPERATION_UPDATE, null, new ChangeSet(
                    ['rule_id' => $idB],
                    ['rule_id' => $idC],
                    false
                )),
                new EntityWriteResult($idA[], 'one_to_many', EntityWriteResult::OPERATION_DELETE, null, new ChangeSet(
                    ['rule_id' => $idD],
                    ['rule_id' => null],
                    
$eventDispatcher = new EventDispatcher();

        $event = null;
        $eventDispatcher->addListener(EntityWrittenContainerEvent::classfunction D$inner) use (&$event): void {
            $event = $inner;
        });

        $versionManager = $this->createMock(VersionManager::class);
        $versionManager
            ->expects(static::once())
            ->method('insert')
            ->willReturn([[new EntityWriteResult('test', [], 'product', EntityWriteResult::OPERATION_INSERT)]]);

        $repo = new EntityRepository(
            new ProductDefinition(),
            $this->createMock(EntityReaderInterface::class),
            $versionManager,
            $this->createMock(EntitySearcherInterface::class),
            $this->createMock(EntityAggregatorInterface::class),
            $eventDispatcher,
            $this->createMock(EntityLoadedEventFactory::class),
        );

        
foreach ($event->getCommands() as $command) {
            static::assertInstanceOf(ChangeSetAware::class$command);
            static::assertFalse($command->requiresChangeSet());
        }
    }

    public function testOnReviewDeleted(): void
    {
        $event = new EntityDeletedEvent(
            ProductReviewDefinition::ENTITY_NAME,
            [
                new EntityWriteResult(
                    'id',
                    ['id' => 'id'],
                    ProductReviewDefinition::ENTITY_NAME,
                    EntityWriteResult::OPERATION_DELETE,
                    new EntityExistence(ProductReviewDefinition::ENTITY_NAME, ['id' => 'id'], true, false, false, []),
                    new ChangeSet(['customer_id' => 'customer_id'][], true)
                ),
                // should not trigger update as it has empty changeset                 new EntityWriteResult(
                    'id',
                    ['id' => 'id'],
                    
$entityReaderMock->expects(static::once())->method('read')->willReturn($entityCollectionMock);
        $serializer->expects(static::once())->method('serialize')
            ->willReturn('{"extensions":{"foreignKeys":{"extensions":[],"apiAlias":null,"manyToOneId":"' . Uuid::randomHex() . '"}}}');

        $writeContextMock = $this->createMock(WriteContext::class);

        $writeContextMockWithVersionId = $this->createMock(WriteContext::class);
        $writeContextMock->expects(static::once())->method('createWithVersionId')->willReturn($writeContextMockWithVersionId);

        $entityWriterMock->expects(static::once())->method('insert')->willReturn([
            'product' => [
                new EntityWriteResult('1', ['languageId' => '1'], 'product', EntityWriteResult::OPERATION_INSERT),
            ],
        ]);

        $writeContextMockWithVersionId->expects(static::once())->method('scope')
            ->with(static::equalTo(Context::SYSTEM_SCOPE)static::callback(function Dcallable $closure) use ($writeContextMockWithVersionId) {
                /** @var callable(MockObject&WriteContext): void $closure */
                $closure($writeContextMockWithVersionId);

                return true;
            }));

        
static::assertSame([RangeFilter::GTE => 10]$entity->getApiFilter()[0]['parameters']);
        static::assertFalse($entity->isInvalid());
    }

    private function createWrittenEvent(string $id): EntityWrittenContainerEvent
    {
        return new EntityWrittenContainerEvent(
            $this->context,
            new NestedEventCollection([
                new EntityWrittenEvent(
                    ProductStreamDefinition::ENTITY_NAME,
                    [new EntityWriteResult($id[], ProductStreamDefinition::ENTITY_NAME, EntityWriteResult::OPERATION_INSERT, null)],
                    Context::createDefaultContext()
                ),
            ]),
            []
        );
    }
}

        foreach ($parents as $entity => $primaryKeys) {
            $primaryKeys = array_unique($primaryKeys);
            if (!isset($writeResults[$entity])) {
                $writeResults[$entity] = [];
            }

            foreach ($primaryKeys as $primaryKey) {
                if ($this->hasResult($entity$primaryKey$writeResults)) {
                    continue;
                }
                $writeResults[$entity][] = new EntityWriteResult($primaryKey[]$entity, EntityWriteResult::OPERATION_UPDATE);
            }
        }

        return $writeResults;
    }

    public function addDeleteResults(array $identifiers, array $notFound, array $parents): WriteResult
    {
        $results = $this->splitResultsByOperation($identifiers);

        $deleted = $this->addParentResults($results['deleted']$parents);

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