You are here

public function AuthenticationMultivalueKeyType::validateKeyValue in Key 8

Allows the Key Type plugin to validate the key value.

Parameters

array $form: An associative array containing the structure of the plugin form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the plugin form.

string|null $key_value: The key value to be validated.

Overrides KeyTypeInterface::validateKeyValue

File

src/Plugin/KeyType/AuthenticationMultivalueKeyType.php, line 40

Class

AuthenticationMultivalueKeyType
Defines a generic key type for authentication with multiple values.

Namespace

Drupal\key\Plugin\KeyType

Code

public function validateKeyValue(array $form, FormStateInterface $form_state, $key_value) {
  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.
  if (isset($form['settings']['input_section']['key_input_settings']['key_value'])) {
    $error_element = $form['settings']['input_section']['key_input_settings']['key_value'];
  }
  else {
    $error_element = $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,
      ]));
    }
  }
}