aggregate example

    $matches = [];
    preg_match('/node\/([0-9]+)/', $this->getUrl()$matches);
    return $matches[1] ?? FALSE;
  }

  /** * Retrieves the fid of the last inserted file. */
  protected function getLastFileId() {
    return (int) \Drupal::entityQueryAggregate('file')
      ->accessCheck(FALSE)
      ->aggregate('fid', 'max')
      ->execute()[0]['fid_max'];
  }

}
/** * @return array<int, int|string> */
    public function getAuthors(Context $context): array
    {
        $files = $this->snippetFileCollection->toArray();

        $criteria = new Criteria();
        $criteria->addAggregation(new TermsAggregation('distinct_author', 'author'));

        /** @var TermsResult|null $aggregation */
        $aggregation = $this->snippetRepository->aggregate($criteria$context)
                ->get('distinct_author');

        if (!$aggregation || empty($aggregation->getBuckets())) {
            $result = [];
        } else {
            $result = $aggregation->getKeys();
        }

        $authors = array_flip($result);
        foreach ($files as $file) {
            $authors[$file['author']] = true;
        }
private readonly Client $client,
        private readonly EntityAggregatorInterface $decorated,
        private readonly AbstractElasticsearchAggregationHydrator $hydrator,
        private readonly EventDispatcherInterface $eventDispatcher,
        private readonly string $timeout = '5s'
    ) {
    }

    public function aggregate(EntityDefinition $definition, Criteria $criteria, Context $context): AggregationResultCollection
    {
        if (!$this->helper->allowSearch($definition$context$criteria)) {
            return $this->decorated->aggregate($definition$criteria$context);
        }

        $search = $this->createSearch($definition$criteria$context);

        $this->eventDispatcher->dispatch(
            new ElasticsearchEntityAggregatorSearchEvent($search$definition$criteria$context)
        );

        $searchArray = $search->toArray();
        $searchArray['timeout'] = $this->timeout;

        

    public function aggregate(string $entityName, array $criteria): AggregationResultCollection
    {
        $criteriaObject = $this->prepareCriteria($entityName$criteria);

        return $this->registry->getRepository($entityName)->aggregate($criteriaObject$this->context);
    }

    /** * @param array<string, mixed> $criteria */
    private function prepareCriteria(string $entityName, array $criteria): Criteria
    {
        $definition = $this->registry->getByEntityName($entityName);
        $criteriaObject = new Criteria();

        $this->criteriaBuilder->fromArray($criteria$criteriaObject$definition$this->context);

        
public function load(Criteria $origin, SalesChannelContext $context): EntitySearchResult
    {
        $origin->addState(Criteria::STATE_ELASTICSEARCH_AWARE);
        $criteria = clone $origin;

        $this->addGrouping($criteria);
        $this->handleAvailableStock($criteria$context);

        $ids = $this->productRepository->searchIds($criteria$context);
        /** @var list<string> $keys */
        $keys = $ids->getIds();
        $aggregations = $this->productRepository->aggregate($criteria$context);

        // no products found, no need to continue         if (empty($keys)) {
            return new EntitySearchResult(
                ProductDefinition::ENTITY_NAME,
                0,
                new ProductCollection(),
                $aggregations,
                $origin,
                $context->getContext()
            );
        }
if (!$criteria->getTitle()) {
            return $this->_search($criteria$context);
        }

        return Profiler::trace($criteria->getTitle()fn () => $this->_search($criteria$context), 'repository');
    }

    public function aggregate(Criteria $criteria, Context $context): AggregationResultCollection
    {
        $criteria = clone $criteria;

        $result = $this->aggregator->aggregate($this->definition, $criteria$context);

        $event = new EntityAggregationResultLoadedEvent($this->definition, $result$context);
        $this->eventDispatcher->dispatch($event$event->getName());

        return $result;
    }

    public function searchIds(Criteria $criteria, Context $context): IdSearchResult
    {
        $criteria = clone $criteria;

        
      $document['included'] = $this->serializer->normalize($object->getIncludes()$format$context)->omitIfEmpty();
      // Add omissions and metadata.       $normalized_omissions = $this->normalizeOmissionsLinks($object->getOmissions()$format$context);
      $meta = !$normalized_omissions instanceof CacheableOmission
        ? array_merge($object->getMeta()['omitted' => $normalized_omissions->getNormalization()])
        : $object->getMeta();
      $document['meta'] = (new CacheableNormalization($normalized_omissions$meta))->omitIfEmpty();
    }
    // Add document links.     $document['links'] = $this->serializer->normalize($object->getLinks()$format$context)->omitIfEmpty();
    // Every JSON:API document contains absolute URLs.     return CacheableNormalization::aggregate($document)->withCacheableDependency((new CacheableMetadata())->addCacheContexts(['url.site']));
  }

  /** * Normalizes an error collection. * * @param \Drupal\jsonapi\JsonApiResource\JsonApiDocumentTopLevel $document * The document to normalize. * @param string $format * The normalization format. * @param array $context * The normalization context. * * @return \Drupal\jsonapi\Normalizer\Value\CacheableNormalization * The normalized document. * * @todo: refactor this to use CacheableNormalization::aggregate in https://www.drupal.org/project/drupal/issues/3036284. */
