ttv_assistant-1.0.x-dev/src/Services/AssistantService.php

src/Services/AssistantService.php
<?php

namespace Drupal\ttv_assistant\Services;

use Drupal\Core\Session\AccountProxy;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\node\NodeInterface;
use Drupal\field\Entity\FieldConfig;

/**
 * Service handler for Notification Logger.
 */
class AssistantService {

  /**
   * Drupal\Core\Session\AccountProxy definition.
   *
   * @var \Drupal\Core\Session\AccountProxy
   */
  protected $currentUser;

  /**
   * Symfony\Component\HttpFoundation\Request definition.
   *
   * @var Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * {@inheritdoc}
   */
  public function __construct(AccountProxy $current_user,
  RequestStack $request) {
    $this->currentUser = $current_user;
    $this->request     = $request;
  }

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

  /**
   * Extract taxonomy field from node.
   */
  public static function extractTaxonomyField($node) {
    $taxonomy_fields = [];
    if ($node instanceof NodeInterface) {
      // Find taxonomy fields.
      $bundle = $node->bundle();
      $entityFieldManager = \Drupal::service('entity_field.manager');
      $fields = $entityFieldManager->getFieldDefinitions('node', $bundle);
      if ($fields) {
        foreach ($fields as $field_name => $field) {
          if ($field instanceof FieldConfig
            && $field->getType() == 'entity_reference'
            && $field->getSetting('target_type') == 'taxonomy_term') {
            $taxonomy_fields[$field_name]['target_bundles'] = $field->getSettings()['handler_settings']['target_bundles'];
            $taxonomy_fields[$field_name]['cardinality'] = $node->getFieldDefinition($field_name)
              ->getFieldStorageDefinition()
              ->getCardinality();
          }
        }
      }
    }
    return $taxonomy_fields;
  }

  /**
   * Extract taxonomies from input text.
   */
  public static function getRecommendTag($bundle = '', $input = '') {
    // Based on config, find recommend tag via taxonomies or files.
    $recommend = self::tagByDatabase($bundle, $input);
    return $recommend;
  }

  /**
   * Search through taxonomies to return recommend tags.
   *
   * Rules: count match tags by input.
   */
  public static function tagByDatabase($bundle = '', $input = '') {
    $recommend           = [];
    $entityTypeManager   = \Drupal::entityTypeManager();
    $config              = \Drupal::config('ttv_assistant.settings');
    $vocabularies        = $entityTypeManager->getStorage('taxonomy_vocabulary')->loadMultiple();
    $caseSensitivity     = $config->get('case_sensitivity') ?? 0;
    $search_vocabularies = array_diff_key($vocabularies, array_filter($config->get("taxonomy_ignored")));
    foreach (array_keys($search_vocabularies) as $key) {
      $terms = $entityTypeManager->getStorage('taxonomy_term')->loadTree($key);
      $matches = [];
      foreach ($terms as $term) {
        $term_name = $term->name;
        if ($caseSensitivity == '1') {
          preg_match_all('/\b' . $term_name . '\b/', $input, $matches);
        }
        else {
          preg_match_all('/\b' . $term_name . '\b/i', $input, $matches);
        }
        if (!empty($matches[0])) {
          $recommend[$term->tid] = [
            'tid' => $term->tid,
            'vid' => $term->vid,
            'title' => $term->name,
            'weight' => count($matches[0]),
          ];
        }
      }
    }

    // Sort by weight.
    usort($recommend, function ($a, $b) {
      return (($a["weight"] < $b["weight"]) ? -1 : ($a["weight"] > $b["weight"])) ? 1 : 0;
    });
    // If max number is set, return sort by weight, split for result.
    if ($config->get('max_tag') != "-1") {
      $recommend = array_chunk($recommend, $config->get('max_tag'))[0];
    }
    return $recommend;
  }

}

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

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