You are here

public function LogAutocompleteController::autocomplete in Log entity 2.x

Retrieves suggestions for log name autocompletion.

Parameters

string $log_bundle: The log bundle name.

\Symfony\Component\HttpFoundation\Request $request: The current request.

Return value

\Symfony\Component\HttpFoundation\JsonResponse A JSON response containing autocomplete suggestions.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

1 string reference to 'LogAutocompleteController::autocomplete'
log.routing.yml in ./log.routing.yml
log.routing.yml

File

src/Controller/LogAutocompleteController.php, line 56

Class

LogAutocompleteController
Returns autocomplete responses for log names.

Namespace

Drupal\log\Controller

Code

public function autocomplete(string $log_bundle, Request $request) {
  $matches = [];
  if ($input = $request->query
    ->get('q')) {

    // A regular database query is used so the results returned can be sorted
    // by usage.
    $table_mapping = $this
      ->entityTypeManager()
      ->getStorage('log')
      ->getTableMapping();
    $query = $this->database
      ->select($table_mapping
      ->getDataTable(), 'log_field_data');
    $query
      ->fields('log_field_data', [
      'name',
    ]);
    $query
      ->addExpression('COUNT(name)', 'count');
    $query
      ->condition('type', $log_bundle);
    $query
      ->condition('name', '%' . $this->database
      ->escapeLike($input) . '%', 'LIKE');

    // Because a regular database query is used to sort by the usage of the
    // log names, a minimal access control is done here.
    // If the user has administer log or can view any log entity from any
    // bundle, no further condition is added, if the user can see their own
    // entities, the query is restricted by user, otherwise an empty set is
    // returned.
    switch ($this
      ->typeOfAccess($log_bundle)) {
      case 'none':
        return new JsonResponse([]);
      case 'own':
        $query
          ->condition('uid', $this
          ->currentUser()
          ->id());
        break;
      case 'any':
      default:
    }
    $query
      ->groupBy('name');
    $query
      ->orderBy('count', 'DESC');
    $query
      ->orderBy('name', 'ASC');
    $matches = $query
      ->execute()
      ->fetchCol();
  }
  return new JsonResponse($matches);
}