Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
novicell/dds_content / src / Controller / DDSContentEntityAutocompleteController.php
Size: Mime:
<?php

namespace Drupal\dds_content\Controller;

use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Tags;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\KeyValueStore\KeyValueStoreInterface;
use Drupal\Core\Site\Settings;
use Drupal\path_alias\AliasManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Defines a route controller for entity autocomplete form elements.
 */
class DDSContentEntityAutocompleteController extends ControllerBase {

  /**
   * The key value store.
   *
   * @var \Drupal\Core\KeyValueStore\KeyValueStoreInterface
   */
  protected $keyValue;

  /**
   * The database connection service.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The path alias manager service.
   *
   * @var \Drupal\path_alias\AliasManager
   */
  protected $pathAliasManager;


  /**
   * {@inheritdoc}
   */
  public function __construct(
    KeyValueStoreInterface $key_value,
    Connection $database,
    AliasManager $alias_manager,
    EntityTypeManagerInterface $entity_type_manager
  ) {
    $this->keyValue = $key_value;
    $this->database = $database;
    $this->pathAliasManager = $alias_manager;
    $this->entityTypeManager = $entity_type_manager;
  }

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


  /**
   * Autocomplete the label of an entity.
   *
   * @param string $target_type
   *   The ID of the target entity type.
   * @param string $selection_handler
   *   The plugin ID of the entity reference selection handler.
   * @param string $selection_settings_key
   *   The hashed key of the key/value entry that holds the selection handler
   *   settings.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   The matched entity labels as a JSON response.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException
   *   Thrown if the selection settings key is not found in the key/value store
   *   or if it does not match the stored data.
   */
  public function handleAutocomplete($target_type, $selection_handler, $selection_settings_key) {
    $request = \Drupal::request();
    $matches = [];
    // Get the typed string from the URL, if it exists.
    if ($input = $request->query->get('q')) {
      $typed_string = Tags::explode($input);
      $typed_string = mb_strtolower(array_pop($typed_string));

      // Selection settings are passed in as a hashed key of a serialized array
      // stored in the key/value store.
      $selection_settings = $this->keyValue->get($selection_settings_key, FALSE);
      if ($selection_settings !== FALSE) {
        $selection_settings_hash = Crypt::hmacBase64(serialize($selection_settings) . $target_type . $selection_handler, Settings::getHashSalt());
        if ($selection_settings_hash !== $selection_settings_key) {
          // Disallow access when the selection settings hash does not match the
          // passed-in key.
          throw new AccessDeniedHttpException('Invalid selection settings key.');
        }
      }
      else {
        // Disallow access when the selection settings key is not found in the
        // key/value store.
        throw new AccessDeniedHttpException();
      }

      try {
        $query = $this->database->select('node_field_data', 'n');
        $query->fields('n', ['nid', 'title']);
        $query->condition('n.title', $typed_string . '%', 'LIKE');
        $query->range(0, 10);
        $execute = $query->execute();

        if (!is_null($execute)) {
          $nodes = $execute->fetchAll();
          foreach ($nodes as $node) {
            $key = $node->title . ' (' . $node->nid . ')';
            // Strip things like starting/trailing white spaces,
            // line breaks and tags.
            $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
            // Names containing commas or quotes must be wrapped in quotes.
            $key = Tags::encode($key);
            $matches['node' . $node->nid] = [
              'value' => $key,
              'label' => $node->title,
            ];
          }
        }

        $query = $this->database->select('media_field_data', 'm');
        $query->fields('m', ['mid', 'name']);
        $query->condition('m.name', $typed_string . '%', 'LIKE');
        $query->condition('m.bundle', 'dds_file');
        $query->range(0, 10);
        $execute = $query->execute();

        if (!is_null($execute)) {
          $medias = $this->entityTypeManager->getStorage('media')->loadMultiple($execute->fetchCol());
          foreach ($medias as $media) {
            if (!is_null($media) && $media->hasField('field_media_file')) {
              /** @var \Drupal\file\Entity\File $file */
              $file = $media->get('field_media_file')->entity;
              if (is_null($file)) {
                continue;
              }
              $matches['media' . $media->id()] = [
                'value' => $file->toUrl()->setAbsolute(FALSE)->toString(),
                'label' => $media->label(),
              ];
            }
          }
        }

        if (count($matches) < 10) {
          $query = $this->database->select('node_field_data', 'n');
          $query->fields('n', ['nid', 'title']);
          $query->condition('n.title', '%' . $typed_string . '%', 'LIKE');
          $query->range(0, 10);
          $execute = $query->execute();

          if (!is_null($execute)) {
            $nodes = $execute->fetchAll();
            foreach ($nodes as $node) {
              $key = $node->title . ' (' . $node->nid . ')';
              // Strip things like starting/trailing white spaces,
              // line breaks and tags.
              $key = preg_replace('/\s\s+/', ' ', str_replace("\n", '', trim(Html::decodeEntities(strip_tags($key)))));
              // Names containing commas or quotes must be wrapped in quotes.
              $key = Tags::encode($key);
              $matches['node' . $node->nid] = [
                'value' => $key,
                'label' => $node->title,
              ];
            }
          }

          $query = $this->database->select('media_field_data', 'm');
          $query->fields('m', ['mid', 'name']);
          $query->condition('m.name', '%' . $typed_string . '%', 'LIKE');
          $query->condition('m.bundle', 'dds_file');
          $query->range(0, 10);
          $execute = $query->execute();

          if (!is_null($execute)) {
            $medias = $this->entityTypeManager->getStorage('media')->loadMultiple($execute->fetchCol());
            foreach ($medias as $media) {
              if (!is_null($media) && $media->hasField('field_media_file')) {
                /** @var \Drupal\file\Entity\File $file */
                $file = $media->get('field_media_file')->entity;
                if (is_null($file)) {
                  continue;
                }
                $matches['media' . $media->id()] = [
                  'value' => $file->toUrl()->setAbsolute(FALSE)->toString(),
                  'label' => $media->label(),
                ];
              }
            }
          }
        }

        if (count($matches) > 10) {
          $matches = array_slice($matches, 0, 10);
        }
      }
      catch (\Exception $e) {
        \Drupal::logger('dds_content')->error($e->getMessage());
      }
    }

    return new JsonResponse(array_values($matches));
  }

}