getEventByEntityName example

'routeName' => ProductPageSeoUrlRoute::ROUTE_NAME,
            'entityName' => $this->getContainer()->get(ProductDefinition::class)->getEntityName(),
            'template' => ProductPageSeoUrlRoute::DEFAULT_TEMPLATE,
        ];

        $context = Context::createDefaultContext();
        /** @var EntityRepository $repo */
        $repo = $this->getContainer()->get('seo_url_template.repository');
        $events = $repo->create([$template]$context);
        static::assertCount(1, $events->getEvents());

        $event = $events->getEventByEntityName(SeoUrlTemplateDefinition::ENTITY_NAME);
        static::assertNotNull($event);
        static::assertCount(1, $event->getPayloads());
    }

    /** * @dataProvider templateUpdateDataProvider */
    public function testUpdate(string $id, array $template): void
    {
        $context = Context::createDefaultContext();
        /** @var EntityRepository $repo */
        
public static function getSubscribedEvents(): array
    {
        return [
            EntityWrittenContainerEvent::class => [
                ['invalidate', 2000],
            ],
        ];
    }

    public function invalidate(EntityWrittenContainerEvent $event): void
    {
        if ($event->getEventByEntityName(SalesChannelDefinition::ENTITY_NAME)) {
            $this->logger->invalidate([CachedDomainLoader::CACHE_KEY]);
        }
    }
}
'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            'translations' => [
                'en-GB' => [
                    'name' => 'US Dollar',
                    'shortName' => 'FOO',
                ],
            ],
        ];

        $result = $this->currencyRepository->create([$data]$this->context);

        $currencies = $result->getEventByEntityName(CurrencyDefinition::ENTITY_NAME);
        static::assertInstanceOf(EntityWrittenEvent::class$currencies);
        static::assertCount(1, $currencies->getIds());

        $translations = $result->getEventByEntityName(CurrencyTranslationDefinition::ENTITY_NAME);
        static::assertInstanceOf(EntityWrittenEvent::class$translations);
        static::assertCount(1, $translations->getIds());
        $languageIds = array_column($translations->getPayloads(), 'languageId');
        static::assertContains(Defaults::LANGUAGE_SYSTEM, $languageIds);

        $payload = $translations->getPayloads()[0];
        static::assertArrayHasKey('name', $payload);
        


    /** * `getIds()` filters the written events down to the events of a single entity. * * @param string $entity The entity for which the events should be filtered. * * @return WrittenEventIdCollection The id collection for the written events which allows further filtering. */
    public function getIds(string $entity): WrittenEventIdCollection
    {
        $writtenEvent = $this->containerEvent->getEventByEntityName($entity);

        return new WrittenEventIdCollection(
            $writtenEvent ? $writtenEvent->getWriteResults() : []
        );
    }
}
if (empty($ids)) {
            return null;
        }

        return new MediaIndexingMessage(array_values($ids)$iterator->getOffset());
    }

    public function update(EntityWrittenContainerEvent $event): ?EntityIndexingMessage
    {
        $updates = $event->getPrimaryKeys(MediaFolderDefinition::ENTITY_NAME);
        $mediaFolderEvent = $event->getEventByEntityName(MediaFolderDefinition::ENTITY_NAME);

        if (empty($updates) || !$mediaFolderEvent) {
            return null;
        }

        $idsWithChangedParentIds = [];
        foreach ($mediaFolderEvent->getWriteResults() as $result) {
            $payload = $result->getPayload();
            if (\array_key_exists('parentId', $payload)) {
                $idsWithChangedParentIds[] = $payload['id'];
            }
        }
if (
            !$source->isAllowed('user:update')
            && $source->getUserId() !== $data['id']
        ) {
            throw new PermissionDeniedException();
        }

        /** @var EntityWrittenContainerEvent $events */
        $events = $context->scope(Context::SYSTEM_SCOPE, fn (Context $context) => $this->userRepository->upsert([$data]$context));

        /** @var EntityWrittenEvent $event */
        $event = $events->getEventByEntityName(UserDefinition::ENTITY_NAME);

        $eventIds = $event->getIds();
        $entityId = array_pop($eventIds);

        return $factory->createRedirectResponse($this->userRepository->getDefinition()$entityId$request$context);
    }

    #[Route(path: '/api/user/{userId}', name: 'api.user.update', defaults: ['auth_required' => true, '_acl' => ['user:update']], methods: ['PATCH'])]     public function updateUser(?string $userId, Request $request, Context $context, ResponseFactoryInterface $factory): Response
    {
        return $this->upsertUser($userId$request$context$factory);
    }
