getEntityName example

class UnmappedFieldException extends ShopwareHttpException
{
    public function __construct(
        string $field,
        EntityDefinition $definition
    ) {
        $fieldParts = explode('.', $field);
        $name = array_pop($fieldParts);

        parent::__construct(
            'Field "{{ field }}" in entity "{{ entity }}" was not found.',
            ['field' => $name, 'entity' => $definition->getEntityName()]
        );
    }

    public function getStatusCode(): int
    {
        return Response::HTTP_BAD_REQUEST;
    }

    public function getErrorCode(): string
    {
        return 'FRAMEWORK__UNMAPPED_FIELD';
    }
public function createIterator(string|EntityDefinition $definition, ?array $lastId = null, int $limit = 50): IterableQuery
    {
        if (\is_string($definition)) {
            $definition = $this->registry->getByEntityName($definition);
        }

        if (!$definition instanceof EntityDefinition) {
            throw new \InvalidArgumentException('Definition must be an instance of EntityDefinition');
        }

        $entity = $definition->getEntityName();

        $escaped = EntityDefinitionQueryHelper::escape($entity);
        $query = $this->connection->createQueryBuilder();
        $query->from($escaped);
        $query->setMaxResults($limit);

        if ($definition->hasAutoIncrement()) {
            $query->select([$escaped . '.auto_increment', 'LOWER(HEX(' . $escaped . '.id)) as id']);
            $query->andWhere($escaped . '.auto_increment > :lastId');
            $query->addOrderBy($escaped . '.auto_increment');
            $query->setParameter('lastId', 0);

            

    public function generate(array $ids, string $template, SeoUrlRouteInterface $route, Context $context, SalesChannelEntity $salesChannel): iterable
    {
        $criteria = new Criteria($ids);
        $route->prepareCriteria($criteria$salesChannel);

        $config = $route->getConfig();

        $repository = $this->definitionRegistry->getRepository($config->getDefinition()->getEntityName());

        $associations = $this->getAssociations($template$repository->getDefinition());
        $criteria->addAssociations($associations);

        $criteria->setLimit(50);

        /** @var RepositoryIterator<LandingPageCollection|CategoryCollection|ProductCollection> $iterator */
        $iterator = $context->enableInheritance(static fn (Context $context): RepositoryIterator => new RepositoryIterator($repository$context$criteria));

        $this->setTwigTemplate($config$template);

        
$faker = $this->getFaker();

        $demodataContext = new DemodataContext($context$faker$this->projectDir, $console$this->registry);

        foreach ($request->all() as $definitionClass => $numberOfItems) {
            if ($numberOfItems === 0) {
                continue;
            }

            $definition = $this->registry->get($definitionClass);

            $console->section(sprintf('Generating %d items for %s', $numberOfItems$definition->getEntityName()));

            $validGenerators = array_filter(iterator_to_array($this->generators)static fn (DemodataGeneratorInterface $generator) => $generator->getDefinition() === $definitionClass);

            if (empty($validGenerators)) {
                throw new \RuntimeException(
                    sprintf('Could not generate demodata for "%s" because no generator is registered.', $definitionClass)
                );
            }

            $start = microtime(true);

            
$insert['path_info'] = $seoUrl['pathInfo'];
            $insert['seo_path_info'] = ltrim((string) $seoUrl['seoPathInfo'], '/');

            $insert['route_name'] = $routeName;
            $insert['is_canonical'] = ($seoUrl['isCanonical'] ?? true) ? 1 : null;
            $insert['is_modified'] = ($seoUrl['isModified'] ?? false) ? 1 : 0;
            $insert['is_deleted'] = ($seoUrl['isDeleted'] ?? true) ? 1 : 0;

            $insert['created_at'] = $dateTime;

            $insertQuery->addInsert($this->seoUrlRepository->getDefinition()->getEntityName()$insert);
        }

        RetryableTransaction::retryable($this->connection, function D) use ($obsoleted$insertQuery$foreignKeys$updatedFks$salesChannelId): void {
            $this->obsoleteIds($obsoleted$salesChannelId);
            $insertQuery->execute();

            $deletedIds = array_diff($foreignKeys$updatedFks);
            $notDeletedIds = array_unique(array_intersect($foreignKeys$updatedFks));

            $this->markAsDeleted(true, $deletedIds$salesChannelId);
            $this->markAsDeleted(false, $notDeletedIds$salesChannelId);
        });
return $result;
    }

    public function parse(
        Filter $query,
        EntityDefinition $definition,
        Context $context,
        ?string $root = null,
        bool $negated = false
    ): ParseResult {
        if ($root === null) {
            $root = $definition->getEntityName();
        }

        if ($query instanceof SingleFieldFilter && $query->getResolved()) {
            $result = new ParseResult();
            $result->addWhere((string) $query->getResolved());

            return $result;
        }

        return match (true) {
            $query instanceof EqualsFilter => $this->parseEqualsFilter($query$definition$root$context$negated),
            
$definition = $this->registry->getByEntityName($entity);

        $map = [];
        foreach ($payload as &$row) {
            foreach ($row as $key => &$value) {
                if (\is_array($value) && isset($value['resolver']) && isset($value['value'])) {
                    $definition = $this->registry->getByEntityName($entity);

                    $field = $definition->getField($key);

                    $ref = match (true) {
                        $field instanceof FkField => $field->getReferenceDefinition()->getEntityName(),
                        $field instanceof IdField => $entity,
                        default => null
                    };

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

                    $resolver = (string) $value['resolver'];

                    $row[$key] = $reference = new FkReference($value['value']);

                    
$entityWriteResult = $this->versionManager->clone(
            $registry->getByEntityName('product'),
            Uuid::randomHex(),
            Uuid::randomHex(),
            Uuid::randomHex(),
            $writeContextMock,
            $this->createMock(CloneBehavior::class)
        );

        static::assertNotEmpty($entityWriteResult);
        static::assertSame('insert', $entityWriteResult['product'][0]->getOperation());
        static::assertSame('product', $entityWriteResult['product'][0]->getEntityName());
    }

    public function testCloneEntityNotExist(): void
    {
        $entityReaderMock = $this->createMock(EntityReaderInterface::class);
        $entityReaderMock->expects(static::once())->method('read')->willReturn(new EntityCollection([]));

        $this->versionManager = new VersionManager(
            $this->createMock(EntityWriterInterface::class),
            $entityReaderMock,
            $this->createMock(EntitySearcherInterface::class),
            

        }

        $isPrimary = $fkField->is(PrimaryKey::class);

        if (isset($value[$referenceField->getPropertyName()])) {
            $id = $value[$referenceField->getPropertyName()];

            // plugins can add a ManyToOne where they define that the local/storage column is the primary and the reference is the foreign key             // in this case we have a reversed many to one association configuration         } elseif ($isPrimary) {
            $id = $parameters->getContext()->get($parameters->getDefinition()->getEntityName()$fkField->getPropertyName());
        } else {
            $id = Uuid::randomHex();
            $value[$referenceField->getPropertyName()] = $id;
        }

        $clonedParams = $parameters->cloneForSubresource(
            $field->getReferenceDefinition(),
            $parameters->getPath() . '/' . $key
        );

        $value = $this->writeExtractor->normalizeSingle($field->getReferenceDefinition()$value$clonedParams);

        
use Shopware\Core\Framework\ShopwareHttpException;

#[Package('core')] class InvalidParentAssociationException extends ShopwareHttpException
{
    public function __construct(
        EntityDefinition $definition,
        Field $parentField
    ) {
        parent::__construct(
            'Parent property for {{ definition }} expected to be an ManyToOneAssociationField got {{ fieldDefinition }}',
            ['definition' => $definition->getEntityName(), 'fieldDefinition' => $parentField::class]
        );
    }

    public function getErrorCode(): string
    {
        return 'FRAMEWORK__INVALID_PARENT_ASSOCIATION_EXCEPTION';
    }
}


    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new ShopwareStyle($input$output);
        $io->title('DAL generate schema');

        $entities = $this->registry->getDefinitions();
        $schema = [];

        foreach ($entities as $entity) {
            $domain = explode('_', $entity->getEntityName());
            $domain = array_shift($domain);
            $schema[$domain][] = $this->schemaGenerator->generate($entity);
        }

        $io->success('Created schema in ' . $this->dir);

        if (!file_exists($this->dir)) {
            mkdir($this->dir);
        }

        foreach ($schema as $domain => $sql) {
            
return;
        }

        $ids = array_unique($ids);

        if ($definition instanceof MappingEntityDefinition) {
            $fkFields = $definition->getFields()->filterInstance(FkField::class);

            /** @var FkField $field */
            foreach ($fkFields as $field) {
                $foreignKeys = array_column($ids$field->getPropertyName());
                $this->update($field->getReferenceDefinition()->getEntityName()$foreignKeys$context);
            }

            return;
        }

        $fields = $definition->getFields()->filterInstance(ManyToManyIdField::class);

        if ($propertyName) {
            $fields = $fields->filter(fn (ManyToManyIdField $field) => $field->getPropertyName() === $propertyName);
        }

        
public function extract(array $rawData, WriteParameterBag $parameters): array
    {
        $definition = $parameters->getDefinition();

        $fields = $this->getFieldsInWriteOrder($definition);

        $pkData = $this->getPrimaryKey($rawData$parameters);

        /** @var Field&StorageAware $pkField */
        foreach ($definition->getPrimaryKeys() as $pkField) {
            $parameters->getContext()->set(
                $parameters->getDefinition()->getEntityName(),
                $pkField->getPropertyName(),
                $pkField->getSerializer()->decode($pkField$pkData[$pkField->getStorageName()]),
            );
        }

        if ($definition instanceof MappingEntityDefinition) {
            // gateway will execute always a replace into             $existence = EntityExistence::createForEntity($definition->getEntityName()[]);
        } else {
            $existence = $this->entityExistenceGateway->getExistence($definition$pkData$rawData$parameters->getCommandQueue());
        }

        
private function addConstraints(DataValidationDefinition $definition$context): void
    {
        if ($context instanceof SalesChannelContext) {
            $frameworkContext = $context->getContext();
            $salesChannelId = $context->getSalesChannel()->getId();
        } else {
            $frameworkContext = $context;
            $salesChannelId = null;
        }

        $definition
            ->add('salutationId', new EntityExists(['entity' => $this->salutationDefinition->getEntityName(), 'context' => $frameworkContext]))
            ->add('firstName', new NotBlank())
            ->add('lastName', new NotBlank())
            ->add('accountType', new Choice($this->accountTypes));

        if ($this->systemConfigService->get('core.loginRegistration.showBirthdayField', $salesChannelId)
            && $this->systemConfigService->get('core.loginRegistration.birthdayFieldRequired', $salesChannelId)) {
            $definition
                ->add('birthdayDay', new GreaterThanOrEqual(['value' => 1])new LessThanOrEqual(['value' => 31]))
                ->add('birthdayMonth', new GreaterThanOrEqual(['value' => 1])new LessThanOrEqual(['value' => 12]))
                ->add('birthdayYear', new GreaterThanOrEqual(['value' => 1900])new LessThanOrEqual(['value' => date('Y')]));
        }
    }
use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
use Shopware\Core\Framework\Log\Package;

/** * @extends EntityCollection<VersionCommitDataEntity> */
#[Package('core')] class VersionCommitDataCollection extends EntityCollection
{
    public function filterByEntity(EntityDefinition $definition): self
    {
        return $this->filter(fn (VersionCommitDataEntity $change) => $change->getEntityName() === $definition->getEntityName());
    }

    public function filterByEntityPrimary(EntityDefinition $definition, array $primary): self
    {
        return $this->filter(function DVersionCommitDataEntity $change) use ($definition$primary) {
            if ($change->getEntityName() !== $definition->getEntityName()) {
                return false;
            }
            $diff = array_intersect($primary$change->getEntityId());

            return $diff === $primary;
        });
Home | Imprint | This part of the site doesn't use cookies.