You are here

public function CustomConfig::validateCustomConfig in CKEditor custom config 8.3

Same name and namespace in other branches
  1. 8.2 src/Plugin/CKEditorPlugin/CustomConfig.php \Drupal\ckeditor_config\Plugin\CKEditorPlugin\CustomConfig::validateCustomConfig()

Custom validator for the "custom_config" element in settingsForm().

File

src/Plugin/CKEditorPlugin/CustomConfig.php, line 140

Class

CustomConfig
Defines the "customconfig" plugin.

Namespace

Drupal\ckeditor_config\Plugin\CKEditorPlugin

Code

public function validateCustomConfig(array $element, FormStateInterface $form_state) {

  // Convert submitted value into an array. Return is empty.
  $config_value = $element['#value'];
  if (empty($config_value)) {
    return;
  }
  $config_array = preg_split('/\\R/', $config_value);

  // Loop through lines.
  $i = 1;
  foreach ($config_array as $config_value) {

    // Check that syntax matches "[something] = [something]".
    preg_match('/(.*?) \\= (.*)/', $config_value, $matches);
    if (empty($matches)) {
      $form_state
        ->setError($element, $this
        ->t('The configuration syntax on line @line is incorrect. The correct syntax is "[setting.name] = [value]"', [
        '@line' => $i,
      ]));
    }
    else {

      // Check is value is valid JSON.
      $exploded_value = explode(" = ", $config_value);
      $key = $exploded_value[0];
      $value = $exploded_value[1];

      // Create JSON string and attempt to decode.
      // If invalid, then set error.
      $json = '{ "' . $key . '": ' . $value . ' }';
      $decoded_json = Json::decode($json, TRUE);
      if (is_null($decoded_json)) {
        $form_state
          ->setError($element, $this
          ->t('The configuration value on line @line is not valid JSON.', [
          '@line' => $i,
        ]));
      }
    }
    $i++;
  }
}