bef_entity_select_buttons-1.0.0-alpha1/src/Service/ContentPathsService.php

src/Service/ContentPathsService.php
<?php

namespace Drupal\bef_entity_select_buttons\Service;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Routing\UrlGeneratorInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Url;

class ContentPathsService {
  protected EntityTypeManagerInterface $entityTypeManager;
  protected UrlGeneratorInterface $urlGenerator;
  protected ModuleHandlerInterface $moduleHandler;

  public function __construct(
    EntityTypeManagerInterface $entityTypeManager,
    UrlGeneratorInterface $urlGenerator,
    ModuleHandlerInterface $moduleHandler
  ) {
    $this->entityTypeManager = $entityTypeManager;
    $this->urlGenerator = $urlGenerator;
    $this->moduleHandler = $moduleHandler;
  }

  /**
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   */
  public function getAddContentUrl($entityTypeId, $bundle): ?Url
  {
    $definition = $this->entityTypeManager->getDefinition($entityTypeId);

    $uri = $definition->hasLinkTemplate('add-form')
      ? $this->getEntityAddPath($definition, $bundle)
      : $this->getNodeAddPath($bundle);

    $url = Url::fromUri("internal:$uri");
    return $url->isRouted() && $url->access() ? $url : null;
  }

  protected function getNodeAddPath($bundle) {
    if ($this->moduleHandler->moduleExists('node')) {
      return $this->urlGenerator->generateFromRoute('node.add', ['node_type' => $bundle]);
    }
    return NULL;
  }

  protected function getEntityAddPath($definition, $bundle) {
    $linkTemplate = $definition->getLinkTemplate('add-form');
    return str_replace('{' . $definition->getBundleEntityType() . '}', $bundle, $linkTemplate);
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc