devel_wizard-2.x-dev/src/Controller/AutocompleteEntityTypeIdController.php

src/Controller/AutocompleteEntityTypeIdController.php
<?php

declare(strict_types=1);

namespace Drupal\devel_wizard\Controller;

use Drupal\Core\Config\Entity\ConfigEntityTypeInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class AutocompleteEntityTypeIdController extends ControllerBase {

  protected int $minKeywordLength = 2;

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

  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  public function body(Request $request, string $types) {
    $etm = $this->entityTypeManager();
    $matches = [];

    $keyword = mb_strtolower($request->query->get('q', ''));
    if (mb_strlen($keyword) < $this->minKeywordLength) {
      return new JsonResponse($matches);
    }

    // @todo Filter for if the content entity type is bundelable or not.
    $allowedEntityTypes = $this->parseTypes($types);
    foreach ($etm->getDefinitions() as $entityType) {
      $type = $this->getTypeOfEntityType($entityType);
      if (empty($allowedEntityTypes[$type])) {
        continue;
      }

      // @todo Fuzzy search.
      if (str_contains(mb_strtolower($entityType->id()), $keyword)
        || str_contains(mb_strtolower((string) $entityType->getLabel()), $keyword)
      ) {
        $matches[] = [
          'value' => $entityType->id(),
          'label' => $this->t(
            '@entityType.label (@entityType.group - @entityType.id)',
            [
              '@entityType.label' => $entityType->getLabel(),
              '@entityType.group' => $entityType->getGroup(),
              '@entityType.id' => $entityType->id(),
            ],
          ),
        ];
      }
    }

    uasort(
      $matches,
      function ($a, $b): int {
        return strnatcmp($a['value'], $b['value']);
      },
    );

    return new JsonResponse($matches);
  }

  protected function parseTypes(string $types): array {
    $allowed = [
      'config' => FALSE,
      'content' => FALSE,
    ];
    foreach (array_unique(explode(',', $types)) as $type) {
      $allowed[$type] = TRUE;
    }

    return $allowed;
  }

  protected function getTypeOfEntityType(EntityTypeInterface $entityType): string {
    if ($entityType instanceof ConfigEntityTypeInterface) {
      return 'config';
    }

    return 'content';
  }

}

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

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