You are here

class ContextUIController in Context 8.0

Same name and namespace in other branches
  1. 8.4 modules/context_ui/src/Controller/ContextUIController.php \Drupal\context_ui\Controller\ContextUIController
  2. 8 modules/context_ui/src/Controller/ContextUIController.php \Drupal\context_ui\Controller\ContextUIController

Hierarchy

Expanded class hierarchy of ContextUIController

File

modules/context_ui/src/Controller/ContextUIController.php, line 22

Namespace

Drupal\context_ui\Controller
View source
class ContextUIController extends ControllerBase {

  /**
   * The context reaction manager.
   *
   * @var ContextReactionManager
   */
  protected $contextReactionManager;

  /**
   * The Context module context manager.
   *
   * @var ContextManager
   */
  protected $contextManager;

  /**
   * The Drupal core condition manager.
   *
   * @var ConditionManager
   */
  protected $conditionManager;

  /**
   * Construct a new context controller.
   *
   * @param ContextManager $contextManager
   *   The Context module context manager.
   *
   * @param ContextReactionManager $contextReactionManager
   *   The Context module context reaction plugin manager.
   *
   * @param ConditionManager $conditionManager
   *   The Drupal core condition manager.
   */
  function __construct(ContextManager $contextManager, ContextReactionManager $contextReactionManager, ConditionManager $conditionManager) {
    $this->contextManager = $contextManager;
    $this->contextReactionManager = $contextReactionManager;
    $this->conditionManager = $conditionManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('context.manager'), $container
      ->get('plugin.manager.context_reaction'), $container
      ->get('plugin.manager.condition'));
  }

  /**
   * Retrieves group suggestions for a context.
   *
   * @param Request $request
   *   The current request.
   *
   * @return JsonResponse
   *   A JSON response with groups matching the query.
   */
  public function groupsAutocomplete(Request $request) {
    $query = $request->query
      ->get('q');
    $matches = [];
    foreach ($this->contextManager
      ->getContexts() as $context) {
      if (stripos($context
        ->getGroup(), $query) === 0) {
        $matches[] = $context
          ->getGroup();
      }
    }
    $response = [];

    // Format the unique matches to be used with the autocomplete field.
    foreach (array_unique($matches) as $match) {
      $response[] = [
        'value' => $match,
        'label' => Html::escape($match),
      ];
    }
    return new JsonResponse($response);
  }

  /**
   * Displays a list of conditions that can be added to the context.
   *
   * @param ContextInterface $context
   *   The context to display available conditions for.
   *
   * @return array
   */
  public function listConditions(ContextInterface $context) {

    // Get a list of all available conditions.
    $conditions = $this->conditionManager
      ->getDefinitions();
    $header = [
      $this
        ->t('Condition'),
    ];
    $build['filter'] = [
      '#type' => 'search',
      '#title' => $this
        ->t('Filter'),
      '#title_display' => 'invisible',
      '#size' => 30,
      '#placeholder' => $this
        ->t('Filter by condition name'),
      '#attributes' => [
        'class' => [
          'context-table-filter',
        ],
        'data-element' => '.condition-add-table',
        'title' => $this
          ->t('Enter a part of the condition name to filter by.'),
      ],
    ];
    $rows = [];

    // Add a table row for each condition.
    foreach ($conditions as $condition_id => $condition) {

      // Only add the condition to the list of it's not already been added to
      // the context.
      if ($context
        ->hasCondition($condition_id)) {
        continue;
      }
      $rows[] = [
        'condition' => [
          'data' => [
            '#type' => 'link',
            '#title' => $condition['label'],
            '#url' => Url::fromRoute('context.condition_add', [
              'context' => $context
                ->id(),
              'condition_id' => $condition_id,
            ]),
            '#attributes' => [
              'class' => [
                'use-ajax',
                'context-table-filter-text-source',
              ],
            ],
            '#options' => [
              'html' => TRUE,
            ],
          ],
        ],
      ];
    }
    $build['conditions'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this
        ->t('There are no conditions left that can be added to this context.'),
      '#attributes' => [
        'class' => [
          'condition-add-table',
        ],
      ],
    ];
    $build['#attached']['library'][] = 'context_ui/admin';
    return $build;
  }

  /**
   * Displays a list of reactions that can be added to the context.
   *
   * @param ContextInterface $context
   *   The context to display available
   *
   * @return array
   */
  public function listReactions(ContextInterface $context) {

    // Get a list of all available conditions.
    $reactions = $this->contextReactionManager
      ->getDefinitions();
    $header = [
      $this
        ->t('Reactions'),
    ];
    $build['filter'] = [
      '#type' => 'search',
      '#title' => $this
        ->t('Filter'),
      '#title_display' => 'invisible',
      '#size' => 30,
      '#placeholder' => $this
        ->t('Filter by reaction name'),
      '#attributes' => [
        'class' => [
          'context-table-filter',
        ],
        'data-element' => '.reaction-add-table',
        'title' => $this
          ->t('Enter a part of the reaction name to filter by.'),
      ],
    ];
    $rows = [];

    // Add a table row for each context reaction.
    foreach ($reactions as $reaction_id => $reaction) {

      // Only add the reaction to the list of it's not already been added to
      // the context.
      if ($context
        ->hasReaction($reaction_id)) {
        continue;
      }
      $rows[] = [
        'reaction' => [
          'data' => [
            '#type' => 'link',
            '#title' => $reaction['label'],
            '#url' => Url::fromRoute('context.reaction_add', [
              'context' => $context
                ->id(),
              'reaction_id' => $reaction_id,
            ]),
            '#attributes' => [
              'class' => [
                'use-ajax',
                'context-table-filter-text-source',
              ],
            ],
            '#options' => [
              'html' => TRUE,
            ],
            '#ajax' => TRUE,
          ],
        ],
      ];
    }
    $build['reactions'] = [
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this
        ->t('There are no reactions left that can be added to this context.'),
      '#attributes' => [
        'class' => [
          'reaction-add-table',
        ],
      ],
    ];
    $build['#attached']['library'][] = 'context_ui/admin';
    return $build;
  }

  /**
   * Add the specified reaction to the context.
   *
   * @param Request $request
   *   The current request.
   *
   * @param ContextInterface $context
   *   The context to add the reaction to.
   *
   * @param $reaction_id
   *   The ID of the reaction to add.
   *
   * @return AjaxResponse|RedirectResponse
   */
  public function addReaction(Request $request, ContextInterface $context, $reaction_id) {
    if ($context
      ->hasReaction($reaction_id)) {
      throw new HttpException(403, 'The specified condition had already been added to the context.');
    }

    // Create an instance of the reaction and add it to the context.
    try {
      $reaction = $this->contextReactionManager
        ->createInstance($reaction_id);
    } catch (PluginException $e) {
      throw new HttpException(400, $e
        ->getMessage());
    }
    $context
      ->addReaction($reaction
      ->getConfiguration());
    $context
      ->save();

    // If the request is an AJAX request then return an AJAX response with
    // commands to replace the content on the page.
    if ($request
      ->isXmlHttpRequest()) {
      $response = new AjaxResponse();
      $contextForm = $this->contextManager
        ->getForm($context, 'edit');
      $response
        ->addCommand(new CloseModalDialogCommand());
      $response
        ->addCommand(new ReplaceCommand('#context-reactions', $contextForm['reactions']));
      return $response;
    }
    $url = $context
      ->urlInfo('edit-form');
    return $this
      ->redirect($url
      ->getRouteName(), $url
      ->getRouteParameters());
  }

  /**
   * Add the specified condition to the context.
   *
   * @param Request $request
   *   The current request.
   *
   * @param ContextInterface $context
   *   The context to add the condition to.
   *
   * @param $condition_id
   *   The ID of the condition to add.
   *
   * @return AjaxResponse|RedirectResponse
   */
  public function addCondition(Request $request, ContextInterface $context, $condition_id) {
    if ($context
      ->hasCondition($condition_id)) {
      throw new HttpException(403, 'The specified condition had already been added to the context.');
    }

    // Create an instance of the condition and add it to the context.
    try {
      $condition = $this->conditionManager
        ->createInstance($condition_id);
    } catch (PluginException $e) {
      throw new HttpException(400, $e
        ->getMessage());
    }
    $context
      ->addCondition($condition
      ->getConfiguration());
    $context
      ->save();

    // If the request is an AJAX request then return an AJAX response with
    // commands to replace the content on the page.
    if ($request
      ->isXmlHttpRequest()) {
      $response = new AjaxResponse();
      $contextForm = $this->contextManager
        ->getForm($context, 'edit');
      $response
        ->addCommand(new CloseModalDialogCommand());
      $response
        ->addCommand(new ReplaceCommand('#context-conditions', $contextForm['conditions']));
      return $response;
    }
    $url = $context
      ->urlInfo('edit-form');
    return $this
      ->redirect($url
      ->getRouteName(), $url
      ->getRouteParameters());
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ContextUIController::$conditionManager protected property The Drupal core condition manager.
ContextUIController::$contextManager protected property The Context module context manager.
ContextUIController::$contextReactionManager protected property The context reaction manager.
ContextUIController::addCondition public function Add the specified condition to the context.
ContextUIController::addReaction public function Add the specified reaction to the context.
ContextUIController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
ContextUIController::groupsAutocomplete public function Retrieves group suggestions for a context.
ContextUIController::listConditions public function Displays a list of conditions that can be added to the context.
ContextUIController::listReactions public function Displays a list of reactions that can be added to the context.
ContextUIController::__construct function Construct a new context controller.
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.
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 protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
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.