throw new DecorationPatternException(static::class);
    }

    private function isGeneratingIndividualCode(EntityWrittenContainerEvent $event): bool
    {
        $events = $event->getEvents();

        if (!$event->getContext()->getSource() instanceof AdminApiSource || $events === null || $events->count() !== 2) {
            return false;
        }

        $promotionIndividualWrittenEvent = $event->getEventByEntityName(PromotionIndividualCodeDefinition::ENTITY_NAME);

        if ($promotionIndividualWrittenEvent === null || $promotionIndividualWrittenEvent->getName() !== 'promotion_individual_code.written') {
            return false;
        }

        $promotionWrittenEvent = $event->getEventByEntityName(PromotionDefinition::ENTITY_NAME);

        if ($promotionWrittenEvent === null || $promotionWrittenEvent->getName() !== 'promotion.written' || !empty($promotionWrittenEvent->getPayloads()[0])) {
            return false;
        }

        
static::assertTrue($this->getPublicFilesystem()->has($secondPath));
    }

    public function testDeleteForUnusedIds(): void
    {
        $firstId = Uuid::randomHex();

        $event = $this->mediaRepository->delete([['id' => $firstId]]$this->context);

        $this->runWorker();

        static::assertNull($event->getEventByEntityName(MediaDefinition::ENTITY_NAME));
    }

    public function testDeleteForEmptyIds(): void
    {
        $secondId = Uuid::randomHex();

        $this->mediaRepository->create(
            [
                [
                    'id' => $secondId,
                    'name' => 'test media',
                    

                'id' => $bazId,
                'name' => 'foo\'bar',
                'custom' => [
                    'foo' => 'baz',
                ],
            ],
        ];

        $repo = $this->getTestRepository();
        $result = $repo->create($entities, Context::createDefaultContext());
        $events = $result->getEventByEntityName(CustomFieldTestDefinition::ENTITY_NAME);
        static::assertCount(2, $events->getPayloads());

        $expected = [$barId$bazId];
        static::assertEquals($expected$events->getIds());

        $actual = $repo->search(new Criteria([$barId]), Context::createDefaultContext())->first();
        static::assertEquals($barId$actual->get('id'));
        static::assertEquals($entities[0]['custom']$actual->get('custom'));

        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('custom.foo', 'bar'));
        


    public static function getSubscribedEvents(): array
    {
        return [
            EntityWrittenContainerEvent::class => 'onNewCustomFieldCreated',
        ];
    }

    public function onNewCustomFieldCreated(EntityWrittenContainerEvent $containerEvent): void
    {
        $event = $containerEvent->getEventByEntityName(CustomFieldDefinition::ENTITY_NAME);

        if ($event === null) {
            return;
        }

        if (!$this->elasticsearchHelper->allowIndexing()) {
            return;
        }

        $newCreatedFields = [];

        
if ($missing) {
            throw ApiException::missingPrivileges([$missing]);
        }

        /** @var EntityWrittenContainerEvent $eventContainer */
        $eventContainer = $context->scope(Context::CRUD_API_SCOPE, function DContext $context) use ($definition$id$behavior): EntityWrittenContainerEvent {
            $entityRepo = $this->definitionRegistry->getRepository($definition->getEntityName());

            return $entityRepo->clone($id$context, null, $behavior);
        });

        $event = $eventContainer->getEventByEntityName($definition->getEntityName());
        if (!$event) {
            throw ApiException::noEntityCloned($entity$id);
        }

        $ids = $event->getIds();
        $newId = array_shift($ids);

        return new JsonResponse(['id' => $newId]);
    }

    #[Route(path: '/api/_action/version/{entity}/{id}', name: 'api.createVersion', methods: ['POST'], requirements: ['version' => '\d+', 'entity' => '[a-zA-Z-]+', 'id' => '[0-9a-f]{32}'])]
