language_negotiation_matrix-1.0.0-beta2/src/Plugin/KeyType/GenericLangcodeKeyType.php
src/Plugin/KeyType/GenericLangcodeKeyType.php
<?php
namespace Drupal\language_negotiation_matrix\Plugin\KeyType;
use Drupal\Core\Form\FormStateInterface;
use Drupal\key\Plugin\KeyPluginFormInterface;
use Drupal\key\Plugin\KeyTypeBase;
/**
* Defines a generic key type with a language association.
*
* @KeyType(
* id = "generic_langcode",
* label = @Translation("Generic with Langcode"),
* description = @Translation("A generic key type to use for passing environment variables that maps to a language id."),
* group = "generic",
* key_value = {
* "plugin" = "textarea_field"
* }
* )
*/
class GenericLangcodeKeyType extends KeyTypeBase implements KeyPluginFormInterface {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'language' => '',
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
$languages = \Drupal::languageManager()->getLanguages();
foreach ($languages as $language) {
$options[$language->getId()] = $language->getName();
}
$form['language'] = [
'#type' => 'select',
'#title' => $this->t('Language'),
'#description' => $this->t('The key will be matched to a language.'),
'#options' => $options,
'#default_value' => $this->getConfiguration()['language'],
'#required' => TRUE,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state): void {
$this->setConfiguration($form_state->getValues());
}
/**
* {@inheritdoc}
*/
public static function generateKeyValue(array $configuration): string {
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 = $key_value;
$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]));
}
}
}
}
