You are here

class renderCheeseburgerMenuBlock in Cheeseburger Menu 8

Same name and namespace in other branches
  1. 8.4 src/Controller/RenderCheeseburgerMenuBlock.php \Drupal\cheeseburger_menu\Controller\RenderCheeseburgerMenuBlock
  2. 8.2 src/Controller/RenderCheeseburgerMenuBlock.php \Drupal\cheeseburger_menu\Controller\RenderCheeseburgerMenuBlock
  3. 8.3 src/Controller/RenderCheeseburgerMenuBlock.php \Drupal\cheeseburger_menu\Controller\RenderCheeseburgerMenuBlock

Hierarchy

Expanded class hierarchy of renderCheeseburgerMenuBlock

1 file declares its use of renderCheeseburgerMenuBlock
CheeseburgerMenu.php in src/Plugin/Block/CheeseburgerMenu.php

File

src/Controller/renderCheeseburgerMenuBlock.php, line 24

Namespace

Drupal\cheeseburger_menu\Controller
View source
class renderCheeseburgerMenuBlock extends ControllerBase {

  /**
   * {@inheritdoc}
   */
  public function content(Request $request) {

    //var_dump($request->getContent());

    /*var_dump($request);
      die();*/

    /*$build = [
        '#markup' => t('Hello World!'),
      ];
      return $build;*/
    $block_id = $request->request
      ->get('block_id');
    $route_id = $request->request
      ->get('route_id');
    $page_type = $request->request
      ->get('page_type');
    $current_route = $request->request
      ->get('current_route');
    $block = \Drupal\block\Entity\Block::load($block_id);
    if (!$block) {
      return new Response('<div>No such block</div>');
    }
    $config = $block
      ->get('settings');
    $tree = $this
      ->render_tree($route_id, $page_type, $current_route, $config);

    /** @var \Drupal\Core\Render\Renderer $renderer */
    $renderer = \Drupal::service('renderer');
    $rendered_tree = $renderer
      ->render($tree);

    //dsm($rendered_tree);

    /*$build = [
        '#markup' => t('Hello World!'),
      ];
      return $build;*/
    return new Response($rendered_tree);
  }
  public function render_tree($route_id, $page_type, $current_route, $config) {
    $menus_appear = isset($config['menus_appear']) ? $config['menus_appear'] : [];
    $menus_weight = isset($config['menus_weight']) ? $config['menus_weight'] : [];
    $menus_title = isset($config['menus_title']) ? $config['menus_title'] : [];
    $taxonomy_appear = isset($config['taxonomy_appear']) ? $config['taxonomy_appear'] : [];
    $taxonomy_weight = isset($config['taxonomy_weight']) ? $config['taxonomy_weight'] : [];
    $taxonomy_title = isset($config['taxonomy_title']) ? $config['taxonomy_title'] : [];
    $cart = [];
    $cart['appear'] = isset($config['cart_appear']) ? $config['cart_appear'] : FALSE;
    $cart['weight'] = isset($config['cart_weight']) ? $config['cart_weight'] : 0;
    $phone['appear'] = isset($config['phone_appear']) ? $config['phone_appear'] : FALSE;
    $phone['weight'] = isset($config['phone_weight']) ? $config['phone_weight'] : 0;
    $phone['store'] = isset($config['phone_store']) ? $config['phone_store'] : FALSE;
    $phone['number'] = isset($config['phone_number']) ? $config['phone_number'] : '';
    $language_switcher = isset($config['lang_switcher']) ? $config['lang_switcher'] : FALSE;
    $language_switcher_weight = isset($config['lang_switcher_weight']) ? $config['lang_switcher_weight'] : 0;
    $headerHeight = isset($config['headerHeight']) ? $config['headerHeight'] : 0;
    $headerPadding = isset($config['headerPadding']) ? $config['headerPadding'] : 0;
    $moduleHandler = \Drupal::service('module_handler');
    $menu_ids = $this
      ->getAllMenuLinkId();
    $taxonomy_term_ids = $this
      ->getAllTaxonomyTermIds();
    $tree = [];
    $titles = [];
    foreach ($menus_appear as $key => $menu) {
      $helpArray = [];
      if ($menus_title[$key] === TRUE || $menus_title[$key] === FALSE) {
        $helpArray['title'] = array_search($key, $menu_ids);
      }
      else {
        $helpArray['title'] = $menus_title[$key];
      }
      $helpArray['class'] = $key;
      $helpArray['weight'] = $menus_weight[$key];
      $titles[] = $helpArray;
    }
    foreach ($taxonomy_appear as $key => $taxonomy) {
      $helpArray = [];
      if ($taxonomy_title[$key] === TRUE || $taxonomy_title[$key] === FALSE) {
        $helpArray['title'] = array_search($key, $taxonomy_term_ids);
      }
      else {
        $helpArray['title'] = $taxonomy_title[$key];
      }
      $helpArray['class'] = $key;
      $helpArray['weight'] = $taxonomy_weight[$key];
      $titles[] = $helpArray;
    }
    if ($cart['appear']) {
      $helpArray = [];
      $helpArray['title'] = $this
        ->t('Cart');
      $helpArray['class'] = 'cart';
      $helpArray['url'] = '/cart';
      $helpArray['weight'] = $cart['weight'];
      $titles[] = $helpArray;
    }
    if ($phone['appear']) {
      if ($phone['store'] == 0) {
        $phone_number = $phone['number'];
      }
      else {
        if ($moduleHandler
          ->moduleExists('commerce_store')) {
          $store = Store::load($phone['store']);
          try {
            $phone_number = current($store
              ->get('field_phone')
              ->getValue())['value'];
          } catch (\Exception $exception) {
            $phone_number = FALSE;
          }
          $phone_number = str_replace(' ', '', $phone_number);
        }
        else {
          $phone_number = FALSE;
        }
      }
      if ($phone_number != FALSE) {
        $helpArray = [];
        $helpArray['title'] = $this
          ->t('Phone');
        $helpArray['class'] = 'phone';
        $helpArray['url'] = 'tel:' . $phone_number;
        $helpArray['weight'] = $phone['weight'];
        $titles[] = $helpArray;
      }
    }
    $titles = $this
      ->bubbleSortWeight($titles);
    $tree[] = [
      '#theme' => 'hierarchical_navigation',
      '#tree' => $titles,
      '#weight' => -100,
    ];
    $trees = [];

    //MENUS
    foreach ($menus_appear as $key => $menu) {
      if ($menus_title[$key] === TRUE) {
        $title = array_search($key, $menu_ids);
      }
      elseif ($menus_title[$key] === FALSE) {
        $title = FALSE;
      }
      else {
        $title = $menus_title[$key];
      }
      $trees[] = [
        '#theme' => 'hierarchical_menu',
        '#menu_tree' => $this
          ->getMenuTree($key),
        '#route_id' => $route_id,
        '#page_type' => $page_type,
        '#title' => $title,
        '#machine_name' => $key,
        '#current_url' => $current_route,
        '#cache' => [
          'max-age' => 0,
        ],
        '#attached' => [
          'library' => [
            'cheeseburger_menu/cheeseburger_menu',
          ],
          'drupalSettings' => [
            'collapsibleMenu' => 1,
            'interactiveParentMenu' => 0,
            'headerHeight' => $headerHeight,
            'headerPadding' => $headerPadding,
            'breakpoints' => $config['breakpoints'],
            'activeBreakpoints' => [],
          ],
        ],
        'weight' => $menus_weight[$key],
      ];
    }

    //taxonomies
    foreach ($taxonomy_appear as $key => $taxonomy) {
      if ($taxonomy_title[$key] === TRUE) {
        $title = array_search($key, $taxonomy_term_ids);
      }
      elseif ($taxonomy_title[$key] === FALSE) {
        $title = FALSE;
      }
      else {
        $title = $taxonomy_title[$key];
      }

      /** @var  $entityTypeManager Drupal\Core\Entity\EntityTypeManager */
      $entityTypeManager = \Drupal::service('entity_type.manager');
      $vocabulary_tree = $entityTypeManager
        ->getStorage('taxonomy_term')
        ->loadTree($key);
      $vocabulary_tree_array = [];
      foreach ($vocabulary_tree as $item) {
        $term = Term::load($item->tid);
        try {
          $icon = $term
            ->get('field_icon');
          if (!empty($icon
            ->getValue())) {
            $icon = $term
              ->get('field_icon')->entity
              ->getFileUri();
            $icon = file_create_url($icon);
          }
          else {
            $icon = '';
          }
        } catch (\Exception $exception) {
          $icon = '';
        }
        $vocabulary_tree_array[] = [
          'id' => $item->tid,
          'name' => $term
            ->getName(),
          'url' => $term
            ->url(),
          'parents' => $item->parents,
          'interactive_parent' => 1,
          'type' => 'taxonomy_term',
          'icon' => $icon,
        ];
      }
      $vocabulary_tree = $this
        ->generateTree($vocabulary_tree_array);
      $trees[] = [
        '#theme' => 'hierarchical_menu',
        '#menu_tree' => $vocabulary_tree,
        '#route_id' => $route_id,
        '#page_type' => $page_type,
        '#title' => $title,
        '#machine_name' => $key,
        '#current_url' => $current_route,
        '#cache' => [
          'max-age' => 0,
        ],
        '#attached' => [
          'library' => [
            'cheeseburger_menu/cheeseburger_menu',
          ],
          'drupalSettings' => [
            'collapsibleMenu' => 1,
            'interactiveParentMenu' => 0,
            'headerHeight' => $headerHeight,
            'headerPadding' => $headerPadding,
            'breakpoints' => $config['breakpoints'],
            'activeBreakpoints' => [],
          ],
        ],
        'weight' => $taxonomy_weight[$key],
      ];
    }
    if ($language_switcher == 1) {

      /** @var Drupal\Core\Language\LanguageManager $languageManager */
      $languageManager = \Drupal::service('language_manager');
      $current_language = $languageManager
        ->getCurrentLanguage()
        ->getId();
      $languageTree = [];
      $languages = $languageManager
        ->getLanguages();
      foreach ($languages as $language) {
        $languageTree[] = [
          'name' => $language
            ->getName(),
          'id' => $language
            ->getId(),
          'url' => $language
            ->isDefault() ? '/' : '/' . $language
            ->getId(),
          'type' => 'language',
        ];
      }
      $title = 'Language';
      $trees[] = [
        '#theme' => 'hierarchical_menu',
        '#menu_tree' => $languageTree,
        '#route_id' => $current_language,
        '#page_type' => 'language',
        '#title' => $title,
        '#machine_name' => 'language_switcher',
        '#current_url' => $current_route,
        '#cache' => [
          'max-age' => 0,
        ],
        '#attached' => [
          'library' => [
            'cheeseburger_menu/cheeseburger_menu',
          ],
          'drupalSettings' => [
            'collapsibleMenu' => 1,
            'interactiveParentMenu' => 0,
            'headerHeight' => $headerHeight,
            'headerPadding' => $headerPadding,
            'breakpoints' => $config['breakpoints'],
            'activeBreakpoints' => [],
          ],
        ],
        'weight' => $language_switcher_weight,
      ];
    }
    if ($config['css_default']) {
      $tree['#attached']['library'][] = 'cheeseburger_menu/cheeseburger_menu.css';
    }
    $trees = $this
      ->bubbleSortWeight($trees);
    foreach ($trees as $key => $iterator) {
      unset($trees[$key]['weight']);
    }
    $tree = array_merge($tree, $trees);
    return $tree;
  }
  public function getMenuTree($menu) {
    $menu_tree = \Drupal::menuTree();
    $tree = $menu_tree
      ->load($menu, new \Drupal\Core\Menu\MenuTreeParameters());
    $tree = $menu_tree
      ->transform($tree, []);
    $menu_build = $menu_tree
      ->build($tree);
    $menu_tree_formatted = [];
    if (array_key_exists('#items', $menu_build)) {
      if (is_iterable($menu_build['#items'])) {
        foreach ($menu_build['#items'] as $menu_data) {
          if ($menu_data['url']
            ->isRouted()) {
            $help_array = [];
            $help_array['subitem'] = $this
              ->findChildren($menu_data['below']);
            $help_array['name'] = $menu_data['title'];
            try {
              $help_array['id'] = $menu_data['url']
                ->getRouteParameters();
            } catch (\Exception $exception) {
              $help_array['id'][0] = NULL;
            }
            if (reset($help_array['id']) != NULL) {
              $help_array['type'] = key($help_array['id']);
              $help_array['id'] = reset($help_array['id']);
            }
            else {
              try {
                $help_array['id'] = $menu_data['url']
                  ->getRouteName();
              } catch (\Exception $exception) {
                $help_array['id'] = NULL;
              }
              if ($help_array['id'] == "user.page") {
                $user = \Drupal::currentUser();
                $help_array['id'] = $user != NULL ? $user
                  ->id() : $user;
                $help_array['type'] = 'user';
              }
              else {
                $help_array['type'] = 'view';
              }
            }
            try {
              $route_name = $menu_data['url']
                ->getRouteName();
            } catch (\Exception $exception) {
              $route_name = NULL;
            }
            if ($route_name != NULL) {
              $url = \Drupal\Core\Url::fromRoute($menu_data['url']
                ->getRouteName(), $menu_data['url']
                ->getRouteParameters());
              $help_array['url'] = $url
                ->toString();
            }
            else {
              $help_array['url'] = '';
            }
            $menu_tree_formatted[] = $help_array;
          }
        }
      }
    }
    return $menu_tree_formatted;
  }
  public function findChildren($menu) {
    $menu_tree_formatted = [];
    if (is_iterable($menu)) {
      foreach ($menu as $menu_data) {
        if ($menu_data['url']
          ->isRouted()) {
          $help_array = [];
          $help_array['subitem'] = $this
            ->findChildren($menu_data['below']);
          $help_array['name'] = $menu_data['title'];
          try {
            $help_array['id'] = $menu_data['url']
              ->getRouteParameters();
          } catch (\Exception $exception) {
            $help_array['id'][0] = NULL;
          }
          if (reset($help_array['id']) != NULL) {
            $help_array['type'] = key($help_array['id']);
            $help_array['id'] = reset($help_array['id']);
          }
          else {
            try {
              $help_array['id'] = $menu_data['url']
                ->getRouteName();
            } catch (\Exception $exception) {
              $help_array['id'] = NULL;
            }
            if ($help_array['id'] == "user.page") {
              $user = \Drupal::currentUser();
              $help_array['id'] = $user != NULL ? $user
                ->id() : $user;
              $help_array['type'] = 'user';
            }
            else {
              $help_array['type'] = 'view';
            }
          }
          try {
            $route_name = $menu_data['url']
              ->getRouteName();
          } catch (\Exception $exception) {
            $route_name = NULL;
          }
          if ($route_name != NULL) {
            $url = \Drupal\Core\Url::fromRoute($menu_data['url']
              ->getRouteName(), $menu_data['url']
              ->getRouteParameters());
            $help_array['url'] = $url
              ->toString();
          }
          else {
            $help_array['url'] = '';
          }
          $menu_tree_formatted[] = $help_array;
        }
      }
    }
    return $menu_tree_formatted;
  }

