You are here

class TBMegaMenuAdminController in The Better Mega Menu 8

Same name and namespace in other branches
  1. 2.x src/Controller/TBMegaMenuAdminController.php \Drupal\tb_megamenu\Controller\TBMegaMenuAdminController

Handler for configuring and saving MegaMenu settings.

Hierarchy

Expanded class hierarchy of TBMegaMenuAdminController

File

src/Controller/TBMegaMenuAdminController.php, line 21

Namespace

Drupal\tb_megamenu\Controller
View source
class TBMegaMenuAdminController extends ControllerBase {

  /**
   * The menu tree service.
   *
   * @var \Drupal\Core\Menu\MenuLinkTreeInterface
   */
  protected $menuTree;

  /**
   * The renderer service.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The menu builder service.
   *
   * @var \Drupal\tb_megamenu\TBMegaMenuBuilderInterface
   */
  private $menuBuilder;

  /**
   * Constructs a TBMegaMenuAdminController object.
   *
   * @param \Drupal\Core\Menu\MenuLinkTreeInterface $menu_tree
   *   The Menu Link Tree service.
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The renderer service.
   * @param \Drupal\tb_megamenu\TBMegaMenuBuilderInterface $menu_builder
   *   The menu builder service.
   */
  public function __construct(MenuLinkTreeInterface $menu_tree, RendererInterface $renderer, TBMegaMenuBuilderInterface $menu_builder) {
    $this->menuTree = $menu_tree;
    $this->renderer = $renderer;
    $this->menuBuilder = $menu_builder;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('menu.link_tree'), $container
      ->get('renderer'), $container
      ->get('tb_megamenu.menu_builder'));
  }

  /**
   * Ajax callback for admin screen.
   *
   * Handles:  Save, Reset, and add block requests.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   A string response with either a success/error message or just data.
   */
  public function saveConfiguration(Request $request) {
    $data = NULL;
    $action = '';
    $result = 'Invalid TB Megamenu Ajax request!';

    // All ajax calls should use json data now.
    if ($request
      ->getContentType() == 'json') {
      $data = Json::decode($request
        ->getContent());
      $action = $data['action'];
    }

    // Assemble the appropriate Ajax response for the current action.
    switch ($action) {
      case 'load':
        $result = self::loadMenuConfig($data);
        break;
      case 'save':
        $result = self::saveMenuConfig($data);
        break;
      case 'load_block':
        $result = self::loadMenuBlock($data);
        break;
      default:
        break;
    }

    // Return the response message and status code.
    $response = new Response($result['message']);
    $response
      ->setStatusCode($result['code']);
    return $response;
  }

  /**
   * Loads a menu configuration.
   *
   * @param array $data
   *   A decoded JSON object used to load the configuration.
   *
   * @return array
   *   The message and status code indicating the result of the load attempt.
   */
  public function loadMenuConfig(array $data) {
    $menu_name = self::getMenuName($data);
    $theme = self::getTheme($data);
    $code = 200;

    // Attempt to load the menu config.
    if ($menu_name && $theme) {
      $renderable_array = $this->menuBuilder
        ->renderBlock($menu_name, $theme);
      $result = $this->renderer
        ->render($renderable_array)
        ->__toString();
    }
    else {
      $result = self::saveError('load_config');
      $code = 500;
    }
    return [
      'message' => $result,
      'code' => $code,
    ];
  }

  /**
   * Saves a menu configuration.
   *
   * @param array $data
   *   A decoded JSON object used to save the configuration.
   *
   * @return array
   *   The message and status code indicating the result of the save attempt.
   */
  public function saveMenuConfig(array $data) {
    $menu_config = self::getMenuConfig($data);
    $block_config = self::getBlockConfig($data);
    $menu_name = self::getMenuName($data);
    $theme = self::getTheme($data);
    $code = 200;

    // Ensure the config can be loaded before proceeding.
    $config = MegaMenuConfig::loadMenu($menu_name, $theme);
    if ($config === NULL) {
      return [
        'message' => self::saveError('load_menu'),
        'code' => 500,
      ];
    }
    if ($menu_config && $menu_name && $block_config && $theme) {

      // This is parameter to load menu_tree with the enabled links.
      $menu_tree_parameters = (new MenuTreeParameters())
        ->onlyEnabledLinks();

      // Load menu items with condition.
      $menu_items = $this->menuTree
        ->load($menu_name, $menu_tree_parameters);

      // Sync mega menu before store.
      $this->menuBuilder
        ->syncConfigAll($menu_items, $menu_config, 'backend');
      $this->menuBuilder
        ->syncOrderMenus($menu_config);
      $config
        ->setBlockConfig($block_config);
      $config
        ->setMenuConfig($menu_config);

      // Save the config and return a success message.
      $saved_config = $config
        ->save();
      if ($saved_config == 1 || $saved_config == 2) {
        $result = $this
          ->t("Saved config sucessfully!");
      }
      else {
        $result = self::saveError('unknown');
        $code = 500;
      }
    }
    else {
      $result = self::saveError('missing_info', $menu_name, $theme, $block_config, $menu_config);
      $code = 500;
    }
    return [
      'message' => $result,
      'code' => $code,
    ];
  }

  /**
   * Displays and logs an error when config can't be saved.
   *
   * @param string $event
   *   The event that triggered the error.
   * @param string $menu_name
   *   The machine name for the current menu.
   * @param string $theme
   *   The machine name for the current theme.
   * @param array $block_config
   *   The configuration for the current block.
   * @param array $menu_config
   *   The configuration for the current menu.
   *
   * @return string
   *   An error message displayed to the user.
   */
  public function saveError(string $event, string $menu_name = NULL, string $theme = NULL, array $block_config = NULL, array $menu_config = NULL) {
    $msg = $this
      ->t("TB MegaMenu error:");
    switch ($event) {
      case 'load_menu':
        $msg .= ' ' . $this
          ->t("could not load the requested menu.");
        break;
      case 'load_config':
        $msg .= ' ' . $this
          ->t("could not (re)load the requested menu configuration.");
        break;
      case 'load_block':
        $msg .= ' ' . $this
          ->t("could not load the requested menu block.");
        break;
      case 'missing_info':
        $problem = ($menu_name ? '' : "menu_name ") . ($theme ? '' : "theme_name ") . ($block_config ? '' : "block_config ") . ($menu_config ? '' : "menu_config");
        $msg .= ' ' . $this
          ->t("Post was missing the following information: @problem", [
          '@problem' => $problem,
        ]);
        break;
      default:
        $msg .= ' ' . $this
          ->t("an unknown error occurred.");
    }
    return $msg;
  }

  /**
   * Loads a menu block.
   *
   * @param array $data
   *   A decoded JSON object used to load the block.
   *
   * @return array
   *   The message and status code indicating the result of the load attempt.
   */
  public function loadMenuBlock(array $data) {
    $block_id = isset($data['block_id']) ? $data['block_id'] : NULL;
    $id = isset($data['id']) ? $data['id'] : NULL;
    $showblocktitle = isset($data['showblocktitle']) ? $data['showblocktitle'] : NULL;
    $code = 200;

    // Attempt to render the specified block.
    if ($block_id && $id) {
      $render = [
        '#theme' => 'tb_megamenu_block',
        '#block_id' => $block_id,
        '#section' => 'backend',
        '#showblocktitle' => $showblocktitle,
      ];
      $content = $this->renderer
        ->render($render)
        ->__toString();
      $result = Json::encode([
        'content' => $content,
        'id' => $id,
      ]);
    }
    else {
      $result = self::saveError('load_block');
      $code = 500;
    }
    return [
      'message' => $result,
      'code' => $code,
    ];
  }

  /**
   * Get the machine name of a menu.
   *
   * @param array $data
   *   A decoded JSON object used to load the configuration.
   *
   * @return mixed
   *   A string or null.
   */
  public function getMenuName(array $data) {
    return isset($data['menu_name']) ? $data['menu_name'] : NULL;
  }

  /**
   * Get the machine name of a theme.
   *
   * @param array $data
   *   A decoded JSON object used to load the configuration.
   *
   * @return mixed
   *   An string or null.
   */
  public function getTheme(array $data) {
    return isset($data['theme']) ? $data['theme'] : NULL;
  }

  /**
   * Get an existing menu configuration.
   *
   * @param array $data
   *   A decoded JSON object used to load the configuration.
   *
   * @return mixed
   *   An array or null.
   */
  public function getMenuConfig(array $data) {
    return isset($data['menu_config']) ? $data['menu_config'] : NULL;
  }

  /**
   * Get an existing block configuration.
   *
   * @param array $data
   *   A decoded JSON object used to load the configuration.
   *
   * @return mixed
   *   An array or null.
   */
  public function getBlockConfig(array $data) {
    return isset($data['block_config']) ? $data['block_config'] : NULL;
  }

  /**
   * This is a menu page. To edit Mega Menu.
   */
  public function configMegaMenu(ConfigEntityInterface $tb_megamenu, Request $request) {

    // Add font-awesome library.
    $page['#attached']['library'][] = 'tb_megamenu/form.font-awesome';

    // Add chosen library.
    $page['#attached']['library'][] = 'tb_megamenu/form.chosen';

    // Add a custom library.
    $page['#attached']['library'][] = 'tb_megamenu/form.configure-megamenu';
    Url::fromRoute('tb_megamenu.admin.save', [], [
      'absolute' => TRUE,
    ]);
    $abs_url_config = Url::fromRoute('tb_megamenu.admin.save', [], [
      'absolute' => TRUE,
    ])
      ->toString();
    $page['#attached']['drupalSettings']['TBMegaMenu']['saveConfigURL'] = $abs_url_config;
    if (!empty($tb_megamenu)) {
      $page['tb_megamenu'] = [
        '#theme' => 'tb_megamenu_backend',
        '#menu_name' => $tb_megamenu->menu,
        '#block_theme' => $tb_megamenu->theme,
      ];
    }
    return $page;
  }

}

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.
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.
TBMegaMenuAdminController::$menuBuilder private property The menu builder service.
TBMegaMenuAdminController::$menuTree protected property The menu tree service.
TBMegaMenuAdminController::$renderer protected property The renderer service.
TBMegaMenuAdminController::configMegaMenu public function This is a menu page. To edit Mega Menu.
TBMegaMenuAdminController::create public static function Instantiates a new instance of this class. Overrides ControllerBase::create
TBMegaMenuAdminController::getBlockConfig public function Get an existing block configuration.
TBMegaMenuAdminController::getMenuConfig public function Get an existing menu configuration.
TBMegaMenuAdminController::getMenuName public function Get the machine name of a menu.
TBMegaMenuAdminController::getTheme public function Get the machine name of a theme.
TBMegaMenuAdminController::loadMenuBlock public function Loads a menu block.
TBMegaMenuAdminController::loadMenuConfig public function Loads a menu configuration.
TBMegaMenuAdminController::saveConfiguration public function Ajax callback for admin screen.
TBMegaMenuAdminController::saveError public function Displays and logs an error when config can't be saved.
TBMegaMenuAdminController::saveMenuConfig public function Saves a menu configuration.
TBMegaMenuAdminController::__construct public function Constructs a TBMegaMenuAdminController object.
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.