language_negotiation_matrix-1.0.0-beta2/src/Plugin/KeyType/GenericMultivalueKeyType.php

src/Plugin/KeyType/GenericMultivalueKeyType.php
<?php

namespace Drupal\language_negotiation_matrix\Plugin\KeyType;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\key\Plugin\KeyTypeBase;
use Drupal\key\Plugin\KeyTypeMultivalueInterface;

/**
 * Defines a generic key type for authentication with multiple values.
 *
 * @KeyType(
 *   id = "generic_multivalue",
 *   label = @Translation("Generic (Multivalue)"),
 *   description = @Translation("A generic key type to use for passing environment variables that contains multiple values in JSON format."),
 *   group = "generic",
 *   key_value = {
 *     "plugin" = "textarea_field"
 *   },
 *   multivalue = {
 *     "enabled" = true,
 *     "fields" = {}
 *   }
 * )
 */
class GenericMultivalueKeyType extends KeyTypeBase implements KeyTypeMultivalueInterface {

  /**
   * {@inheritdoc}
   */
  public static function generateKeyValue(array $configuration): string {
    // Return an empty JSON element.
    return '[]';
  }

  /**
   * {@inheritdoc}
   */
  public function validateKeyValue(array $form, FormStateInterface $form_state, $key_value): void {
    if (empty($key_value)) {
      return;
    }

    // If a field named "key_value" exists in the key input settings, use it for
    // the error element, if necessary. Otherwise, use the entire form.
    $error_element = $form['settings']['input_section']['key_input_settings']['key_value'] ?? $form;

    $value = $this->unserialize($key_value);
    if ($value === NULL) {
      $form_state->setError($error_element, $this->t('The key value does not contain valid JSON.'));
      return;
    }

    $definition = $this->getPluginDefinition();
    $fields = $definition['multivalue']['fields'];

    foreach ($fields as $id => $field) {
      if (!is_array($field)) {
        $field = ['label' => $field];
      }

      if (isset($field['required']) && $field['required'] === FALSE) {
        continue;
      }

      if (!isset($value[$id])) {
        $form_state->setError($error_element, $this->t('The key value is missing the field %field.', ['%field' => $id]));
      }
      elseif (empty($value[$id])) {
        $form_state->setError($error_element, $this->t('The key value field %field is empty.', ['%field' => $id]));
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  public function serialize(array $array): bool|string {
    return Json::encode($array);
  }

  /**
   * {@inheritdoc}
   */
  public function unserialize($value) {
    if ($value === NULL) {
      return NULL;
    }
    return Json::decode($value);
  }

}

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

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