  /**
   *
   * @return all menu translated name
   */
  public function getAllMenuLinkNames() {
    $all_menus = Menu::loadMultiple();
    $menus = [];
    foreach ($all_menus as $id => $menu) {
      $menus[$id] = $menu
        ->label();
    }
    asort($menus);
    return $menus;
  }

  /**
   *
   * @return all menu translated id
   */
  public function getAllMenuLinkId() {
    $all_menus = Menu::loadMultiple();
    $menus = [];
    foreach ($all_menus as $id => $menu) {
      $menus[$menu
        ->label()] = $id;
    }
    asort($menus);
    return $menus;
  }

  /**
   *
   * @return all taxonomy term translated names
   */
  public function getAllTaxonomyTermNames() {
    $all_taxonomies = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_vocabulary')
      ->loadMultiple();
    $menus = [];
    foreach ($all_taxonomies as $id => $menu) {
      $menus[$id] = $menu
        ->label();
    }
    asort($menus);
    return $menus;
  }

  /**
   *
   * @return all menu translated id
   */
  public function getAllTaxonomyTermIds() {
    $all_taxonomies = \Drupal::entityTypeManager()
      ->getStorage('taxonomy_vocabulary')
      ->loadMultiple();
    $menus = [];
    foreach ($all_taxonomies as $id => $menu) {
      $menus[$menu
        ->label()] = $id;
    }
    asort($menus);
    return $menus;
  }

