fox-1.1.2/src/FoxCommandsHelper.php

src/FoxCommandsHelper.php
<?php

declare(strict_types=1);

namespace Drupal\fox;

use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\fox\Plugin\FoxCommandsManager;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Config\Entity\ConfigEntityInterface;

/**
 * Fox command helper class.
 */
class FoxCommandsHelper {

  use StringTranslationTrait;
  use FoxCommonFunctionsTrait;

  /**
   * Constructs a FoxCommandsHelper object.
   */
  public function __construct(
    private readonly EntityTypeManagerInterface $entityTypeManager,
    private readonly EntityTypeBundleInfoInterface $entityTypeBundleInfo,
    private readonly EntityFieldManagerInterface $entityFieldManager,
    private readonly FoxCommandsManager $foxCommandsManager,
    private readonly Connection $connection,
  ) {}

  /**
   * Get entity type and bundle.
   *
   * @param array $parts
   *   Input parts.
   *
   * @return array
   *   Entity type and bundle.
   */
  public static function getTypeBundle(array $parts): array {
    $entity_type = $parts[0];
    $bundle = $parts[1] ?? NULL;
    return [$entity_type, $bundle];
  }

  /**
   * Get entity query.
   *
   * @param string $entity_type
   *   Entity type.
   * @param string|null $bundle
   *   Bundle, if exists.
   *
   * @return \Drupal\Core\Entity\Query\QueryInterface
   *   Entity Query interface.
   */
  public function getEntityQuery(string $entity_type, $bundle = NULL) {
    $query = $this->entityTypeManager
      ->getStorage($entity_type)
      ->getQuery()
      ->accessCheck(TRUE);

    if (!empty($bundle)) {
      $bundle_key = $this->entityKey($entity_type, 'bundle');
      if (!empty($bundle_key)) {
        $query->condition($bundle_key, $bundle);
      }
    }

    return $query;
  }

  /**
   * Get entity type manager.
   *
   * @return \Drupal\Core\Entity\EntityTypeManagerInterface
   *   Entity type manager.
   */
  public function entityTypeManager() {
    return $this->entityTypeManager;
  }

  /**
   * Get entity type bundle info.
   *
   * @return \Drupal\Core\Entity\EntityTypeBundleInfoInterface
   *   Entity type bundle info.
   */
  public function entityTypeBundleInfo() {
    return $this->entityTypeBundleInfo;
  }

  /**
   * Get entity field manager.
   *
   * @return \Drupal\Core\Entity\EntityFieldManagerInterface
   *   Entity field manager.
   */
  public function entityFieldManager() {
    return $this->entityFieldManager;
  }

  /**
   * Get the Fox commands manager.
   *
   * @return \Drupal\fox\Plugin\FoxCommandsManager
   *   Fox commands manager.
   */
  public function foxCommandsManager() {
    return $this->foxCommandsManager;
  }

  /**
   * Get entity type ID key.
   *
   * @param string $entity_type
   *   Entity type.
   * @param string $key
   *   Entity key ID.
   *
   * @return string
   *   Entity key value.
   */
  public function entityKey(string $entity_type, string $key) {
    return $this->entityTypeManager
      ->getDefinition($entity_type)
      ->getKey($key);
  }