$buyBox->setProduct($product);
            $buyBox->setProductId($product->getId());
            $buyBox->setConfiguratorSettings($this->configuratorLoader->load($product$resolverContext->getSalesChannelContext()));
            $buyBox->setTotalReviews($this->getReviewsCount($product$resolverContext->getSalesChannelContext()));
        }
    }

    private function getReviewsCount(SalesChannelProductEntity $product, SalesChannelContext $context): int
    {
        $reviewCriteria = $this->createReviewCriteria($context$product->getParentId() ?? $product->getId());

        $aggregation = $this->repository->aggregate($reviewCriteria$context->getContext())->get('review-count');

        return $aggregation instanceof CountResult ? $aggregation->getCount() : 0;
    }

    private function createReviewCriteria(SalesChannelContext $context, string $productId): Criteria
    {
        $reviewFilters = [];
        $criteria = new Criteria();

        $reviewFilters[] = new EqualsFilter('status', true);
        if ($context->getCustomer() !== null) {
            
        // is, some links target routes that depend on a request to determine if         // they're accessible or not. Some other links might target routes to         // which the current user will clearly not have access, in that case         // this code proactively removes those links from the response.         $access = $link->getUri()->access($this->currentUser, TRUE);
        $cacheability = CacheableMetadata::createFromObject($link)->addCacheableDependency($access);
        $normalized[$link_key] = $access->isAllowed()
          ? new CacheableNormalization($cacheability$normalization)
          : new CacheableOmission($cacheability);
      }
    }
    return CacheableNormalization::aggregate($normalized);
  }

  /** * Hashes a link using its href and its target attributes, if any. * * This method generates an unpredictable, but deterministic, 7 character * alphanumeric hash for a given link. * * The hash is unpredictable because a random hash salt will be used for every * request. The hash is deterministic because, within a single request, links * with the same href and target attributes (i.o.w. duplicates) will generate * equivalent hash values. * * @param \Drupal\jsonapi\JsonApiResource\Link $link * A link to be hashed. * * @return string * A 7 character alphanumeric hash. */
