bim_gdpr-1.0.0-rc3/src/PluginManager/BimGdprTemplate/BimGdprTemplateTrait.php

src/PluginManager/BimGdprTemplate/BimGdprTemplateTrait.php
<?php

namespace Drupal\bim_gdpr\PluginManager\BimGdprTemplate;

use Drupal\bim_gdpr\Services\TemplateManager;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;

/**
 * Trait BimGdprTemplateTrait.
 *
 * Trait for defining translation form.
 *
 * @package Drupal\bim_gdpr\PluginManager\BimGdprTemplate
 */
trait BimGdprTemplateTrait {

  /**
   * Settings.
   *
   * @var array
   */
  protected $settings;

  /**
   * Form.
   *
   * @var array
   */
  protected $form;

  /**
   * Form state.
   *
   * @var \Drupal\Core\Form\FormStateInterface
   */
  protected $formState;

  /**
   * Default text format.
   *
   * @var string
   */
  protected $defaultFormat;

  /**
   * Init the tools.
   *
   * @param string $type
   *   The type.
   * @param \Drupal\bim_gdpr\Services\TemplateManager $templateManager
   *   The template manager.
   * @param array $form
   *   THe form.
   * @param \Drupal\Core\Form\FormStateInterface $formState
   *   The formstate.
   *
   * @return $this
   */
  public function initTemplateTrait(
    string $type,
    TemplateManager $templateManager,
    array $form,
    FormStateInterface $formState
  ) {
    $data = $templateManager->getLocaleSettings('settings');
    $templateManager->cleanOutputLocalData($data);
    $this->settings = isset($data[$type]) ? $data[$type] : [];
    $this->form = $form;
    $this->formState = $formState;
    return $this;
  }

  /**
   * Add a text input.
   *
   * @param int $id
   *   The field id.
   * @param string $title
   *   The field title.
   * @param array $options
   *   The options.
   *
   * @return BimGdprTemplateTrait
   *   This.
   */
  public function addText($id, $title, array $options = []) {
    return $this->addField('textarea', $id, $title, $options);
  }

  /**
   * Add a text input.
   *
   * @param int $id
   *   The field id.
   * @param string $title
   *   The field title.
   * @param array $options
   *   The options.
   *
   * @return BimGdprTemplateTrait
   *   This.
   */
  public function addTextFormat($id, $title, array $options = []) {
    $defaultFormatText = $this->getDefaultFormatText();
    return $this->addField(
      'text_format',
      $id,
      $title,
      $options + [
        '#default_value' => isset($this->settings[$id]) ? $this->settings[$id]['value'] : '',
        '#format' => isset($this->settings[$id]) ? $this->settings[$id]['format'] : $defaultFormatText,
      ]
    );
  }

  /**
   * Return the default text format id.
   *
   * @return string
   *   The default text format id.
   */
  protected function getDefaultFormatText(): string {
    if (is_null($this->defaultFormat)) {
      $this->defaultFormat = '';
      if ($formats = \Drupal::entityTypeManager()->getStorage('filter_format')) {
        $this->defaultFormat = array_keys($formats->loadMultiple())[0];
      }
    }
    return $this->defaultFormat;
  }

  /**
   * Add a text input.
   *
   * @param int $id
   *   The field id.
   * @param string $title
   *   The field title.
   * @param array $options
   *   The options.
   *
   * @return BimGdprTemplateTrait
   *   This.
   */
  public function addInput($id, $title, array $options = []) {
    return $this->addField('textfield', $id, $title, $options);
  }

  /**
   * Add a field in form.
   *
   * @param string $type
   *   The type.
   * @param string $id
   *   The field id.
   * @param string $title
   *   The field title.
   * @param array $options
   *   The options.
   */
  protected function addField($type, $id, $title, array $options = []) {
    $this->form[$id] = $options + [
      '#type' => $type,
      '#title' => $title,
      '#default_value' => isset($this->settings[$id]) ? $this->settings[$id] : '',
    ];

    return $this;
  }

  /**
   * Add a field to not load css.
   */
  public function addNoCss() {
    return $this->addField(
      'checkbox',
      BimGdprTemplateInterface::FIELD_NO_CSS,
      $this->t('Do not load template CSS'),
      [
        '#description' => $this->t(
          "Check this if you don't want to use the default template css but your own."
        ),
      ]
    );
  }

  /**
   * Initialise input from translation data.
   */
  protected function initFromJsonTemplate() {
    $url = $this->getLocalisationJsonTemplateUrl();
    $id = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $url = str_replace(static::LANGUAGE_TOKEN, $id, $url);
    if (!empty($url)) {
      try {
        /** @var \http\Client\Response $body */
        $response = \Drupal::httpClient()->get($url);
        $content = Json::decode($response->getBody());
        $this->createInputFromJson($content);
      }
      catch (\Exception $e) {
        \Drupal::messenger()->addError(
          $this->t("The translation information could't be retrieved at @url", ['@url' => $url])
        );
      }
    }
  }

  /**
   * Create an input from json.
   *
   * @param array $translationData
   *   The translation data.
   */
  protected function createInputFromJson(array $translationData): void {
    foreach ($translationData as $fieldName => $value) {
      if (is_string($value)) {
        $this->addInputFromFieldName($fieldName, $value);
      }
      elseif (is_array($value)) {
        $this->addInputFromFieldData($fieldName, $value);
      }
    }
  }

  /**
   * Add Input from field name and translation data.
   *
   * @param string $fieldName
   *   THe field name.
   * @param string $translation
   *   The translatino data.
   */
  protected function addInputFromFieldName(string $fieldName, string $translation) {
    $this->addText($fieldName, $translation);
  }

  /**
   * Add a field according to the translationData format.
   *
   * @param string $fieldName
   *   The field name.
   * @param array $translationData
   *   The translation data.
   */
  protected function addInputFromFieldData(string $fieldName, array $translationData) {
    // Get the title.
    $title = isset($translationData['description']) ? $translationData['description'] : $fieldName;

    $options = [
      '#description' => $this->getDescriptionFromTranslationData($translationData),
    ];

    switch ($translationData['type']) {
      case 'long':
        $this->addTextFormat($fieldName, $title, $options);
        break;

      case 'short':
        $this->addInput($fieldName, $title, $options);
        break;

      default:
        $this->addText($fieldName, $title, $options);
        break;
    }
  }

  /**
   * Return the description of a field from translation description file.
   *
   * @param array $translationData
   *   The translation data.
   *
   * @return string
   *   The description.
   */
  protected function getDescriptionFromTranslationData(array $translationData) {
    $description = isset($translationData['description']) ? $translationData['description'] : '';

    // Add value.
    if ($translationData['value']) {
      $description .= '<br/><br/>';
      $description .= $this->t(
        'Value : @value',
        [
          '@value' => $translationData['value'],
        ]
      );
    }

    // Add Arguments.
    if (isset($translationData['args']) && is_array($translationData['args']) && !empty($translationData['args'])) {
      $args = [];
      foreach ($translationData['args'] as $arg) {
        $args[] = $this->t(
          '@argId: @description',
          [
            '@argId' => $arg['name'],
            '@description' => $arg['description'],
          ]
        );
      }

      $description .= '<br/><br/>';
      $description .= $this->t(
        'Available arguments : <ul><li>@args</li></ul>',
        [
          '@args' => implode('</li><li>', $args),
        ]
      );
    }

    return $description;
  }

}

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

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