  /**
   *
   * @return rendered block
   * pulls a block by id and returns its rendered array
   *
   */
  public function placeBlockContent($block_id) {
    $block = Block::load($block_id);
    $render = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
    return $render;
  }

  /**
   * Generate menu tree.
   */
  public function generateTree($array, $parent = 0) {
    $tree = [];
    foreach ($array as $item) {
      if (reset($item['parents']) == $parent) {
        $item['subitem'] = isset($item['subitem']) ? $item['subitem'] : $this
          ->generateTree($array, $item['id']);
        $tree[] = $item;
      }
    }
    return $tree;
  }
  public function getLinkFromTid($tid) {
    $term = Term::load($tid);
    return $term
      ->url();
  }
  public function bubbleSortWeight($sort) {
    do {
      $change = FALSE;
      for ($i = 0; $i < count($sort) - 1; $i++) {
        if ($sort[$i]['weight'] > $sort[$i + 1]['weight']) {
          $temp = $sort[$i];
          $sort[$i] = $sort[$i + 1];
          $sort[$i + 1] = $temp;
          $change = TRUE;
        }
      }
    } while ($change == TRUE);
    return $sort;
  }
  public function returnBreakpointsForDefaultTheme() {

    /** @var \Drupal\Core\Extension\ThemeHandler $theme_handler */
    $theme_handler = \Drupal::service('theme_handler');

    /** @var \Drupal\breakpoint\BreakpointManager $breakpoint_manager */
    $breakpoint_manager = \Drupal::service('breakpoint.manager');
    $groups = $breakpoint_manager
      ->getGroups();
    $list = [];
    foreach ($groups as $group) {

      //dsm($group);
      if (is_object($group)) {
        try {
          $breakpoints = $breakpoint_manager
            ->getBreakpointsByGroup($group
            ->__toString());
          foreach ($breakpoints as $key => $breakpoint) {
            if ($breakpoint
              ->getProvider() == $theme_handler
              ->getDefault()) {
              $list[$key]['mediaQuery'] = $breakpoint
                ->getMediaQuery();
              $list[$key]['label'] = $breakpoint
                ->getLabel();
              if (is_object($list[$key]['label'])) {
                $list[$key]['label'] = $list[$key]['label']
                  ->__toString();
              }
            }
          }
        } catch (Exception $exception) {

          //do nothing
        }
      }
      else {
        try {
          $breakpoints = $breakpoint_manager
            ->getBreakpointsByGroup($group);
          foreach ($breakpoints as $key => $breakpoint) {
            if ($breakpoint
              ->getProvider() == $theme_handler
              ->getDefault()) {
              $list[$key]['mediaQuery'] = $breakpoint
                ->getMediaQuery();
              $list[$key]['label'] = $breakpoint
                ->getLabel();
              if (is_object($list[$key]['label'])) {
                $list[$key]['label'] = $list[$key]['label']
                  ->__toString();
              }
            }
          }
        } catch (Exception $exception) {

          //do nothing
        }
      }
    }
    return $list;
  }

}

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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 40
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.
renderCheeseburgerMenuBlock::bubbleSortWeight public function
renderCheeseburgerMenuBlock::content public function
renderCheeseburgerMenuBlock::findChildren public function
renderCheeseburgerMenuBlock::generateTree public function Generate menu tree.
renderCheeseburgerMenuBlock::getAllMenuLinkId public function
renderCheeseburgerMenuBlock::getAllMenuLinkNames public function
renderCheeseburgerMenuBlock::getAllTaxonomyTermIds public function
renderCheeseburgerMenuBlock::getAllTaxonomyTermNames public function
renderCheeseburgerMenuBlock::getLinkFromTid public function
renderCheeseburgerMenuBlock::getMenuTree public function
renderCheeseburgerMenuBlock::placeBlockContent public function
renderCheeseburgerMenuBlock::render_tree public function
renderCheeseburgerMenuBlock::returnBreakpointsForDefaultTheme public function
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.