SearchApiSortsManager.php in Search API sorts 8
File
src/SearchApiSortsManager.php
View source
<?php
namespace Drupal\search_api_sorts;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\search_api\Display\DisplayInterface;
use Drupal\search_api\Display\DisplayPluginManagerInterface;
use Drupal\search_api\IndexInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class SearchApiSortsManager implements SearchApiSortsManagerInterface {
use ConfigIdEscapeTrait;
protected $currentRequest;
protected $moduleHandler;
protected $searchApiSortsFieldStorage;
protected $searchApiDisplayManager;
public function __construct(RequestStack $request_stack, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, DisplayPluginManagerInterface $searchApiDisplayManager) {
$this->currentRequest = $request_stack
->getCurrentRequest();
$this->searchApiSortsFieldStorage = $entity_type_manager
->getStorage('search_api_sorts_field');
$this->moduleHandler = $module_handler;
$this->searchApiDisplayManager = $searchApiDisplayManager;
}
public function getActiveSort(DisplayInterface $display) {
$order = strtolower($this->currentRequest
->get('order')) === 'desc' ? 'desc' : 'asc';
$active_sort = new SortsField($this->currentRequest
->get('sort'), $order);
if ($active_sort
->getFieldName()) {
$this->moduleHandler
->alter('search_api_sorts_active_sort', $active_sort, $display);
}
return $active_sort;
}
public function getEnabledSorts(DisplayInterface $display) {
return $this->searchApiSortsFieldStorage
->loadByProperties([
'status' => TRUE,
'display_id' => $this
->getEscapedConfigId($display
->getPluginId()),
]);
}
protected function getSorts(DisplayInterface $display) {
return $this->searchApiSortsFieldStorage
->loadByProperties([
'display_id' => $this
->getEscapedConfigId($display
->getPluginId()),
]);
}
public function getDefaultSort(DisplayInterface $display) {
$default_sort = new SortsField('search_api_relevance', 'desc');
foreach ($this
->getEnabledSorts($display) as $enabled_sort) {
if ($enabled_sort
->getDefaultSort()) {
$default_sort = new SortsField($enabled_sort
->getFieldIdentifier(), $enabled_sort
->getDefaultOrder());
}
}
$this->moduleHandler
->alter('search_api_sorts_default_sort', $default_sort, $display);
return $default_sort;
}
public function cleanupSortFields(IndexInterface $index) {
foreach ($this->searchApiDisplayManager
->getInstances() as $display) {
if ($display
->getIndex() instanceof IndexInterface && $index
->id() === $display
->getIndex()
->id()) {
foreach ($this
->getSorts($display) as $search_api_sorts_field) {
if ($search_api_sorts_field
->getFieldIdentifier() === 'search_api_relevance') {
continue;
}
$field = $index
->getField($search_api_sorts_field
->getFieldIdentifier());
if ($field === NULL) {
$search_api_sorts_field
->delete();
}
}
}
}
}
}