AutocompleteHelper.php in Search API Autocomplete 8
File
src/Utility/AutocompleteHelper.php
View source
<?php
namespace Drupal\search_api_autocomplete\Utility;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultReasonInterface;
use Drupal\Core\Render\ElementInfoManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\search_api_autocomplete\SearchInterface;
class AutocompleteHelper implements AutocompleteHelperInterface {
protected $elementInfo;
public function __construct(ElementInfoManagerInterface $element_info) {
$this->elementInfo = $element_info;
}
public function splitKeys($keys) {
$keys = ltrim($keys);
if (rtrim($keys, " \"") != $keys) {
return [
rtrim($keys, ' '),
'',
];
}
if (preg_match('/^(.*?)\\s*"?([\\S]*)$/', $keys, $m)) {
return [
$m[1],
$m[2],
];
}
return [
'',
$keys,
];
}
public function alterElement(array &$element, SearchInterface $search, array $data = []) {
$element['#type'] = 'search_api_autocomplete';
$element['#search_id'] = $search
->id();
$element['#additional_data'] = $data;
$info = $this->elementInfo
->getInfo('search_api_autocomplete');
if (!empty($info['#process'])) {
$old_process = $element['#process'] ?? [];
$element['#process'] = array_merge($old_process, $info['#process']);
}
}
public function access(SearchInterface $search_api_autocomplete_search, AccountInterface $account) {
$search = $search_api_autocomplete_search;
$permission = 'use search_api_autocomplete for ' . $search
->id();
$access = AccessResult::allowedIf($search
->status())
->andIf(AccessResult::allowedIf($search
->hasValidIndex() && $search
->getIndex()
->status()))
->andIf(AccessResult::allowedIfHasPermissions($account, [
$permission,
'administer search_api_autocomplete',
], 'OR'))
->addCacheableDependency($search);
if ($access instanceof AccessResultReasonInterface) {
$access
->setReason("The \"{$permission}\" permission is required and autocomplete for this search must be enabled.");
}
return $access;
}
}