  /**
   * Render string with parameters.
   *
   * @param string $template
   *   Text template.
   * @param array $variables
   *   Variables data.
   *
   * @return string
   *   Rendered string.
   */
  public function stringRender(string $template, array $variables = []) {
    $result = $template;

    if (!empty($variables)) {
      preg_match_all('/@([a-zA-Z0-9_.]+)/', $result, $matches);
      $matches = array_filter($matches);
      if (count($matches) == 2) {
        $params = [];
        foreach ($matches[0] as $key => $value) {
          $name = $matches[1][$key];

          // Support array elements.
          $parts = explode('.', $name);
          $name = reset($parts);
          unset($parts[0]);

          $variable = $variables[$name] ?? NULL;
          if (!is_null($variable) && !empty($parts)) {
            foreach ($parts as $part) {
              if (!is_null($variable)) {
                $variable = $variable[$part] ?? NULL;
              }
            }
          }

          if (!is_null($variable)) {
            $params[$value] = $variable;
          }
        }

        if (!(is_array($variable) || is_object($variable)) && !empty($params)) {
          // phpcs:disable
          $value = $this->t($result, $params);
          // phpcs:enable

          $value = (string) $value;
        }
        else {
          $value = $variable;
        }
      }
    }

    if (!isset($value)) {
      return $result;
    }

    if (is_array($value) || is_object($value)) {
      return $value;
    }

    // Check for expression.
    try {
      $query = $this->connection->query("SELECT ($value) AS expr FROM {users} WHERE uid=0");
      $res = $query->fetchAll();
      if (!empty($res)) {
        $value = $res[0]->expr;
      }
    }
    catch (\Exception $e) {
    }

    return $value;
  }

  /**
   * Get record entity.
   *
   * @param array $variables
   *   Variables data.
   *
   * @return mixed
   *   Entity or error.
   */
  public function getEntity(array $variables) {
    $entity_type = $variables['entity_type'] ?? NULL;
    $id = $variables['id'] ?? NULL;

    if (empty($entity_type)) {
      return $this->errorReturn($this->t('Empty entity type. Use USE command.'));
    }

    if ($id === NULL) {
      return $this->errorReturn($this->t('Empty ID. Use GO command.'));
    }

    $entity = $this->entityTypeManager
      ->getStorage($entity_type)
      ->load($id);

    return $entity;
  }

  /**
   * Get record info.
   *
   * @param array $data
   *   Array with entity data.
   * @param array $variables
   *   Variables data.
   *
   * @return mixed
   *   Entities or error.
   */
  public function getEntities(array $data, array $variables) {
    $entity_type = $variables['entity_type'] ?? NULL;
    if (empty($entity_type)) {
      return $this->errorReturn($this->t('Empty entity type. Use USE command.'));
    }

    $id_key = $this->entityKey($entity_type, 'id');
    if (empty($id_key)) {
      return $this->errorReturn($this->t('Empty ID key for entity type "@entity_type".', [
        '@entity_type' => $entity_type,
      ]));
    }

    $ids = array_column($data, $id_key);
    if (empty($ids)) {
      return $this->errorReturn($this->t('Empty ID data for entity type "@entity_type" and ID "@id_key".', [
        '@entity_type' => $entity_type,
        '@id_key' => $id_key,
      ]));
    }

    $entities = $this->entityTypeManager
      ->getStorage($entity_type)
      ->loadMultiple($ids);

    return $entities;
  }

  /**
   * Get fields of entity.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   Entity object.
   *
   * @return array
   *   List of the entity fields.
   */
  public function getFields(EntityInterface $entity) {
    if ($entity instanceof ContentEntityInterface) {
      return $entity->getFields();
    }

    if ($entity instanceof ConfigEntityInterface) {
      return $entity->toArray();
    }
  }

  /**
   * Get record number by ID.
   *
   * @param string $id
   *   ID value.
   * @param array $variables
   *   Variables data.
   *
   * @return int|null
   *   Record number, ordered from 1.
   */
  public function getRecnoById($id, array $variables) {
    $entity_type = $variables['entity_type'] ?? NULL;
    $bundle = $variables['bundle'] ?? NULL;

    $query = $this->getEntityQuery($entity_type, $bundle);

    $id_key = $this->entityKey($entity_type, 'id');
    $query->sort($id_key);
    $ids = $query->execute();

    if (empty($ids)) {
      return NULL;
    }

    $recno = array_search($id, array_values($ids)) + 1;
    return $recno;
  }

