jsonapi_search_api-8.x-1.x-dev/modules/jsonapi_search_api_facets/src/Plugin/facets/facet_source/JsonApiFacets.php
modules/jsonapi_search_api_facets/src/Plugin/facets/facet_source/JsonApiFacets.php
<?php
namespace Drupal\jsonapi_search_api_facets\Plugin\facets\facet_source;
use Drupal\Core\Plugin\PluginDependencyTrait;
use Drupal\facets\Exception\Exception;
use Drupal\facets\Plugin\facets\facet_source\SearchApiBaseFacetSource;
use Drupal\search_api\Entity\Index;
use Drupal\search_api\Query\ResultSetInterface;
/**
* Provides a facet source for use in JSON:API.
*
* @FacetsFacetSource(
* id = "jsonapi_search_api_facets",
* deriver = "Drupal\jsonapi_search_api_facets\Plugin\facets\facet_source\JsonApiFacetsDeriver"
* )
*/
class JsonApiFacets extends SearchApiBaseFacetSource {
use PluginDependencyTrait;
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
$this->addDependency('module', 'jsonapi_search_api_facets');
return $this->dependencies;
}
/**
* Fills the facet entities with results from the facet source.
*
* @param \Drupal\facets\FacetInterface[] $facets
* The configured facets.
*/
public function fillFacetsWithResults(array $facets) {
// Check if the results for this search ID are already populated in the
// query helper.
$results = $this->searchApiQueryHelper->getResults(strtr('jsonapi_search_api:!index', ['!index' => $this->getIndex()->id()]));
if (!$results instanceof ResultSetInterface) {
return;
}
// Get our facet data.
$facet_results = $results->getExtraData('search_api_facets');
// If no data is found in the 'search_api_facets' extra data, we can stop
// execution here.
if ($facet_results === []) {
return;
}
// Loop over each facet and execute the build method from the given query
// type.
foreach ($facets as $facet) {
$configuration = [
'query' => $results->getQuery(),
'facet' => $facet,
'results' => $facet_results[$facet->getFieldIdentifier()] ?? [],
];
// Get the Facet Specific Query Type so we can process the results
// using the build() function of the query type.
$query_type = $this->queryTypePluginManager->createInstance($facet->getQueryType(), $configuration);
$query_type->build();
}
}
/**
* {@inheritdoc}
*/
public function getIndex() {
return Index::load($this->pluginDefinition['index']);
}
/**
* {@inheritdoc}
*/
public function getPath() {
return '';
}
/**
* {@inheritdoc}
*/
public function getDataDefinition($field_name) {
$field = $this->getIndex()->getField($field_name);
if ($field) {
return $field->getDataDefinition();
}
throw new Exception("Field with name {$field_name} does not have a definition");
}
/**
* {@inheritdoc}
*/
public function isRenderedInCurrentRequest() {
return TRUE;
}
}
