vendor/shopware/core/Framework/DataAbstractionLayer/Dbal/EntityReader.php line 307

  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Framework\DataAbstractionLayer\Dbal;
  3. use Doctrine\DBAL\Connection;
  4. use Psr\Log\LoggerInterface;
  5. use Shopware\Core\Framework\Context;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Dbal\Exception\ParentAssociationCanNotBeFetched;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Entity;
  8. use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
  9. use Shopware\Core\Framework\DataAbstractionLayer\EntityDefinition;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Field\AssociationField;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Field\ChildrenAssociationField;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Field\Field;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\CascadeDelete;
  14. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\Extension;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\Inherited;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\PrimaryKey;
  17. use Shopware\Core\Framework\DataAbstractionLayer\Field\Flag\Runtime;
  18. use Shopware\Core\Framework\DataAbstractionLayer\Field\JsonField;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Field\ManyToManyAssociationField;
  20. use Shopware\Core\Framework\DataAbstractionLayer\Field\ManyToOneAssociationField;
  21. use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToManyAssociationField;
  22. use Shopware\Core\Framework\DataAbstractionLayer\Field\OneToOneAssociationField;
  23. use Shopware\Core\Framework\DataAbstractionLayer\Field\ParentAssociationField;
  24. use Shopware\Core\Framework\DataAbstractionLayer\Field\StorageAware;
  25. use Shopware\Core\Framework\DataAbstractionLayer\Field\TranslatedField;
  26. use Shopware\Core\Framework\DataAbstractionLayer\FieldCollection;
  27. use Shopware\Core\Framework\DataAbstractionLayer\Read\EntityReaderInterface;
  28. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  29. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  30. use Shopware\Core\Framework\DataAbstractionLayer\Search\Parser\SqlQueryParser;
  31. use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
  32. use Shopware\Core\Framework\Log\Package;
  33. use Shopware\Core\Framework\Struct\ArrayEntity;
  34. use Shopware\Core\Framework\Struct\ArrayStruct;
  35. use Shopware\Core\Framework\Uuid\Uuid;
  36. use function array_filter;
  37. /**
  38.  * @internal
  39.  */
  40. #[Package('core')]
  41. class EntityReader implements EntityReaderInterface
  42. {
  43.     final public const INTERNAL_MAPPING_STORAGE 'internal_mapping_storage';
  44.     final public const FOREIGN_KEYS 'foreignKeys';
  45.     final public const MANY_TO_MANY_LIMIT_QUERY 'many_to_many_limit_query';
  46.     public function __construct(
  47.         private readonly Connection $connection,
  48.         private readonly EntityHydrator $hydrator,
  49.         private readonly EntityDefinitionQueryHelper $queryHelper,
  50.         private readonly SqlQueryParser $parser,
  51.         private readonly CriteriaQueryBuilder $criteriaQueryBuilder,
  52.         private readonly LoggerInterface $logger,
  53.         private readonly CriteriaFieldsResolver $criteriaFieldsResolver
  54.     ) {
  55.     }
  56.     /**
  57.      * @return EntityCollection<Entity>
  58.      */
  59.     public function read(EntityDefinition $definitionCriteria $criteriaContext $context): EntityCollection
  60.     {
  61.         $criteria->resetSorting();
  62.         $criteria->resetQueries();
  63.         /** @var EntityCollection<Entity> $collectionClass */
  64.         $collectionClass $definition->getCollectionClass();
  65.         $fields $this->criteriaFieldsResolver->resolve($criteria$definition);
  66.         return $this->_read(
  67.             $criteria,
  68.             $definition,
  69.             $context,
  70.             new $collectionClass(),
  71.             $definition->getFields()->getBasicFields(),
  72.             true,
  73.             $fields
  74.         );
  75.     }
  76.     protected function getParser(): SqlQueryParser
  77.     {
  78.         return $this->parser;
  79.     }
  80.     /**
  81.      * @param EntityCollection<Entity> $collection
  82.      * @param array<string,mixed> $partial
  83.      *
  84.      * @return EntityCollection<Entity>
  85.      */
  86.     private function _read(
  87.         Criteria $criteria,
  88.         EntityDefinition $definition,
  89.         Context $context,
  90.         EntityCollection $collection,
  91.         FieldCollection $fields,
  92.         bool $performEmptySearch false,
  93.         array $partial = []
  94.     ): EntityCollection {
  95.         $hasFilters = !empty($criteria->getFilters()) || !empty($criteria->getPostFilters());
  96.         $hasIds = !empty($criteria->getIds());
  97.         if (!$performEmptySearch && !$hasFilters && !$hasIds) {
  98.             return $collection;
  99.         }
  100.         if ($partial !== []) {
  101.             $fields $definition->getFields()->filter(function (Field $field) use (&$partial) {
  102.                 if ($field->getFlag(PrimaryKey::class)) {
  103.                     $partial[$field->getPropertyName()] = [];
  104.                     return true;
  105.                 }
  106.                 return isset($partial[$field->getPropertyName()]);
  107.             });
  108.         }
  109.         // always add the criteria fields to the collection, otherwise we have conflicts between criteria.fields and criteria.association logic
  110.         $fields $this->addAssociationFieldsToCriteria($criteria$definition$fields);
  111.         if ($definition->isInheritanceAware() && $criteria->hasAssociation('parent')) {
  112.             throw new ParentAssociationCanNotBeFetched();
  113.         }
  114.         $rows $this->fetch($criteria$definition$context$fields$partial);
  115.         $collection $this->hydrator->hydrate($collection$definition->getEntityClass(), $definition$rows$definition->getEntityName(), $context$partial);
  116.         $collection $this->fetchAssociations($criteria$definition$context$collection$fields$partial);
  117.         $hasIds = !empty($criteria->getIds());
  118.         if ($hasIds && empty($criteria->getSorting())) {
  119.             $collection->sortByIdArray($criteria->getIds());
  120.         }
  121.         return $collection;
  122.     }
  123.     /**
  124.      * @param array<string,mixed> $partial
  125.      */
  126.     private function joinBasic(
  127.         EntityDefinition $definition,
  128.         Context $context,
  129.         string $root,
  130.         QueryBuilder $query,
  131.         FieldCollection $fields,
  132.         ?Criteria $criteria null,
  133.         array $partial = []
  134.     ): void {
  135.         $isPartial $partial !== [];
  136.         $filtered $fields->filter(static function (Field $field) use ($isPartial$partial) {
  137.             if ($field->is(Runtime::class)) {
  138.                 return false;
  139.             }
  140.             if (!$isPartial || $field->getFlag(PrimaryKey::class)) {
  141.                 return true;
  142.             }
  143.             return isset($partial[$field->getPropertyName()]);
  144.         });
  145.         $parentAssociation null;
  146.         if ($definition->isInheritanceAware() && $context->considerInheritance()) {
  147.             $parentAssociation $definition->getFields()->get('parent');
  148.             if ($parentAssociation !== null) {
  149.                 $this->queryHelper->resolveField($parentAssociation$definition$root$query$context);
  150.             }
  151.         }
  152.         $addTranslation false;
  153.         /** @var Field $field */
  154.         foreach ($filtered as $field) {
  155.             //translated fields are handled after loop all together
  156.             if ($field instanceof TranslatedField) {
  157.                 $this->queryHelper->resolveField($field$definition$root$query$context);
  158.                 $addTranslation true;
  159.                 continue;
  160.             }
  161.             //self references can not be resolved if set to autoload, otherwise we get an endless loop
  162.             if (!$field instanceof ParentAssociationField && $field instanceof AssociationField && $field->getAutoload() && $field->getReferenceDefinition() === $definition) {
  163.                 continue;
  164.             }
  165.             //many to one associations can be directly fetched in same query
  166.             if ($field instanceof ManyToOneAssociationField || $field instanceof OneToOneAssociationField) {
  167.                 $reference $field->getReferenceDefinition();
  168.                 $basics $reference->getFields()->getBasicFields();
  169.                 $this->queryHelper->resolveField($field$definition$root$query$context);
  170.                 $alias $root '.' $field->getPropertyName();
  171.                 $joinCriteria null;
  172.                 if ($criteria && $criteria->hasAssociation($field->getPropertyName())) {
  173.                     $joinCriteria $criteria->getAssociation($field->getPropertyName());
  174.                     $basics $this->addAssociationFieldsToCriteria($joinCriteria$reference$basics);
  175.                 }
  176.                 $this->joinBasic($reference$context$alias$query$basics$joinCriteria$partial[$field->getPropertyName()] ?? []);
  177.                 continue;
  178.             }
  179.             //add sub select for many to many field
  180.             if ($field instanceof ManyToManyAssociationField) {
  181.                 if ($this->isAssociationRestricted($criteria$field->getPropertyName())) {
  182.                     continue;
  183.                 }
  184.                 //requested a paginated, filtered or sorted list
  185.                 $this->addManyToManySelect($definition$root$field$query$context);
  186.                 continue;
  187.             }
  188.             //other associations like OneToManyAssociationField fetched lazy by additional query
  189.             if ($field instanceof AssociationField) {
  190.                 continue;
  191.             }
  192.             if ($parentAssociation !== null
  193.                 && $field instanceof StorageAware
  194.                 && $field->is(Inherited::class)
  195.                 && $context->considerInheritance()
  196.             ) {
  197.                 $parentAlias $root '.' $parentAssociation->getPropertyName();
  198.                 //contains the field accessor for the child value (eg. `product.name`.`name`)
  199.                 $childAccessor EntityDefinitionQueryHelper::escape($root) . '.'
  200.                     EntityDefinitionQueryHelper::escape($field->getStorageName());
  201.                 //contains the field accessor for the parent value (eg. `product.parent`.`name`)
  202.                 $parentAccessor EntityDefinitionQueryHelper::escape($parentAlias) . '.'
  203.                     EntityDefinitionQueryHelper::escape($field->getStorageName());
  204.                 //contains the alias for the resolved field (eg. `product.name`)
  205.                 $fieldAlias EntityDefinitionQueryHelper::escape($root '.' $field->getPropertyName());
  206.                 if ($field instanceof JsonField) {
  207.                     // merged in hydrator
  208.                     $parentFieldAlias EntityDefinitionQueryHelper::escape($root '.' $field->getPropertyName() . '.inherited');
  209.                     $query->addSelect(sprintf('%s as %s'$parentAccessor$parentFieldAlias));
  210.                 }
  211.                 //add selection for resolved parent-child inheritance field
  212.                 $query->addSelect(sprintf('COALESCE(%s, %s) as %s'$childAccessor$parentAccessor$fieldAlias));
  213.                 continue;
  214.             }
  215.             //all other StorageAware fields are stored inside the main entity
  216.             if ($field instanceof StorageAware) {
  217.                 $query->addSelect(
  218.                     EntityDefinitionQueryHelper::escape($root) . '.'
  219.                     EntityDefinitionQueryHelper::escape($field->getStorageName()) . ' as '
  220.                     EntityDefinitionQueryHelper::escape($root '.' $field->getPropertyName())
  221.                 );
  222.             }
  223.         }
  224.         if ($addTranslation) {
  225.             $this->queryHelper->addTranslationSelect($root$definition$query$context$partial);
  226.         }
  227.     }
  228.     /**
  229.      * @param array<string,mixed> $partial
  230.      *
  231.      * @return list<array<string,mixed>>
  232.      */
  233.     private function fetch(Criteria $criteriaEntityDefinition $definitionContext $contextFieldCollection $fields, array $partial = []): array
  234.     {
  235.         $table $definition->getEntityName();
  236.         $query $this->criteriaQueryBuilder->build(
  237.             new QueryBuilder($this->connection),
  238.             $definition,
  239.             $criteria,
  240.             $context
  241.         );
  242.         $this->joinBasic($definition$context$table$query$fields$criteria$partial);
  243.         if (!empty($criteria->getIds())) {
  244.             $this->queryHelper->addIdCondition($criteria$definition$query);
  245.         }
  246.         if ($criteria->getTitle()) {
  247.             $query->setTitle($criteria->getTitle() . '::read');
  248.         }
  249.         return $query->executeQuery()->fetchAllAssociative();
  250.     }
  251.     /**
  252.      * @param EntityCollection<Entity> $collection
  253.      * @param array<string,mixed> $partial
  254.      */
  255.     private function loadManyToMany(
  256.         Criteria $criteria,
  257.         ManyToManyAssociationField $association,
  258.         Context $context,
  259.         EntityCollection $collection,
  260.         array $partial
  261.     ): void {
  262.         $associationCriteria $criteria->getAssociation($association->getPropertyName());
  263.         if (!$associationCriteria->getTitle() && $criteria->getTitle()) {
  264.             $associationCriteria->setTitle(
  265.                 $criteria->getTitle() . '::association::' $association->getPropertyName()
  266.             );
  267.         }
  268.         //check if the requested criteria is restricted (limit, offset, sorting, filtering)
  269.         if ($this->isAssociationRestricted($criteria$association->getPropertyName())) {
  270.             //if restricted load paginated list of many to many
  271.             $this->loadManyToManyWithCriteria($associationCriteria$association$context$collection$partial);
  272.             return;
  273.         }
  274.         //otherwise the association is loaded in the root query of the entity as sub select which contains all ids
  275.         //the ids are extracted in the entity hydrator (see: \Shopware\Core\Framework\DataAbstractionLayer\Dbal\EntityHydrator::extractManyToManyIds)
  276.         $this->loadManyToManyOverExtension($associationCriteria$association$context$collection$partial);
  277.     }
  278.     private function addManyToManySelect(
  279.         EntityDefinition $definition,
  280.         string $root,
  281.         ManyToManyAssociationField $field,
  282.         QueryBuilder $query,
  283.         Context $context
  284.     ): void {
  285.         $mapping $field->getMappingDefinition();
  286.         $versionCondition '';
  287.         if ($mapping->isVersionAware() && $definition->isVersionAware() && $field->is(CascadeDelete::class)) {
  288.             $versionField $definition->getEntityName() . '_version_id';
  289.             $versionCondition ' AND #alias#.' $versionField ' = #root#.version_id';
  290.         }
  291.         $source EntityDefinitionQueryHelper::escape($root) . '.' EntityDefinitionQueryHelper::escape($field->getLocalField());
  292.         if ($field->is(Inherited::class) && $context->considerInheritance()) {
  293.             $source EntityDefinitionQueryHelper::escape($root) . '.' EntityDefinitionQueryHelper::escape($field->getPropertyName());
  294.         }
  295.         $parameters = [
  296.             '#alias#' => EntityDefinitionQueryHelper::escape($root '.' $field->getPropertyName() . '.mapping'),
  297.             '#mapping_reference_column#' => EntityDefinitionQueryHelper::escape($field->getMappingReferenceColumn()),
  298.             '#mapping_table#' => EntityDefinitionQueryHelper::escape($mapping->getEntityName()),
  299.             '#mapping_local_column#' => EntityDefinitionQueryHelper::escape($field->getMappingLocalColumn()),
  300.             '#root#' => EntityDefinitionQueryHelper::escape($root),
  301.             '#source#' => $source,
  302.             '#property#' => EntityDefinitionQueryHelper::escape($root '.' $field->getPropertyName() . '.id_mapping'),
  303.         ];
  304.         $query->addSelect(
  305.             str_replace(
  306.                 array_keys($parameters),
  307.                 array_values($parameters),
  308.                 '(SELECT GROUP_CONCAT(HEX(#alias#.#mapping_reference_column#) SEPARATOR \'||\')
  309.                   FROM #mapping_table# #alias#
  310.                   WHERE #alias#.#mapping_local_column# = #source#'
  311.                   $versionCondition
  312.                   ' ) as #property#'
  313.             )
  314.         );
  315.     }
  316.     /**
  317.      * @param EntityCollection<Entity> $collection
  318.      *
  319.      * @return array<string>
  320.      */
  321.     private function collectManyToManyIds(EntityCollection $collectionAssociationField $association): array
  322.     {
  323.         $ids = [];
  324.         $property $association->getPropertyName();
  325.         /** @var Entity $struct */
  326.         foreach ($collection as $struct) {
  327.             /** @var ArrayStruct<string, mixed> $ext */
  328.             $ext $struct->getExtension(self::INTERNAL_MAPPING_STORAGE);
  329.             /** @var array<string> $tmp */
  330.             $tmp $ext->get($property);
  331.             foreach ($tmp as $id) {
  332.                 $ids[] = $id;
  333.             }
  334.         }
  335.         return $ids;
  336.     }
  337.     /**
  338.      * @param EntityCollection<Entity> $collection
  339.      * @param array<string,mixed> $partial
  340.      */
  341.     private function loadOneToMany(
  342.         Criteria $criteria,
  343.         EntityDefinition $definition,
  344.         OneToManyAssociationField $association,
  345.         Context $context,
  346.         EntityCollection $collection,
  347.         array $partial
  348.     ): void {
  349.         $fieldCriteria = new Criteria();
  350.         if ($criteria->hasAssociation($association->getPropertyName())) {
  351.             $fieldCriteria $criteria->getAssociation($association->getPropertyName());
  352.         }
  353.         if (!$fieldCriteria->getTitle() && $criteria->getTitle()) {
  354.             $fieldCriteria->setTitle(
  355.                 $criteria->getTitle() . '::association::' $association->getPropertyName()
  356.             );
  357.         }
  358.         //association should not be paginated > load data over foreign key condition
  359.         if ($fieldCriteria->getLimit() === null) {
  360.             $this->loadOneToManyWithoutPagination($definition$association$context$collection$fieldCriteria$partial);
  361.             return;
  362.         }
  363.         //load association paginated > use internal counter loops
  364.         $this->loadOneToManyWithPagination($definition$association$context$collection$fieldCriteria$partial);
  365.     }
  366.     /**
  367.      * @param EntityCollection<Entity> $collection
  368.      * @param array<string,mixed> $partial
  369.      */
  370.     private function loadOneToManyWithoutPagination(
  371.         EntityDefinition $definition,
  372.         OneToManyAssociationField $association,
  373.         Context $context,
  374.         EntityCollection $collection,
  375.         Criteria $fieldCriteria,
  376.         array $partial
  377.     ): void {
  378.         $ref $association->getReferenceDefinition()->getFields()->getByStorageName(
  379.             $association->getReferenceField()
  380.         );
  381.         \assert($ref instanceof Field);
  382.         $propertyName $ref->getPropertyName();
  383.         if ($association instanceof ChildrenAssociationField) {
  384.             $propertyName 'parentId';
  385.         }
  386.         //build orm property accessor to add field sortings and conditions `customer_address.customerId`
  387.         $propertyAccessor $association->getReferenceDefinition()->getEntityName() . '.' $propertyName;
  388.         $ids array_values($collection->getIds());
  389.         $isInheritanceAware $definition->isInheritanceAware() && $context->considerInheritance();
  390.         if ($isInheritanceAware) {
  391.             $parentIds array_values(array_filter($collection->map(fn (Entity $entity) => $entity->get('parentId'))));
  392.             $ids array_unique([...$ids, ...$parentIds]);
  393.         }
  394.         $fieldCriteria->addFilter(new EqualsAnyFilter($propertyAccessor$ids));
  395.         $referenceClass $association->getReferenceDefinition();
  396.         /** @var EntityCollection<Entity> $collectionClass */
  397.         $collectionClass $referenceClass->getCollectionClass();
  398.         if ($partial !== []) {
  399.             // Make sure our collection index will be loaded
  400.             $partial[$propertyName] = [];
  401.             $collectionClass EntityCollection::class;
  402.         }
  403.         $data $this->_read(
  404.             $fieldCriteria,
  405.             $referenceClass,
  406.             $context,
  407.             new $collectionClass(),
  408.             $referenceClass->getFields()->getBasicFields(),
  409.             false,
  410.             $partial
  411.         );
  412.         $grouped = [];
  413.         foreach ($data as $entity) {
  414.             $fk $entity->get($propertyName);
  415.             $grouped[$fk][] = $entity;
  416.         }
  417.         //assign loaded data to root entities
  418.         foreach ($collection as $entity) {
  419.             $structData = new $collectionClass();
  420.             if (isset($grouped[$entity->getUniqueIdentifier()])) {
  421.                 $structData->fill($grouped[$entity->getUniqueIdentifier()]);
  422.             }
  423.             //assign data of child immediately
  424.             if ($association->is(Extension::class)) {
  425.                 $entity->addExtension($association->getPropertyName(), $structData);
  426.             } else {
  427.                 //otherwise the data will be assigned directly as properties
  428.                 $entity->assign([$association->getPropertyName() => $structData]);
  429.             }
  430.             if (!$association->is(Inherited::class) || $structData->count() > || !$context->considerInheritance()) {
  431.                 continue;
  432.             }
  433.             //if association can be inherited by the parent and the struct data is empty, filter again for the parent id
  434.             $structData = new $collectionClass();
  435.             if (isset($grouped[$entity->get('parentId')])) {
  436.                 $structData->fill($grouped[$entity->get('parentId')]);
  437.             }
  438.             if ($association->is(Extension::class)) {
  439.                 $entity->addExtension($association->getPropertyName(), $structData);
  440.                 continue;
  441.             }
  442.             $entity->assign([$association->getPropertyName() => $structData]);
  443.         }
  444.     }
  445.     /**
  446.      * @param EntityCollection<Entity> $collection
  447.      * @param array<string,mixed> $partial
  448.      */
  449.     private function loadOneToManyWithPagination(
  450.         EntityDefinition $definition,
  451.         OneToManyAssociationField $association,
  452.         Context $context,
  453.         EntityCollection $collection,
  454.         Criteria $fieldCriteria,
  455.         array $partial
  456.     ): void {
  457.         $isPartial $partial !== [];
  458.         $propertyAccessor $this->buildOneToManyPropertyAccessor($definition$association);
  459.         // inject sorting for foreign key, otherwise the internal counter wouldn't work `order by customer_address.customer_id, other_sortings`
  460.         $sorting array_merge(
  461.             [new FieldSorting($propertyAccessorFieldSorting::ASCENDING)],
  462.             $fieldCriteria->getSorting()
  463.         );
  464.         $fieldCriteria->resetSorting();
  465.         $fieldCriteria->addSorting(...$sorting);
  466.         $ids array_values($collection->getIds());
  467.         if ($isPartial) {
  468.             // Make sure our collection index will be loaded
  469.             $partial[$association->getPropertyName()] = [];
  470.         }
  471.         $isInheritanceAware $definition->isInheritanceAware() && $context->considerInheritance();
  472.         if ($isInheritanceAware) {
  473.             $parentIds array_values(array_filter($collection->map(fn (Entity $entity) => $entity->get('parentId'))));
  474.             $ids array_unique([...$ids, ...$parentIds]);
  475.         }
  476.         $fieldCriteria->addFilter(new EqualsAnyFilter($propertyAccessor$ids));
  477.         $mapping $this->fetchPaginatedOneToManyMapping($definition$association$context$collection$fieldCriteria);
  478.         $ids = [];
  479.         foreach ($mapping as $associationIds) {
  480.             foreach ($associationIds as $associationId) {
  481.                 $ids[] = $associationId;
  482.             }
  483.         }
  484.         $fieldCriteria->setIds(array_filter($ids));
  485.         $fieldCriteria->resetSorting();
  486.         $fieldCriteria->resetFilters();
  487.         $fieldCriteria->resetPostFilters();
  488.         $referenceClass $association->getReferenceDefinition();
  489.         /** @var EntityCollection<Entity> $collectionClass */
  490.         $collectionClass $referenceClass->getCollectionClass();
  491.         $data $this->_read(
  492.             $fieldCriteria,
  493.             $referenceClass,
  494.             $context,
  495.             new $collectionClass(),
  496.             $referenceClass->getFields()->getBasicFields(),
  497.             false,
  498.             $partial
  499.         );
  500.         //assign loaded reference collections to root entities
  501.         /** @var Entity $entity */
  502.         foreach ($collection as $entity) {
  503.             //extract mapping ids for the current entity
  504.             $mappingIds $mapping[$entity->getUniqueIdentifier()];
  505.             $structData $data->getList($mappingIds);
  506.             //assign data of child immediately
  507.             if ($association->is(Extension::class)) {
  508.                 $entity->addExtension($association->getPropertyName(), $structData);
  509.             } else {
  510.                 $entity->assign([$association->getPropertyName() => $structData]);
  511.             }
  512.             if (!$association->is(Inherited::class) || $structData->count() > || !$context->considerInheritance()) {
  513.                 continue;
  514.             }
  515.             $parentId $entity->get('parentId');
  516.             if ($parentId === null) {
  517.                 continue;
  518.             }
  519.             //extract mapping ids for the current entity
  520.             $mappingIds $mapping[$parentId];
  521.             $structData $data->getList($mappingIds);
  522.             //assign data of child immediately
  523.             if ($association->is(Extension::class)) {
  524.                 $entity->addExtension($association->getPropertyName(), $structData);
  525.             } else {
  526.                 $entity->assign([$association->getPropertyName() => $structData]);
  527.             }
  528.         }
  529.     }
  530.     /**
  531.      * @param EntityCollection<Entity> $collection
  532.      * @param array<string,mixed> $partial
  533.      */
  534.     private function loadManyToManyOverExtension(
  535.         Criteria $criteria,
  536.         ManyToManyAssociationField $association,
  537.         Context $context,
  538.         EntityCollection $collection,
  539.         array $partial
  540.     ): void {
  541.         //collect all ids of many to many association which already stored inside the struct instances
  542.         $ids $this->collectManyToManyIds($collection$association);
  543.         $criteria->setIds($ids);
  544.         $referenceClass $association->getToManyReferenceDefinition();
  545.         /** @var EntityCollection<Entity> $collectionClass */
  546.         $collectionClass $referenceClass->getCollectionClass();
  547.         $data $this->_read(
  548.             $criteria,
  549.             $referenceClass,
  550.             $context,
  551.             new $collectionClass(),
  552.             $referenceClass->getFields()->getBasicFields(),
  553.             false,
  554.             $partial
  555.         );
  556.         /** @var Entity $struct */
  557.         foreach ($collection as $struct) {
  558.             /** @var ArrayEntity $extension */
  559.             $extension $struct->getExtension(self::INTERNAL_MAPPING_STORAGE);
  560.             //use assign function to avoid setter name building
  561.             $structData $data->getList(
  562.                 $extension->get($association->getPropertyName())
  563.             );
  564.             //if the association is added as extension (for plugins), we have to add the data as extension
  565.             if ($association->is(Extension::class)) {
  566.                 $struct->addExtension($association->getPropertyName(), $structData);
  567.             } else {
  568.                 $struct->assign([$association->getPropertyName() => $structData]);
  569.             }
  570.         }
  571.     }
  572.     /**
  573.      * @param EntityCollection<Entity> $collection
  574.      * @param array<string,mixed> $partial
  575.      */
  576.     private function loadManyToManyWithCriteria(
  577.         Criteria $fieldCriteria,
  578.         ManyToManyAssociationField $association,
  579.         Context $context,
  580.         EntityCollection $collection,
  581.         array $partial
  582.     ): void {
  583.         $fields $association->getToManyReferenceDefinition()->getFields();
  584.         $reference null;
  585.         foreach ($fields as $field) {
  586.             if (!$field instanceof ManyToManyAssociationField) {
  587.                 continue;
  588.             }
  589.             if ($field->getReferenceDefinition() !== $association->getReferenceDefinition()) {
  590.                 continue;
  591.             }
  592.             $reference $field;
  593.             break;
  594.         }
  595.         if (!$reference) {
  596.             throw new \RuntimeException(
  597.                 sprintf(
  598.                     'No inverse many to many association found, for association %s',
  599.                     $association->getPropertyName()
  600.                 )
  601.             );
  602.         }
  603.         //build inverse accessor `product.categories.id`
  604.         $accessor $association->getToManyReferenceDefinition()->getEntityName() . '.' $reference->getPropertyName() . '.id';
  605.         $fieldCriteria->addFilter(new EqualsAnyFilter($accessor$collection->getIds()));
  606.         $root EntityDefinitionQueryHelper::escape(
  607.             $association->getToManyReferenceDefinition()->getEntityName() . '.' $reference->getPropertyName() . '.mapping'
  608.         );
  609.         $query = new QueryBuilder($this->connection);
  610.         // to many selects results in a `group by` clause. In this case the order by parts will be executed with MIN/MAX aggregation
  611.         // but at this point the order by will be moved to an sub select where we don't have a group state, the `state` prevents this behavior
  612.         $query->addState(self::MANY_TO_MANY_LIMIT_QUERY);
  613.         $query $this->criteriaQueryBuilder->build(
  614.             $query,
  615.             $association->getToManyReferenceDefinition(),
  616.             $fieldCriteria,
  617.             $context
  618.         );
  619.         $localColumn EntityDefinitionQueryHelper::escape($association->getMappingLocalColumn());
  620.         $referenceColumn EntityDefinitionQueryHelper::escape($association->getMappingReferenceColumn());
  621.         $orderBy '';
  622.         $parts $query->getQueryPart('orderBy');
  623.         if (!empty($parts)) {
  624.             $orderBy ' ORDER BY ' implode(', '$parts);
  625.             $query->resetQueryPart('orderBy');
  626.         }
  627.         // order by is handled in group_concat
  628.         $fieldCriteria->resetSorting();
  629.         $query->select([
  630.             'LOWER(HEX(' $root '.' $localColumn ')) as `key`',
  631.             'GROUP_CONCAT(LOWER(HEX(' $root '.' $referenceColumn ')) ' $orderBy ') as `value`',
  632.         ]);
  633.         $query->addGroupBy($root '.' $localColumn);
  634.         if ($fieldCriteria->getLimit() !== null) {
  635.             $limitQuery $this->buildManyToManyLimitQuery($association);
  636.             $params = [
  637.                 '#source_column#' => EntityDefinitionQueryHelper::escape($association->getMappingLocalColumn()),
  638.                 '#reference_column#' => EntityDefinitionQueryHelper::escape($association->getMappingReferenceColumn()),
  639.                 '#table#' => $root,
  640.             ];
  641.             $query->innerJoin(
  642.                 $root,
  643.                 '(' $limitQuery ')',
  644.                 'counter_table',
  645.                 str_replace(
  646.                     array_keys($params),
  647.                     array_values($params),
  648.                     'counter_table.#source_column# = #table#.#source_column# AND
  649.                      counter_table.#reference_column# = #table#.#reference_column# AND
  650.                      counter_table.id_count <= :limit'
  651.                 )
  652.             );
  653.             $query->setParameter('limit'$fieldCriteria->getLimit());
  654.             $this->connection->executeQuery('SET @n = 0; SET @c = null;');
  655.         }
  656.         $mapping $query->executeQuery()->fetchAllKeyValue();
  657.         $ids = [];
  658.         foreach ($mapping as &$row) {
  659.             $row array_filter(explode(',', (string) $row));
  660.             foreach ($row as $id) {
  661.                 $ids[] = $id;
  662.             }
  663.         }
  664.         unset($row);
  665.         $fieldCriteria->setIds($ids);
  666.         $referenceClass $association->getToManyReferenceDefinition();
  667.         /** @var EntityCollection<Entity> $collectionClass */
  668.         $collectionClass $referenceClass->getCollectionClass();
  669.         $data $this->_read(
  670.             $fieldCriteria,
  671.             $referenceClass,
  672.             $context,
  673.             new $collectionClass(),
  674.             $referenceClass->getFields()->getBasicFields(),
  675.             false,
  676.             $partial
  677.         );
  678.         /** @var Entity $struct */
  679.         foreach ($collection as $struct) {
  680.             $structData = new $collectionClass();
  681.             $id $struct->getUniqueIdentifier();
  682.             $parentId $struct->has('parentId') ? $struct->get('parentId') : '';
  683.             if (\array_key_exists($struct->getUniqueIdentifier(), $mapping)) {
  684.                 //filter mapping list of whole data array
  685.                 $structData $data->getList($mapping[$id]);
  686.                 //sort list by ids if the criteria contained a sorting
  687.                 $structData->sortByIdArray($mapping[$id]);
  688.             } elseif (\array_key_exists($parentId$mapping) && $association->is(Inherited::class) && $context->considerInheritance()) {
  689.                 //filter mapping for the inherited parent association
  690.                 $structData $data->getList($mapping[$parentId]);
  691.                 //sort list by ids if the criteria contained a sorting
  692.                 $structData->sortByIdArray($mapping[$parentId]);
  693.             }
  694.             //if the association is added as extension (for plugins), we have to add the data as extension
  695.             if ($association->is(Extension::class)) {
  696.                 $struct->addExtension($association->getPropertyName(), $structData);
  697.             } else {
  698.                 $struct->assign([$association->getPropertyName() => $structData]);
  699.             }
  700.         }
  701.     }
  702.     /**
  703.      * @param EntityCollection<Entity> $collection
  704.      *
  705.      * @return array<string,string[]>
  706.      */
  707.     private function fetchPaginatedOneToManyMapping(
  708.         EntityDefinition $definition,
  709.         OneToManyAssociationField $association,
  710.         Context $context,
  711.         EntityCollection $collection,
  712.         Criteria $fieldCriteria
  713.     ): array {
  714.         $sortings $fieldCriteria->getSorting();
  715.         // Remove first entry
  716.         array_shift($sortings);
  717.         //build query based on provided association criteria (sortings, search, filter)
  718.         $query $this->criteriaQueryBuilder->build(
  719.             new QueryBuilder($this->connection),
  720.             $association->getReferenceDefinition(),
  721.             $fieldCriteria,
  722.             $context
  723.         );
  724.         $foreignKey $association->getReferenceField();
  725.         if (!$association->getReferenceDefinition()->getField('id')) {
  726.             throw new \RuntimeException(
  727.                 sprintf(
  728.                     'Paginated to many association must have an id field. No id field found for association %s.%s',
  729.                     $definition->getEntityName(),
  730.                     $association->getPropertyName()
  731.                 )
  732.             );
  733.         }
  734.         //build sql accessor for foreign key field in reference table `customer_address.customer_id`
  735.         $sqlAccessor EntityDefinitionQueryHelper::escape($association->getReferenceDefinition()->getEntityName()) . '.'
  736.             EntityDefinitionQueryHelper::escape($foreignKey);
  737.         $query->select(
  738.             [
  739.                 //build select with an internal counter loop, the counter loop will be reset if the foreign key changed (this is the reason for the sorting inject above)
  740.                 '@n:=IF(@c=' $sqlAccessor ', @n+1, IF(@c:=' $sqlAccessor ',1,1)) as id_count',
  741.                 //add select for foreign key for join condition
  742.                 $sqlAccessor,
  743.                 //add primary key select to group concat them
  744.                 EntityDefinitionQueryHelper::escape($association->getReferenceDefinition()->getEntityName()) . '.id',
  745.             ]
  746.         );
  747.         foreach ($query->getQueryPart('orderBy') as $i => $sorting) {
  748.             // The first order is the primary key
  749.             if ($i === 0) {
  750.                 continue;
  751.             }
  752.             --$i;
  753.             // Strip the ASC/DESC at the end of the sort
  754.             $query->addSelect(\sprintf('%s as sort_%s'substr((string) $sorting0, -4), $i));
  755.         }
  756.         $root EntityDefinitionQueryHelper::escape($definition->getEntityName());
  757.         //create a wrapper query which select the root primary key and the grouped reference ids
  758.         $wrapper $this->connection->createQueryBuilder();
  759.         $wrapper->select(
  760.             [
  761.                 'LOWER(HEX(' $root '.id)) as id',
  762.                 'LOWER(HEX(child.id)) as child_id',
  763.             ]
  764.         );
  765.         foreach ($sortings as $i => $sorting) {
  766.             $wrapper->addOrderBy(sprintf('sort_%s'$i), $sorting->getDirection());
  767.         }
  768.         $wrapper->from($root$root);
  769.         //wrap query into a sub select to restrict the association count from the outer query
  770.         $wrapper->leftJoin(
  771.             $root,
  772.             '(' $query->getSQL() . ')',
  773.             'child',
  774.             'child.' $foreignKey ' = ' $root '.id AND id_count >= :offset AND id_count <= :limit'
  775.         );
  776.         //filter result to loaded root entities
  777.         $wrapper->andWhere($root '.id IN (:rootIds)');
  778.         $bytes $collection->map(
  779.             fn (Entity $entity) => Uuid::fromHexToBytes($entity->getUniqueIdentifier())
  780.         );
  781.         if ($definition->isInheritanceAware() && $context->considerInheritance()) {
  782.             /** @var Entity $entity */
  783.             foreach ($collection->getElements() as $entity) {
  784.                 if ($entity->get('parentId')) {
  785.                     $bytes[$entity->get('parentId')] = Uuid::fromHexToBytes($entity->get('parentId'));
  786.                 }
  787.             }
  788.         }
  789.         $wrapper->setParameter('rootIds'$bytesConnection::PARAM_STR_ARRAY);
  790.         $limit $fieldCriteria->getOffset() + $fieldCriteria->getLimit();
  791.         $offset $fieldCriteria->getOffset() + 1;
  792.         $wrapper->setParameter('limit'$limit);
  793.         $wrapper->setParameter('offset'$offset);
  794.         foreach ($query->getParameters() as $key => $value) {
  795.             $type $query->getParameterType($key);
  796.             $wrapper->setParameter($key$value$type);
  797.         }
  798.         //initials the cursor and loop counter, pdo do not allow to execute SET and SELECT in one statement
  799.         $this->connection->executeQuery('SET @n = 0; SET @c = null;');
  800.         $rows $wrapper->executeQuery()->fetchAllAssociative();
  801.         $grouped = [];
  802.         foreach ($rows as $row) {
  803.             $id = (string) $row['id'];
  804.             if (!isset($grouped[$id])) {
  805.                 $grouped[$id] = [];
  806.             }
  807.             if (empty($row['child_id'])) {
  808.                 continue;
  809.             }
  810.             $grouped[$id][] = (string) $row['child_id'];
  811.         }
  812.         return $grouped;
  813.     }
  814.     private function buildManyToManyLimitQuery(ManyToManyAssociationField $association): QueryBuilder
  815.     {
  816.         $table EntityDefinitionQueryHelper::escape($association->getMappingDefinition()->getEntityName());
  817.         $sourceColumn EntityDefinitionQueryHelper::escape($association->getMappingLocalColumn());
  818.         $referenceColumn EntityDefinitionQueryHelper::escape($association->getMappingReferenceColumn());
  819.         $params = [
  820.             '#table#' => $table,
  821.             '#source_column#' => $sourceColumn,
  822.         ];
  823.         $query = new QueryBuilder($this->connection);
  824.         $query->select([
  825.             str_replace(
  826.                 array_keys($params),
  827.                 array_values($params),
  828.                 '@n:=IF(@c=#table#.#source_column#, @n+1, IF(@c:=#table#.#source_column#,1,1)) as id_count'
  829.             ),
  830.             $table '.' $referenceColumn,
  831.             $table '.' $sourceColumn,
  832.         ]);
  833.         $query->from($table$table);
  834.         $query->orderBy($table '.' $sourceColumn);
  835.         return $query;
  836.     }
  837.     private function buildOneToManyPropertyAccessor(EntityDefinition $definitionOneToManyAssociationField $association): string
  838.     {
  839.         $reference $association->getReferenceDefinition();
  840.         if ($association instanceof ChildrenAssociationField) {
  841.             return $reference->getEntityName() . '.parentId';
  842.         }
  843.         $ref $reference->getFields()->getByStorageName(
  844.             $association->getReferenceField()
  845.         );
  846.         if (!$ref) {
  847.             throw new \RuntimeException(
  848.                 sprintf(
  849.                     'Reference field %s not found in definition %s for definition %s',
  850.                     $association->getReferenceField(),
  851.                     $reference->getEntityName(),
  852.                     $definition->getEntityName()
  853.                 )
  854.             );
  855.         }
  856.         return $reference->getEntityName() . '.' $ref->getPropertyName();
  857.     }
  858.     private function isAssociationRestricted(?Criteria $criteriastring $accessor): bool
  859.     {
  860.         if ($criteria === null) {
  861.             return false;
  862.         }
  863.         if (!$criteria->hasAssociation($accessor)) {
  864.             return false;
  865.         }
  866.         $fieldCriteria $criteria->getAssociation($accessor);
  867.         return $fieldCriteria->getOffset() !== null
  868.             || $fieldCriteria->getLimit() !== null
  869.             || !empty($fieldCriteria->getSorting())
  870.             || !empty($fieldCriteria->getFilters())
  871.             || !empty($fieldCriteria->getPostFilters())
  872.         ;
  873.     }
  874.     private function addAssociationFieldsToCriteria(
  875.         Criteria $criteria,
  876.         EntityDefinition $definition,
  877.         FieldCollection $fields
  878.     ): FieldCollection {
  879.         foreach ($criteria->getAssociations() as $fieldName => $_fieldCriteria) {
  880.             $field $definition->getFields()->get($fieldName);
  881.             if (!$field) {
  882.                 $this->logger->warning(
  883.                     sprintf('Criteria association "%s" could not be resolved. Double check your Criteria!'$fieldName)
  884.                 );
  885.                 continue;
  886.             }
  887.             $fields->add($field);
  888.         }
  889.         return $fields;
  890.     }
  891.     /**
  892.      * @param EntityCollection<Entity> $collection
  893.      * @param array<string,mixed> $partial
  894.      */
  895.     private function loadToOne(
  896.         AssociationField $association,
  897.         Context $context,
  898.         EntityCollection $collection,
  899.         Criteria $criteria,
  900.         array $partial
  901.     ): void {
  902.         if (!$association instanceof OneToOneAssociationField && !$association instanceof ManyToOneAssociationField) {
  903.             return;
  904.         }
  905.         if (!$criteria->hasAssociation($association->getPropertyName())) {
  906.             return;
  907.         }
  908.         $associationCriteria $criteria->getAssociation($association->getPropertyName());
  909.         if (!$associationCriteria->getAssociations()) {
  910.             return;
  911.         }
  912.         if (!$associationCriteria->getTitle() && $criteria->getTitle()) {
  913.             $associationCriteria->setTitle(
  914.                 $criteria->getTitle() . '::association::' $association->getPropertyName()
  915.             );
  916.         }
  917.         $related array_filter($collection->map(function (Entity $entity) use ($association) {
  918.             if ($association->is(Extension::class)) {
  919.                 return $entity->getExtension($association->getPropertyName());
  920.             }
  921.             return $entity->get($association->getPropertyName());
  922.         }));
  923.         $referenceDefinition $association->getReferenceDefinition();
  924.         $collectionClass $referenceDefinition->getCollectionClass();
  925.         if ($partial !== []) {
  926.             $collectionClass EntityCollection::class;
  927.         }
  928.         $fields $referenceDefinition->getFields()->getBasicFields();
  929.         $fields $this->addAssociationFieldsToCriteria($associationCriteria$referenceDefinition$fields);
  930.         // This line removes duplicate entries, so after fetchAssociations the association must be reassigned
  931.         $relatedCollection = new $collectionClass();
  932.         if (!$relatedCollection instanceof EntityCollection) {
  933.             throw new \RuntimeException(sprintf('Collection class %s has to be an instance of EntityCollection'$collectionClass));
  934.         }
  935.         $relatedCollection->fill($related);
  936.         $this->fetchAssociations($associationCriteria$referenceDefinition$context$relatedCollection$fields$partial);
  937.         /** @var Entity $entity */
  938.         foreach ($collection as $entity) {
  939.             if ($association->is(Extension::class)) {
  940.                 $item $entity->getExtension($association->getPropertyName());
  941.             } else {
  942.                 $item $entity->get($association->getPropertyName());
  943.             }
  944.             /** @var Entity|null $item */
  945.             if ($item === null) {
  946.                 continue;
  947.             }
  948.             if ($association->is(Extension::class)) {
  949.                 $entity->addExtension($association->getPropertyName(), $relatedCollection->get($item->getUniqueIdentifier()));
  950.                 continue;
  951.             }
  952.             $entity->assign([
  953.                 $association->getPropertyName() => $relatedCollection->get($item->getUniqueIdentifier()),
  954.             ]);
  955.         }
  956.     }
  957.     /**
  958.      * @param EntityCollection<Entity> $collection
  959.      * @param array<string,mixed> $partial
  960.      *
  961.      * @return EntityCollection<Entity>
  962.      */
  963.     private function fetchAssociations(
  964.         Criteria $criteria,
  965.         EntityDefinition $definition,
  966.         Context $context,
  967.         EntityCollection $collection,
  968.         FieldCollection $fields,
  969.         array $partial
  970.     ): EntityCollection {
  971.         if ($collection->count() <= 0) {
  972.             return $collection;
  973.         }
  974.         foreach ($fields as $association) {
  975.             if (!$association instanceof AssociationField) {
  976.                 continue;
  977.             }
  978.             if ($association instanceof OneToOneAssociationField || $association instanceof ManyToOneAssociationField) {
  979.                 $this->loadToOne($association$context$collection$criteria$partial[$association->getPropertyName()] ?? []);
  980.                 continue;
  981.             }
  982.             if ($association instanceof OneToManyAssociationField) {
  983.                 $this->loadOneToMany($criteria$definition$association$context$collection$partial[$association->getPropertyName()] ?? []);
  984.                 continue;
  985.             }
  986.             if ($association instanceof ManyToManyAssociationField) {
  987.                 $this->loadManyToMany($criteria$association$context$collection$partial[$association->getPropertyName()] ?? []);
  988.             }
  989.         }
  990.         foreach ($collection as $struct) {
  991.             $struct->removeExtension(self::INTERNAL_MAPPING_STORAGE);
  992.         }
  993.         return $collection;
  994.     }
  995. }