jfu-1.0.x-dev/src/Plugin/Field/FieldFormatter/JSONComponentFormatter.php

src/Plugin/Field/FieldFormatter/JSONComponentFormatter.php
<?php

namespace Drupal\jfu\Plugin\Field\FieldFormatter;

use Drupal\Core\Config\ConfigFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\image\Entity\ImageStyle;
use Drupal\Component\Serialization\Json;
use Drupal\jfu\Services\JfuConfigServices;

/**
 * Plugin implementation of the 'json_component_formatter' formatter.
 *
 * @FieldFormatter(
 *   id = "json_component_formatter",
 *   label = @Translation("Components"),
 *   field_types = {
 *     "json",
 *     "json_native",
 *     "json_native_binary",
 *   },
 * )
 */

class JSONComponentFormatter extends FormatterBase {
  /**
   * The config factory.
   *
   * @var Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * The jfu Config.
   *
   * @var Drupal\jfu\Services\JfuConfigServices
   */
  protected $jfuConfig;

  /**
   * Constructs a new CommentDefaultFormatter.
   *
   * @param string $plugin_id
   *   The plugin_id for the formatter.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
   *   The definition of the field to which the formatter is associated.
   * @param array $settings
   *   The formatter settings.
   * @param string $label
   *   The formatter label display setting.
   * @param string $view_mode
   *   The view mode.
   * @param array $third_party_settings
   *   Third party settings.
   * @param Drupal\Core\Config\ConfigFactory $config_factory
   *   The config factory.
   * @param Drupal\jfu\Services\JfuConfigServices $jfu_config
   *   The jfu Config.
   */
  public function __construct(
    $plugin_id,
    $plugin_definition,
    FieldDefinitionInterface $field_definition,
    array $settings,
    $label,
    $view_mode,
    array $third_party_settings,
    ConfigFactory $config_factory,
    JfuConfigServices $jfu_config) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->configFactory = $config_factory;
    $this->jfuConfig = $jfu_config;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('config.factory'),
      $container->get('jfu_config.service')
    );
  }

  /**
   * {@inheritdoc}
  */
  public static function defaultSettings() {
    $components_config = [
      'data_number_card' => [
        'data_delay' => 5,
        'data_increment' => 10,
      ],
    ];

    return [
      'format_settings_components' => $components_config,
    ] + parent::defaultSettings();
  }

  /**
   * {@inheritdoc}
  */
  public function settingsForm(array $form, FormStateInterface $form_state) {
    $display_config = $this->getSetting('format_settings_components');
    $styles = ImageStyle::loadMultiple();
    $list_styles = [];
    if (!empty($styles)) {
      foreach ($styles as $key_style => $style) {
        $list_styles[$style->id()] = $style->label();
      }
    }

    $form['format_settings_components'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Format Settings Components'),
    ];

    $form['format_settings_components']['general'] = [
      '#type' => 'details',
      '#title' => $this->t('General'),
    ];

    $form['format_settings_components']['general']['image_style'] = [
      '#type' => 'select',
      '#title' => $this->t('Image style'),
      '#default_value' => isset($display_config['general']['image_style']) ? $display_config['general']['image_style'] : '',
      "#empty_option"=>t('None (original image)'),
      '#options' => $list_styles,
      '#description' => $this->t("This field is intended for converting images to WEBP. Use image styles with different effects cautiously, as this configuration will affect all components of this field."),
    ];

    $form['format_settings_components']['data_number_card'] = [
      '#type' => 'details',
      '#title' => $this->t('Config number card'),
    ];

    $form['format_settings_components']['data_number_card']['data_delay'] = [
      '#type' => 'number',
      '#default_value' => $display_config['data_number_card']['data_delay'],
      '#title' => $this->t('Data delay'),
      '#description' => $this->t("A number data delay for numscroller."),
      '#min' => 5,
      '#required' => TRUE,
    ];

    $form['format_settings_components']['data_number_card']['data_increment'] = [
      '#type' => 'number',
      '#default_value' => $display_config['data_number_card']['data_increment'],
      '#title' => $this->t('Data increment'),
      '#description' => $this->t("A number data increment for numscroller."),
      '#min' => 10,
      '#required' => TRUE,
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function settingsSummary() {
    $components_config = $this->getSetting('format_settings_components');
    $summary = [];
    $summary[] = $this->t('Displays all components.');
    $summary[] = 'Config numscroller = Data delay : ' . $components_config['data_number_card']['data_delay'] . ' and Data increment : ' . $components_config['data_number_card']['data_increment'];
    return $summary;
  }

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $template = '';
    \Drupal::moduleHandler()->invokeAllWith('jfu_add_template',
      function (callable $hook, string $module) use (&$template) {
        $hook($template);
      }
    );
    \Drupal::moduleHandler()->alter('jfu_add_template', $template);

    $components_config = $this->getSetting('format_settings_components');
    $elements = [];
    $json_array = [];

    $json_type_array = [];

    foreach ($items as $key => $item) {
      $json_array[$key] = Json::decode($item->value);
      $json_type_array = $this->jfuImageStyle($json_array[$key]);

      $classes = '';
      if (!empty($json_type_array['options']['custom_classes'])) {
        $clean_string_classes = str_replace(' ', '', $json_type_array['options']['custom_classes']);
        $classes .= ' ' . str_replace(',', ' ', $clean_string_classes);
      }

      if (!empty($json_type_array['options']['selected_class'])) {
        $classes .= ' ' . $json_type_array['options']['selected_class'];
      }

      $jfu_template = 'json_widget_component';
      if(isset($json_type_array['module_name']) && $json_type_array['module_name'] != 'jfu' && !empty($template)) {
        $jfu_template = $template;
      }


      if(isset($json_type_array['options']['group_items_quantity'])
        && isset($json_type_array['options']['group_classes'])
        && !empty($json_type_array['options']['group_items_quantity'])
        && $json_type_array['options']['group_items_quantity'] != 0) {
        $json_type_array = $this->jfuAddGroupItems($json_type_array);

      }

      $elements[] = [
        '#theme' => $jfu_template,
        '#values' => $json_array,
        '#json_array' => $json_type_array,
        '#components_config' => $components_config,
        '#classes' => $classes,
      ];
    }

    return $elements;
  }

  private function jfuAddGroupItems($json_type_array) {
    $group_items = [];
    $key_init = 0;
    $number_init = 0;
    foreach ($json_type_array['items']['items'] as $key => $value) {
      $number_init ++;
      if($number_init > $json_type_array['options']['group_items_quantity']){
        $number_init = 1;
        $key_init = $key_init + 1;
      }

      $group_items[$key_init][$key] = $value;
    }

    $group_classes = '';
    if (!empty($json_type_array['options']['group_classes'])) {
      $clean_string_classes = str_replace(' ', '', $json_type_array['options']['group_classes']);
      $group_classes .= ' ' . str_replace(',', ' ', $clean_string_classes);
    }

    $json_type_array['items']['group_items'] = $group_items;
    $json_type_array['items']['group_classes'] = $group_classes;

    return $json_type_array;
  }

  /**
   * {@inheritdoc}
   */
  private function jfuImageStyle($data) {
    $display_config = $this->getSetting('format_settings_components');
    if (isset($display_config['general']['image_style']) && !empty($display_config['general']['image_style'])) {
      if ($data['type'] == 'tabs') {
        foreach ($data['items'] as $key => $tab) {
          $data['items'][$key]['body'] = $this->jfuSetImageStyle($tab['body']);
        }
      }
      else {
        $data = $this->jfuSetImageStyle($data);
      }
    }
    return $data;
  }

  /**
   * {@inheritdoc}
  */
  private function jfuImageStyleUri($uri) {
    $display_config = $this->getSetting('format_settings_components');
    $image_style = $display_config['general']['image_style'];
    $style = ImageStyle::load($image_style);

    return $style->buildUrl($uri);
  }

  /**
   * {@inheritdoc}
  */
  private function jfuSetImageStyle($data) {
    if (isset($data['image']) && !empty($data['image']['fid'])) {
      $data['image']['value'] = $this->jfuImageStyleUri($data['image']['value']);
    }

    if (isset($data['responsive_image']) && !empty($data['responsive_image']['fid'])) {
      $data['responsive_image']['value'] = $this->jfuImageStyleUri($data['responsive_image']['value']);
    }

    if (isset($data['items']['items'])) {
      foreach ($data['items']['items'] as $k_i => $item) {
        if (isset($item['image']) && !empty($item['image']['fid'])) {
          $data['items']['items'][$k_i]['image']['value'] = $this->jfuImageStyleUri($item['image']['value']);
        }

        if (isset($item['responsive_image']) && !empty($item['responsive_image']['fid'])) {
          $data['items']['items'][$k_i]['responsive_image']['value'] = $this->jfuImageStyleUri($item['responsive_image']['value']);
        }
      }
    }

    return $data;
  }
}

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

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