jfu-1.0.x-dev/src/Services/JfuConfigServices.php

src/Services/JfuConfigServices.php
<?php

namespace Drupal\jfu\Services;

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Entity\EntityDisplayRepository;
use Drupal\Core\Entity\ContentEntityType;
use Drupal\Core\Image\ImageFactory;

 /*
 * @package Drupal\JfuConfig
 */
class JfuConfigServices {
  /**
   * The entity repository service.
   *
   * @var \Drupal\Core\Entity\EntityRepositoryInterface
   */
  protected $entityRepository;

  /**
   * The entity field manager.
   *
   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
   */
  protected $entityFieldManager;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected EntityTypeManagerInterface $entityTypeManager;

  /**
   * The entity display repository service.
   *
   * @var \Drupal\Core\Entity\EntityDisplayRepository
   */
  protected $entityDisplayRepository;

  /**
   * The image factory.
   *
   * @var \Drupal\Core\Image\ImageFactory
   */
  protected $imageFactory;

  /**
   * Constructs a JfuConfigServices.
   *
   * @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
   *   The entity repository service.
   * @param \Drupal\Core\Entity\EntityFieldManagerInterface $entity_field_manager
   *   The entity field manager.
   * @param Drupal\jfu\Services\EntityTypeManagerInterface $entity_type_manager
   *   The The entity type manager.
   * @param \Drupal\Core\Entity\EntityDisplayRepository $entity_display_repository
   *   The file storage service.
   * @param \Drupal\Core\Image\ImageFactory $image_factory
   *   The image factory.
   */
  public function __construct(EntityRepositoryInterface $entity_repository, EntityFieldManagerInterface $entity_field_manager, EntityTypeManagerInterface $entity_type_manager, EntityDisplayRepository $entity_display_repository, ImageFactory $image_factory) {
    $this->entityRepository = $entity_repository;
    $this->entityFieldManager = $entity_field_manager;
    $this->entityTypeManager = $entity_type_manager;
    $this->entityDisplayRepository = $entity_display_repository;
    $this->imageFactory = $image_factory;
  }

