JsonApiFacets.php in JSON:API Search API 8
File
modules/jsonapi_search_api_facets/src/Plugin/facets/facet_source/JsonApiFacets.php
View source
<?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\facets\QueryType\QueryTypePluginManager;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Query\ResultSetInterface;
use Drupal\search_api\Utility\QueryHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;
class JsonApiFacets extends SearchApiBaseFacetSource {
use PluginDependencyTrait;
protected $index;
public function __construct(array $configuration, $plugin_id, $plugin_definition, QueryTypePluginManager $query_type_plugin_manager, QueryHelper $search_results_cache, IndexInterface $index) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $query_type_plugin_manager, $search_results_cache);
$this->index = $index;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$entity_type_manager = $container
->get('entity_type.manager');
$index = $entity_type_manager
->getStorage('search_api_index')
->load($plugin_definition['index']);
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('plugin.manager.facets.query_type'), $container
->get('search_api.query_helper'), $index);
}
public function calculateDependencies() {
$this
->addDependency('module', 'jsonapi_search_api_facets');
return $this->dependencies;
}
public function fillFacetsWithResults(array $facets) {
$results = $this->searchApiQueryHelper
->getResults(strtr('jsonapi_search_api:!index', [
'!index' => $this->index
->id(),
]));
if (!$results instanceof ResultSetInterface) {
return;
}
$facet_results = $results
->getExtraData('search_api_facets');
if ($facet_results === []) {
return;
}
foreach ($facets as $facet) {
$configuration = [
'query' => $results
->getQuery(),
'facet' => $facet,
'results' => $facet_results[$facet
->getFieldIdentifier()] ?? [],
];
$query_type = $this->queryTypePluginManager
->createInstance($facet
->getQueryType(), $configuration);
$query_type
->build();
}
}
public function getPath() {
}
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");
}
public function getIndex() {
return $this->index;
}
public function isRenderedInCurrentRequest() {
return TRUE;
}
}