You are here

class IndexController in Search API 8

Provides route responses for search indexes.

Hierarchy

Expanded class hierarchy of IndexController

File

src/Controller/IndexController.php, line 20

Namespace

Drupal\search_api\Controller
View source
class IndexController extends ControllerBase {

  /**
   * The request stack.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack|null
   */
  protected $requestStack;

  /**
   * The messenger.
   *
   * @var \Drupal\Core\Messenger\MessengerInterface|null
   */
  protected $messenger;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    /** @var static $controller */
    $controller = parent::create($container);
    $controller
      ->setRequestStack($container
      ->get('request_stack'));
    $controller
      ->setMessenger($container
      ->get('messenger'));
    return $controller;
  }

  /**
   * Retrieves the request stack.
   *
   * @return \Symfony\Component\HttpFoundation\RequestStack
   *   The request stack.
   */
  public function getRequestStack() {
    return $this->requestStack ?: \Drupal::service('request_stack');
  }

  /**
   * Retrieves the current request.
   *
   * @return \Symfony\Component\HttpFoundation\Request|null
   *   The current request.
   */
  public function getRequest() {
    return $this
      ->getRequestStack()
      ->getCurrentRequest();
  }

  /**
   * Sets the request stack.
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The new request stack.
   *
   * @return $this
   */
  public function setRequestStack(RequestStack $request_stack) {
    $this->requestStack = $request_stack;
    return $this;
  }

  /**
   * Retrieves the messenger.
   *
   * @return \Drupal\Core\Messenger\MessengerInterface
   *   The messenger.
   */
  public function getMessenger() {
    return $this->messenger ?: \Drupal::service('messenger');
  }

  /**
   * Sets the messenger.
   *
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   *   The new messenger.
   *
   * @return $this
   */
  public function setMessenger(MessengerInterface $messenger) {
    $this->messenger = $messenger;
    return $this;
  }

  /**
   * Displays information about a search index.
   *
   * @param \Drupal\search_api\IndexInterface $search_api_index
   *   The index to display.
   *
   * @return array
   *   An array suitable for drupal_render().
   */
  public function page(IndexInterface $search_api_index) {

    // Build the search index information.
    $render = [
      'view' => [
        '#theme' => 'search_api_index',
        '#index' => $search_api_index,
      ],
    ];

    // Check if the index is enabled and can be written to.
    if ($search_api_index
      ->status() && !$search_api_index
      ->isReadOnly()) {

      // Attach the index status form.
      $render['form'] = $this
        ->formBuilder()
        ->getForm('Drupal\\search_api\\Form\\IndexStatusForm', $search_api_index);
    }
    return $render;
  }

  /**
   * Returns the page title for an index's "View" tab.
   *
   * @param \Drupal\search_api\IndexInterface $search_api_index
   *   The index that is displayed.
   *
   * @return string
   *   The page title.
   */
  public function pageTitle(IndexInterface $search_api_index) {
    return new FormattableMarkup('@title', [
      '@title' => $search_api_index
        ->label(),
    ]);
  }

  /**
   * Enables a search index without a confirmation form.
   *
   * @param \Drupal\search_api\IndexInterface $search_api_index
   *   The index to be enabled.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response to send to the browser.
   */
  public function indexBypassEnable(IndexInterface $search_api_index) {

    // Enable the index.
    $search_api_index
      ->setStatus(TRUE)
      ->save();

    // \Drupal\search_api\Entity\Index::preSave() doesn't allow an index to be
    // enabled if its server is not set or disabled.
    if ($search_api_index
      ->status()) {

      // Notify the user about the status change.
      $this
        ->getMessenger()
        ->addStatus($this
        ->t('The search index %name has been enabled.', [
        '%name' => $search_api_index
          ->label(),
      ]));
    }
    else {

      // Notify the user that the status change did not succeed.
      $this
        ->getMessenger()
        ->addWarning($this
        ->t('The search index %name could not be enabled. Check if its server is set and enabled.', [
        '%name' => $search_api_index
          ->label(),
      ]));
    }

    // Redirect to the index's "View" page.
    $url = $search_api_index
      ->toUrl('canonical');
    return $this
      ->redirect($url
      ->getRouteName(), $url
      ->getRouteParameters());
  }

  /**
   * Removes a field from a search index.
   *
   * @param \Drupal\search_api\IndexInterface $search_api_index
   *   The search index.
   * @param string $field_id
   *   The ID of the field to remove.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The response to send to the browser.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Thrown when the field was not found.
   */
  public function removeField(IndexInterface $search_api_index, $field_id) {
    $fields = $search_api_index
      ->getFields();
    $success = FALSE;
    if (isset($fields[$field_id])) {
      try {
        $search_api_index
          ->removeField($field_id);
        $search_api_index
          ->save();
        $success = TRUE;
      } catch (SearchApiException $e) {
        $args['%field'] = $fields[$field_id]
          ->getLabel();
        $this
          ->getMessenger()
          ->addError($this
          ->t('The field %field is locked and cannot be removed.', $args));
      }
    }
    else {
      throw new NotFoundHttpException();
    }

    // If this is an AJAX request, just remove the row in question.
    if ($success && $this
      ->getRequest()->request
      ->get(AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER)) {
      $response = new AjaxResponse();
      $response
        ->addCommand(new RemoveCommand("tr[data-field-row-id='{$field_id}']"));
      return $response;
    }

    // Redirect to the index's "Fields" page.
    $url = $search_api_index
      ->toUrl('fields');
    return $this
      ->redirect($url
      ->getRouteName(), $url
      ->getRouteParameters());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ControllerBase::$configFactory protected property The configuration factory.
ControllerBase::$currentUser protected property The current user service. 1
ControllerBase::$entityFormBuilder protected property The entity form builder.
ControllerBase::$entityManager protected property The entity manager.
ControllerBase::$entityTypeManager protected property The entity type manager.
ControllerBase::$formBuilder protected property The form builder. 2
ControllerBase::$keyValue protected property The key-value storage. 1
ControllerBase::$languageManager protected property The language manager. 1
ControllerBase::$moduleHandler protected property The module handler. 2
ControllerBase::$stateService protected property The state service.
ControllerBase::cache protected function Returns the requested cache bin.
ControllerBase::config protected function Retrieves a configuration object.
ControllerBase::container private function Returns the service container.
ControllerBase::currentUser protected function Returns the current user. 1
ControllerBase::entityFormBuilder protected function Retrieves the entity form builder.
ControllerBase::entityManager Deprecated protected function Retrieves the entity manager service.
ControllerBase::entityTypeManager protected function Retrieves the entity type manager.
ControllerBase::formBuilder protected function Returns the form builder service. 2
ControllerBase::keyValue protected function Returns a key/value storage collection. 1
ControllerBase::languageManager protected function Returns the language manager service. 1
ControllerBase::moduleHandler protected function Returns the module handler. 2
ControllerBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
ControllerBase::state protected function Returns the state storage service.
IndexController::$messenger protected property The messenger. Overrides MessengerTrait::$messenger
IndexController::$requestStack protected property The request stack.
IndexController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
IndexController::getMessenger public function Retrieves the messenger.
IndexController::getRequest public function Retrieves the current request.
IndexController::getRequestStack public function Retrieves the request stack.
IndexController::indexBypassEnable public function Enables a search index without a confirmation form.
IndexController::page public function Displays information about a search index.
IndexController::pageTitle public function Returns the page title for an index's "View" tab.
IndexController::removeField public function Removes a field from a search index.
IndexController::setMessenger public function Sets the messenger. Overrides MessengerTrait::setMessenger
IndexController::setRequestStack public function Sets the request stack.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::messenger public function Gets the messenger. 29
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.