/** * @internal */
class EntityWrittenEventSerializationTest extends TestCase
{
    use IntegrationTestBehaviour;

    public function testEventCanBeSerialized(): void
    {
        $container = $this->writeTestProduct();
        $event = $container->getEventByEntityName(ProductDefinition::ENTITY_NAME);

        $encoded = json_encode($event, \JSON_THROW_ON_ERROR);
        static::assertNotFalse($encoded);
        static::assertJson($encoded);

        $encoded = json_encode($container, \JSON_THROW_ON_ERROR);
        static::assertNotFalse($encoded);
        static::assertJson($encoded);
    }

    private function writeTestProduct(): EntityWrittenContainerEvent
    {
'factor' => 1,
                'symbol' => 'A',
                'itemRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
                'totalRounding' => json_decode(json_encode(new CashRoundingConfig(2, 0.01, true), \JSON_THROW_ON_ERROR), true, 512, \JSON_THROW_ON_ERROR),
            ],
        ];

        $this->currencyRepository->create($records$context);

        $deleteEvent = $this->currencyRepository->delete([['id' => $recordA]]$context);

        static::assertEquals($recordA$deleteEvent->getEventByEntityName(CurrencyDefinition::ENTITY_NAME)->getWriteResults()[0]->getPrimaryKey());
    }

    public function testDeleteDefaultCurrency(): void
    {
        $context = Context::createDefaultContext();

        $this->expectException(RestrictDeleteViolationException::class);
        $this->currencyRepository->delete([['id' => Defaults::CURRENCY]]$context);
    }
}
return [];
    }

    /** * @return Hookable[] */
    private function wrapEntityWrittenEvent(EntityWrittenContainerEvent $event): array
    {
        $hookables = [];
        foreach (HookableEventCollector::HOOKABLE_ENTITIES as $entity) {
            $writtenEvent = $event->getEventByEntityName($entity);

            if (!$writtenEvent) {
                continue;
            }

            $translationEvent = $event->getEventByEntityName($entity . '_translation');

            $mergedWrittenEvent = $this->writeResultMerger->mergeWriteResults($writtenEvent$translationEvent);

            if (!$mergedWrittenEvent) {
                continue;
            }
public function testDeleteSnippet(): void
    {
        $snippetRepository = $this->getContainer()->get('snippet.repository');
        $snippet = [
            'id' => Uuid::randomHex(),
            'translationKey' => 'foo',
            'value' => 'bar',
            'setId' => $this->getSnippetSetIdForLocale('en-GB'),
            'author' => 'Shopware',
        ];

        $created = $snippetRepository->create([$snippet], Context::createDefaultContext())->getEventByEntityName(SnippetDefinition::ENTITY_NAME);
        static::assertInstanceOf(EntityWrittenEvent::class$created);
        static::assertEquals([$snippet['id']]$created->getIds());

        $deleted = $snippetRepository->delete([['id' => $snippet['id']]], Context::createDefaultContext())->getEventByEntityName(SnippetDefinition::ENTITY_NAME);
        static::assertInstanceOf(EntityWrittenEvent::class$deleted);
        static::assertEquals([$snippet['id']]$deleted->getIds());
    }

    public function testItReplacesReservedCharacter(): void
    {
        static::assertEquals('translator.<_r_strong>', Translator::buildName('</strong>'));
    }
Home | Imprint | This part of the site doesn't use cookies.