  /**
   * Prepare value.
   *
   * @param string|array $value
   *   Original value.
   *
   * @return string
   *   Prepared value.
   */
  public static function prepareValue($value) {
    if (is_array($value)) {
      $value = implode(' ', $value);
    }

    $value = trim($value);
    $value = trim($value, "\"'");
    return $value;
  }

  /**
   * Prepare parameters.
   *
   * @param array $params
   *   Input parameters.
   * @param bool $is_json
   *   Is JSON input.
   * @param string $delimiter
   *   Parameters delimiter.
   *
   * @return array
   *   Prepared parameters.
   */
  public static function prepareParameters(array $params, bool $is_json = FALSE, $delimiter = ','): array {
    $param_str = implode(' ', $params);

    if ($is_json) {
      $pattern = '/(?<=])' . $delimiter . '/';
      $items = preg_split($pattern, $param_str);
      $items = array_map('trim', $items);
    }
    else {
      $items = explode($delimiter, $param_str);
    }

    return $items;
  }

  /**
   * Parse parameters into normal and parameters.
   *
   * @param string $main_param
   *   Main parameter.
   * @param array $params
   *   All parameters.
   *
   * @return array
   *   Normal and additional parameters.
   */
  public static function parseParameters(string $main_param, array $params): array {
    $normal_params = [];
    $additional_params = [];
    $in_main = FALSE;

    foreach ($params as $param) {
      $trimmed = trim($param);

      if (strtolower($trimmed) === $main_param) {
        $in_main = TRUE;
        continue;
      }

      if ($in_main) {
        $additional_params[] = $trimmed;
      }
      else {
        $normal_params[] = $trimmed;
      }
    }

    return [$normal_params, $additional_params];
  }

  /**
   * Get Array from string.
   *
   * @param string $input
   *   Input string.
   *
   * @return array|bool
   *   Return array or FALSE if this is not array.
   */
  public static function getArray(string $input) {
    $input = (string) $input;

    $parts = explode('.', $input);
    if (count($parts) === 1) {
      return FALSE;
    }

    $result = array_pop($parts);
    while ($key = array_pop($parts)) {
      $result = [$key => $result];
    }
    return $result;
  }

  /**
   * Get options for command from parameters list.
   *
   * @param array $params
   *   Parameters list.
   * @param array $default_options
   *   Default parameters list.
   *
   * @return array
   *   Options and parameters list.
   */
  public static function getOptions(array $params, array $default_options = []): array {
    $options = [];
    foreach ($params as $id => $param) {
      if (str_starts_with($param, '--')) {
        $parts = explode('=', $param);

        $key = substr(trim($parts[0]), 2);
        $value = isset($parts[1]) ? trim($parts[1]) : 1;
        $options[$key] = $value;
        unset($params[$id]);
      }
    }

    $options = array_merge($default_options, $options);

    return [
      'options' => $options,
      'params' => $params,
    ];
  }

  /**
   * Get variable string.
   *
   * @param mixed $value
   *   Variable value.
   *
   * @return string
   *   Valuable string.
   */
  public static function getVariable($value): string {
    if ($value === NULL) {
      return '';
    }

    if (is_numeric($value)) {
      return "$value";
    }

    if (is_bool($value)) {
      return $value ? 'TRUE' : 'FALSE';
    }

    if (is_string($value)) {
      return "\"$value\"";
    }

    return '';
  }

  /**
   * Get file path.
   *
   * @param string $filename
   *   Filename value.
   *
   * @return string
   *   Filepath value.
   */
  public static function getFilePath($filename) {
    return getcwd() . '/' . $filename;
  }

  /**
   * Load file.
   *
   * @param string $file
   *   Full filename.
   *
   * @return array
   *   File rows.
   */
  public static function loadFile($file): array {
    $rows = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (!empty($rows)) {
      $rows = array_filter($rows, function ($row) {
        $row = htmlspecialchars_decode(trim($row));
        return $row !== '' && $row[0] !== '#';
      });
    }
    return $rows;
  }

}

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

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