/** * {@inheritdoc} */
  public function normalize($field$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($field instanceof EntityReferenceFieldItemListInterface);
    // Build the relationship object based on the Entity Reference and normalize     // that object instead.     $resource_identifiers = array_filter(ResourceIdentifier::toResourceIdentifiers($field->filterEmptyItems())function DResourceIdentifierInterface $resource_identifier) {
      return !$resource_identifier->getResourceType()->isInternal();
    });
    $normalized_items = CacheableNormalization::aggregate($this->serializer->normalize($resource_identifiers$format$context));
    assert($context['resource_object'] instanceof ResourceObject);
    $resource_relationship = $context['resource_object']->getResourceType()->getFieldByInternalName($field->getName());
    assert($resource_relationship instanceof ResourceTypeRelationship);
    $link_cacheability = new CacheableMetadata();
    $links = array_map(function DUrl $link) use ($link_cacheability) {
      $href = $link->setAbsolute()->toString(TRUE);
      $link_cacheability->addCacheableDependency($href);
      return ['href' => $href->getGeneratedUrl()];
    }static::getRelationshipLinks($context['resource_object']$resource_relationship));
    $data_normalization = $normalized_items->getNormalization();
    $normalization = [
      
$function_expected = [];
    $function_expected['count'] = [['id_count' => 6]];
    $function_expected['min'] = [['id_min' => 1]];
    $function_expected['max'] = [['id_max' => 6]];
    $function_expected['sum'] = [['id_sum' => 21]];
    $function_expected['avg'] = [['id_avg' => (21.0 / 6.0)]];

    // Apply a simple aggregation for different aggregation functions.     foreach ($function_expected as $aggregation_function => $expected) {
      $query = $this->entityStorage->getAggregateQuery()
        ->accessCheck(FALSE)
        ->aggregate('id', $aggregation_function);
      $this->queryResult = $query->execute();
      // We need to check that a character exists before and after the table,       // column and alias identifiers. These would be the quote characters       // specific for each database system.       $this->assertMatchesRegularExpression('/' . $aggregation_function . '\(.*entity_test.\..id.\).* AS .id_' . $aggregation_function . './', (string) $query, 'The argument to the aggregation function should be a quoted field.');
      $this->assertEquals($expected$this->queryResult);
    }

    // Apply aggregation and groupby on the same query.     $this->queryResult = $this->entityStorage->getAggregateQuery()
      ->accessCheck(FALSE)
      

    public function aggregate(string $entityName, array $criteria): AggregationResultCollection
    {
        $criteriaObject = $this->prepareCriteria($entityName$criteria);

        return $this->registry->getSalesChannelRepository($entityName)->aggregate($criteriaObject$this->context);
    }

    /** * @param array<string, mixed> $criteria */
    private function prepareCriteria(string $entityName, array $criteria): Criteria
    {
        $definition = $this->registry->getByEntityName($entityName);
        $criteriaObject = new Criteria();

        $this->criteriaBuilder->fromArray($criteria$criteriaObject$definition$this->context->getContext());

        


  /** * Loads entity revision IDs using a pager sorted by the entity revision ID. * * @return array * An array of entity revision IDs. */
  protected function getEntityRevisionIds() {
    $query = $this->entityTypeManager->getStorage('content_moderation_state')->getAggregateQuery()
      ->accessCheck(TRUE)
      ->aggregate('content_entity_id', 'MAX')
      ->groupBy('content_entity_revision_id')
      ->condition('content_entity_type_id', $this->entityTypeId)
      ->condition('moderation_state', 'published', '<>')
      ->sort('content_entity_revision_id', 'DESC');

    // Only add the pager if a limit is specified.     if ($this->limit) {
      $query->pager($this->limit);
    }

    $result = $query->execute();

    
new EqualsFilter('themes.id', $themeId)]
            )
        );
        $criteria->addAggregation(
            new FilterAggregation(
                'assigned_children_filter',
                new TermsAggregation('assigned_children', 'themes.parentThemeId'),
                [new EqualsFilter('themes.parentThemeId', $themeId)]
            )
        );

        $aggregates = $this->salesChannelRepository->aggregate($criteria$context);

        /** @var TermsResult $directlyAssigned */
        $directlyAssigned = $aggregates->get('assigned_theme');

        /** @var TermsResult $assignedChildren */
        $assignedChildren = $aggregates->get('assigned_children');

        if (!empty($directlyAssigned->getKeys()) || !empty($assignedChildren->getKeys())) {
            throw StoreException::extensionThemeStillInUse($id);
        }
    }

    
$image_files = $this->drupalGetTestFiles('image');
    $this->image = File::create((array) current($image_files));

    [$this->imageExtension] = explode('.', $this->image->getFilename());
    $this->assertFileExists($this->image->getFileUri());

    $this->phpfile = current($this->drupalGetTestFiles('php'));
    $this->assertFileExists($this->phpfile->uri);

    $this->maxFidBefore = (int) \Drupal::entityQueryAggregate('file')
      ->accessCheck(FALSE)
      ->aggregate('fid', 'max')
      ->execute()[0]['fid_max'];

    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');
    // Upload with replace to guarantee there's something there.     $edit = [
      'file_test_replace' => FileSystemInterface::EXISTS_REPLACE,
      'files[file_test_upload][]' => $file_system->realpath($this->image->getFileUri()),
    ];
    $this->drupalGet('file-test/save_upload_from_form_test');
    $this->submitForm($edit, 'Submit');
    
Home | Imprint | This part of the site doesn't use cookies.