You are here

protected static function YamlFormCodeMirror::getErrors in YAML Form 8

Get validation errors.

1 call to YamlFormCodeMirror::getErrors()
YamlFormCodeMirror::validateYamlFormCodeMirror in src/Element/YamlFormCodeMirror.php
Form element validation handler for #type 'yamlform_codemirror'.

File

src/Element/YamlFormCodeMirror.php, line 138

Class

YamlFormCodeMirror
Provides a form element for HTML, YAML, or Plain text using CodeMirror.

Namespace

Drupal\yamlform\Element

Code

protected static function getErrors(&$element, FormStateInterface $form_state, &$complete_form) {
  if (!empty($element['#skip_validation'])) {
    return NULL;
  }
  switch ($element['#mode']) {
    case 'html':

      // @see: http://stackoverflow.com/questions/3167074/which-function-in-php-validate-if-the-string-is-valid-html
      // @see: http://stackoverflow.com/questions/5030392/x-html-validator-in-php
      libxml_use_internal_errors(TRUE);
      if (simplexml_load_string('<fragment>' . $element['#value'] . '</fragment>')) {
        return NULL;
      }
      $errors = libxml_get_errors();
      libxml_clear_errors();
      if (!$errors) {
        return NULL;
      }
      $messages = [];
      foreach ($errors as $error) {
        $messages[] = $error->message;
      }
      return $messages;
    case 'yaml':
      try {
        $value = trim($element['#value']);
        $data = Yaml::decode($value);
        if (!is_array($data) && $value) {
          throw new \Exception(t('YAML must contain an associative array of elements.'));
        }
        return NULL;
      } catch (\Exception $exception) {
        return [
          $exception
            ->getMessage(),
        ];
      }
    default:
      return NULL;
  }
}