You are here

class EntityMenuLinkCloneForm in Menu Link Clone 8

Same name and namespace in other branches
  1. 8.3 src/Form/EntityMenuLinkCloneForm.php \Drupal\menu_link_clone\Form\EntityMenuLinkCloneForm
  2. 8.2 src/Form/EntityMenuLinkCloneForm.php \Drupal\menu_link_clone\Form\EntityMenuLinkCloneForm

Provides a menu link clone form.

Hierarchy

Expanded class hierarchy of EntityMenuLinkCloneForm

File

src/Form/EntityMenuLinkCloneForm.php, line 13

Namespace

Drupal\menu_link_clone\Form
View source
class EntityMenuLinkCloneForm extends EntityCloneForm {

  /**
   * The entity type définition.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface
   */
  protected $entityTypeDefinition;

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildForm($form, $form_state);
    $form['clone_links'] = [
      '#type' => 'checkbox',
      '#title' => t('Clone with Links'),
      '#required' => FALSE,
      '#default_value' => FALSE,
      '#weight' => 0,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form, $form_state);
    $cloneLink = $form_state
      ->getValue('clone_links');
    if ($cloneLink) {
      $sourceMenuId = $this->entity
        ->id();
      $destMenuId = $form_state
        ->getValue('id');
      $sourceMenuExistence = $this
        ->menuLinksAvailabilityCheck($sourceMenuId);
      if (!$sourceMenuExistence) {
        $this->messenger
          ->addMessage($this->stringTranslationManager
          ->translate('Menu links are not available in ' . $this->entity
          ->label() . ' created by admin.'));
      }
      else {
        $result = $this
          ->cloneMenuLinks($sourceMenuId, $destMenuId);
        if ($result) {
          $this->messenger
            ->addMessage($this->stringTranslationManager
            ->translate('Links are cloned successfully for ' . $form_state
            ->getValue('label') . '.'));
        }
        else {
          $this->messenger
            ->addMessage($this->stringTranslationManager
            ->translate('Unsuccessfull to clone links for ' . $form_state
            ->getValue('label') . ', Please try again or contact to site admin.'));
        }
      }
    }
    $response = Url::fromUserInput('/admin/structure/menu');
    $form_state
      ->setRedirectUrl($response);
  }

  /**
   * Clone menu items.
   *
   * @param object $source_menu_name
   *   Source menu name from we need to clone the menu items.
   * @param string $target_menu_name
   *   Destination menu name to clone the menu items.
   */
  protected function cloneMenuLinks($source_menu_name, $target_menu_name) {
    $result = FALSE;
    $menuLinkIds = $this
      ->getMenuItemIds($source_menu_name);
    if ($menuLinkIds['status']) {
      $menuLinks = MenuLinkContent::loadMultiple($menuLinkIds['items']);
      $data = $this
        ->resetLinkItems($menuLinks);
      $data = $this
        ->setUuidForMenuItems($data, $target_menu_name);
      $data = $this
        ->createMenuLinkClone($data);
      if ($data) {
        $result = TRUE;
      }
    }
    return $result;
  }

  /**
   * Genereate UUID (Everytime gives you new unique ids.).
   */
  protected function genUuid() {
    $uuid_service = \Drupal::service('uuid');
    $uuid = $uuid_service
      ->generate();
    return $uuid;
  }

  /**
   * Get menu items ids.
   *
   * @param string $menu_id
   *   Menu name for which we need to check their items ids.
   */
  protected function getMenuItemIds($menu_id) {
    $result = [];
    $menuLinkIds = \Drupal::entityQuery('menu_link_content')
      ->condition('menu_name', $menu_id)
      ->execute();
    if (isset($menuLinkIds) && !empty($menuLinkIds)) {
      $result['status'] = TRUE;
      $result['items'] = $menuLinkIds;
    }
    else {
      $result['status'] = FALSE;
      $result['items'] = [];
    }
    return $result;
  }

  /**
   * Check Menu Link items are availabe inside the menu.
   *
   * @param string $source_menu_id
   *   Menu name for which we need to check their items.
   */
  protected function menuLinksAvailabilityCheck($source_menu_id) {
    $result = FALSE;
    if (isset($source_menu_id) && !empty($source_menu_id)) {
      $menuLinkIds = $this
        ->getMenuItemIds($source_menu_id);
      if ($menuLinkIds['status']) {
        $result = TRUE;
      }
    }
    return $result;
  }

  /**
   * Reset elements in menu item object.
   *
   * @param object $menu_links_object_multiple
   *   Menu Items Object.
   */
  protected function resetLinkItems($menu_links_object_multiple) {
    $result = [];
    foreach ($menu_links_object_multiple as $link) {
      if (!empty($link)) {
        $linkArray = $link
          ->toArray();
        foreach ($linkArray as $key => $linkArrayItem) {
          $linkData[$key] = reset($linkArrayItem);
        }
        $result[$link
          ->id()] = $linkData;
      }
    }
    return $result;
  }

  /**
   * Set UUID for menu items.
   *
   * @param object $menu_links_object_multiple
   *   Menu Items Object.
   * @param string $target_menu_name
   *   Menu Name for which we need to set UUID.
   */
  protected function setUuidForMenuItems($menu_links_object_multiple, $target_menu_name) {
    $uuid_map = [];

    // Create an uuid mapping table.
    foreach ($menu_links_object_multiple as $id => $menu) {
      $uuid = $menu['uuid']['value'];

      // Assume uuid is not duplicated here.
      $new_uuid = $this
        ->genUuid();
      $uuid_map['menu_link_content:' . $uuid] = 'menu_link_content:' . $new_uuid;
      $menu_links_object_multiple[$id]['uuid'] = $new_uuid;
      unset($menu_links_object_multiple[$id]['id']);
      $menu_links_object_multiple[$id]['menu_name'] = $target_menu_name;
      if (isset($menu_links_object_multiple[$id]['parent']['value']) && !empty($menu_links_object_multiple[$id]['parent']['value'])) {
        $menu_links_object_multiple[$id]['parent']['value'] = $uuid_map[$menu_links_object_multiple[$id]['parent']['value']];
      }
    }
    return $menu_links_object_multiple;
  }

  /**
   * Create menu links.
   *
   * @param object $menu_links_object_multiple
   *   Menu Items Object.
   */
  protected function createMenuLinkClone($menu_links_object_multiple) {
    $result = FALSE;
    foreach ($menu_links_object_multiple as $id => $menu) {
      unset($menu['revision_id']);
      unset($menu['bundle']);
      $save_menu = MenuLinkContent::create($menu);
      $save_menu
        ->save();
      if ($save_menu) {
        $result = TRUE;
      }
    }
    return $result;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
EntityCloneForm::$currentUser protected property The current user.
EntityCloneForm::$entity protected property The entity ready to clone.
EntityCloneForm::$entityCloneSettingsManager protected property The entity clone settings manager service.
EntityCloneForm::$entityTypeManager protected property The entity type manager.
EntityCloneForm::$eventDispatcher protected property Event dispatcher service.
EntityCloneForm::$messenger protected property The messenger service. Overrides MessengerTrait::$messenger
EntityCloneForm::$serviceProvider protected property The Service Provider that verifies if entity has ownership.
EntityCloneForm::$stringTranslationManager protected property The string translation manager.
EntityCloneForm::cancelForm public function Cancel form handler.
EntityCloneForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
EntityCloneForm::formSetRedirect protected function Sets a redirect on form state.
EntityCloneForm::getEntity public function Gets the entity of this form.
EntityCloneForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
EntityCloneForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
EntityCloneForm::__construct public function Constructs a new Entity Clone form.
EntityMenuLinkCloneForm::$entityTypeDefinition protected property The entity type définition. Overrides EntityCloneForm::$entityTypeDefinition
EntityMenuLinkCloneForm::buildForm public function Form constructor. Overrides EntityCloneForm::buildForm
EntityMenuLinkCloneForm::cloneMenuLinks protected function Clone menu items.
EntityMenuLinkCloneForm::createMenuLinkClone protected function Create menu links.
EntityMenuLinkCloneForm::genUuid protected function Genereate UUID (Everytime gives you new unique ids.).
EntityMenuLinkCloneForm::getMenuItemIds protected function Get menu items ids.
EntityMenuLinkCloneForm::menuLinksAvailabilityCheck protected function Check Menu Link items are availabe inside the menu.
EntityMenuLinkCloneForm::resetLinkItems protected function Reset elements in menu item object.
EntityMenuLinkCloneForm::setUuidForMenuItems protected function Set UUID for menu items.
EntityMenuLinkCloneForm::submitForm public function Form submission handler. Overrides EntityCloneForm::submitForm
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
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
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.