 /**
 *  List default Settings.
  * @return: Array.
 */
  public function jfuComponents() {
    $components_config = [
      'quote' => [
        'extensions' => 'png, jpg, jpeg',
        'directory' => 'jfu-images',
        'max_size' => '',
        'max_dimensions' => [
          'width' => '',
          'height' => ''
        ],
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'accordion' => [
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'multi_row_accordion' => [
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'banner' => [
        'extensions' => 'png, jpg, jpeg',
        'directory' => 'jfu-images',
        'max_size' => '',
        'max_dimensions' => [
          'width' => '',
          'height' => ''
        ],
        'max_dimensions_responsive' => [
          'width' => '',
          'height' => ''
        ],
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'block' => [
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'tabs' => [
        'extensions' => 'png, jpg, jpeg',
        'directory' => 'jfu-images',
        'max_size' => '',
        'max_dimensions' => [
          'width' => '',
          'height' => ''
        ],
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'embed' => [
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'gallery' => [
        'extensions' => 'png, jpg, jpeg',
        'directory' => 'jfu-images',
        'max_size' => '',
        'max_dimensions' => [
          'width' => '',
          'height' => ''
        ],
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'simple_card' => [
        'extensions' => 'png, jpg, jpeg',
        'directory' => 'jfu-images',
        'max_size' => '',
        'max_dimensions' => [
          'width' => '',
          'height' => ''
        ],
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'content_columns' => [
        'extensions' => 'png, jpg, jpeg',
        'directory' => 'jfu-images',
        'max_size' => '',
        'max_dimensions' => [
          'width' => '',
          'height' => ''
        ],
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
        'allow_group_items' => 0
      ],
      'data_number_card' => [
        'extensions' => 'png, jpg, jpeg',
        'directory' => 'jfu-images',
        'max_size' => '',
        'max_dimensions' => [
          'width' => '',
          'height' => ''
        ],
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
        'allow_group_items' => 0
      ],
      'rich_text' => [
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'table' => [
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
      ],
      'link_list' => [
        'allow_classes' => 0,
        'allow_select_class' => 0,
        'class_list' => '',
        'allow_group_items' => 0
      ],
    ];

    $added_components = [];
    \Drupal::moduleHandler()->invokeAllWith('jfu_add_components',
      function (callable $hook, string $module) use (&$added_components) {
        $hook($added_components);
      }
    );

    \Drupal::moduleHandler()->alter('jfu_add_components', $added_components);

    //TODO: Check components names in order to prevent name collision.
    if(!empty($added_components)) {
      foreach ($added_components as $key => $value) {
        $components_config[$key] = $value;

        if(isset($value['image']) && $value['image']) {
          $components_config[$key]['extensions'] = 'png, jpg, jpeg';
          $components_config[$key]['directory'] = 'jfu-images';
          $components_config[$key]['max_size'] = '';
          $components_config[$key]['max_dimensions'] = [
            'width' => '',
            'height' => ''
          ];
        }

        if(isset($value['responsive_image']) && $value['responsive_image']) {
          $components_config[$key]['max_dimensions_responsive'] = [
            'width' => '',
            'height' => ''
          ];
        }

        //TODO: Probably will not need to be removed when restructuring the components.
        unset($components_config[$key]['image']);
        unset($components_config[$key]['responsive_image']);
      }
    }

    return $components_config;
  }

  /**
  *  List all components.
  * @return: Array.
  */
  public function jfuListComponents() {
    foreach ($this->jfuComponents() as $key_components => $components) {
      $Components[$key_components] = ucfirst(str_replace('_', ' ', $key_components));
    }

    return $Components;
  }

  /**
  *  Jfu config name.
  * @return: string.
  */
  public function jfuConfigName($entity_type, $bundle, $field_name) {
    return 'jfu.field.' . $entity_type . '.' . $bundle . '.' . $field_name;
  }

   /**
   * Parse an HTML snippet for any linked file with data-entity-uuid attributes.
   *
   * @param string $text
   *   The partial (X)HTML snippet to load. Invalid markup will be corrected on
   *   import.
   *
   * @return array
   *   An array of all found UUIDs.
   */
  public function extractFilesUuid($text) {
    $dom = Html::load($text);
    $xpath = new \DOMXPath($dom);
    $uuids = [];
    foreach ($xpath->query('//*[@data-entity-type="file" and @data-entity-uuid]') as $file) {
      $uuids[] = $file->getAttribute('data-entity-uuid');
    }

    return $uuids;
  }

  /**
   * Records file usage of files referenced by formatted text fields.
   *
   * Every referenced file that does not yet have the STATUS_PERMANENT
   * state, will be given that state.
   *
   * @param array $uuids
   *   An array of file entity UUIDs.
   */
  public function recordFileUsage(array $uuids, $entity) {
    $file_usage = \Drupal::service('file.usage');

    try {
      foreach ($uuids as $uuid) {
        if ($file = $this->entityRepository->loadEntityByUuid('file', $uuid)) {
          /** @var \Drupal\file\FileInterface $file */
          if ($file->isTemporary()) {
            $file->setPermanent();
            $file->save();
          }

          if (!empty($entity->id())) {
            $file_usage->add($file, 'jfu', $entity->getEntityTypeId(), $entity->id());
          }
        }
      }
    }
    catch (EntityStorageException $exception) {
      $this->logger('jfu')->warning($exception->getMessage());
    }
  }

  /**
   * @param string $entity_type, $bundle
   *
   * @return array
   *  An array of Json type fields.
  */
  public function jfuGetFieldDefinitions($entity_type, $bundle) {
    $field_type = [
      'json',
      'json_native',
      'json_native_binary'
    ];
    $jfu_field_json_native = [];
    $jfu_field_definitions = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle);

    foreach ($jfu_field_definitions as $field_name => $field_definition) {
      if (!empty($field_definition->getTargetBundle()) && in_array($field_definition->getType(), $field_type)) {
        $jfu_field_json_native[$field_name] = $field_name;
      }
    }

    return $jfu_field_json_native;
  }

  /**
   * Migrate component configurations for nodes, blocks, and taxonomy.
   * @param
   *
   * @return
  */
  private function possibleEntities() {
    return [
      'block_content',
      'commerce_order',
      'commerce_product',
      'commerce_product_variation',
      'commerce_store',
      'group',
      'comment',
      'media',
      'node',
      'profile',
      'taxonomy_term',
    ];
  }

  /**
   * Migrate component configurations for nodes, blocks, taxonomy ...
   * @param
   *
   * @return
  */
  public function migrateComponentConfig() {
    $definitions = $this->entityTypeManager->getDefinitions();
    $possible_entities = $this->possibleEntities();

    foreach ($definitions as $entity_type) {
      if ($entity_type instanceof ContentEntityType) {
        $entity_name = $entity_type->id();
        if (in_array($entity_name, $possible_entities)) {
          $load_entity_bundles =  $entity_name === 'taxonomy_term' ? 'taxonomy_vocabulary' : $entity_name . '_type';
          $bundles = $this->entityTypeManager->getStorage($load_entity_bundles)->loadMultiple();
          foreach ($bundles as $bundle) {
            $bundle_name = $bundle->id();
            $field_definitions = $this->jfuGetFieldDefinitions($entity_name, $bundle_name);
            if (!empty($field_definitions)) {
              foreach ($field_definitions as $field_key => $field_name) {
                $field_settings = $this->entityDisplayRepository->getFormDisplay($entity_name, $bundle_name)->getComponents();
                $settings = $field_settings[$field_name]['settings'];
                if (isset($settings['components_config']) && isset($settings['components'])) {
                  $config_name = $this->jfuConfigName($entity_name, $bundle_name, $field_name);
                  $config = \Drupal::service('config.factory')->getEditable($config_name);
                  if(empty($config->get('components')) && empty($config->get('components_config'))) {
                    $config->set('components', $settings['components'])->save();
                    $config->set('components_config', $settings['components_config'])->save();
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  /**
   * Set width and height of all entities used by components.
   * @param
   *
   * @return
  */
  public function setWidthHeight() {
    $definitions = $this->entityTypeManager->getDefinitions();
    $possible_entities = $this->possibleEntities();

    foreach ($definitions as $entity_type) {
      if ($entity_type instanceof ContentEntityType) {
        $entity_name = $entity_type->id();
        if (in_array($entity_name, $possible_entities)) {
          $load_entity_bundles =  $entity_name === 'taxonomy_term' ? 'taxonomy_vocabulary' : $entity_name . '_type';
          $bundles = $this->entityTypeManager->getStorage($load_entity_bundles)->loadMultiple();
          foreach ($bundles as $bundle) {
            $bundle_name = $bundle->id();
            $field_definitions = $this->jfuGetFieldDefinitions($entity_name, $bundle_name);
            if (!empty($field_definitions)) {
              foreach ($field_definitions as $field_key => $field_name) {
                $ids = \Drupal::entityQuery($entity_name)->accessCheck(TRUE)->condition('type', $bundle_name)->execute();
                foreach ($ids as $k_id => $id) {
                  $entity = $this->entityTypeManager->getStorage($entity_name)->load($id);
                  $json_field = $entity->get($field_name)->getValue();
                  if (!empty($json_field)) {
                    $field_data = [];
                    foreach ($json_field as $j => $json) {
                      $data = json_decode($json['value']);
                      if (isset($data->image) && !empty($data->image->fid)) {
                        $image = $this->imageFactory->get($data->image->value);
                        $data->image->width = $image->getWidth();
                        $data->image->height = $image->getHeight();
                      }

                      if (isset($data->image) && empty($data->image->fid)) {
                        $data->image->width = '';
                        $data->image->height = '';
                      }

                      if (isset($data->items->items)) {
                        foreach ($data->items->items as $i => $item) {
                          if (isset($item->image) && !empty($item->image->fid)) {
                            $image = $this->imageFactory->get($item->image->value);
                            $data->items->items[$i]->image->width = $image->getWidth();
                            $data->items->items[$i]->image->height = $image->getHeight();
                          }

                          if (isset($item->image) && empty($item->image->fid)) {
                            $data->items->items[$i]->image->width = '';
                            $data->items->items[$i]->image->height = '';
                          }
                        }
                      }

                      $field_data[$j]['value'] = json_encode($data);
                    }

                    if (!empty($field_data)) {
                      $entity->set($field_name, $field_data);
                      $entity->save();
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

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

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