You are here

public function ContactStorageExportForm::validateForm in Contact Storage Export 8

Form validation handler.

Parameters

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

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

Overrides FormBase::validateForm

File

src/Form/ContactStorageExportForm.php, line 180

Class

ContactStorageExportForm
Settings form for config devel.

Namespace

Drupal\contact_storage_export\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  $settings = $form_state
    ->getValues();

  // Check if there have been messages since the last export if since last
  // export setting is checked.
  if ($settings['since_last_export']) {
    $last_id = ContactStorageExport::getLastExportId($settings['contact_form']);
    if (!$this
      ->getSingleMessage($settings['contact_form'], $last_id)) {
      $message = $this
        ->t('There have been no new messages since the last export.');
      $form_state
        ->setErrorByName('since_last_export', $message);
    }
  }

  // Ensure filename is csv.
  $filaname_parts = explode('.', $settings['filename']);
  $extension = end($filaname_parts);
  if (strtolower($extension) != 'csv') {
    $message = $this
      ->t('The filename must end in ".csv"');
    $form_state
      ->setErrorByName('filename', $message);
  }

  // Validate filename for characters not well supported by php.
  // @see https://www.drupal.org/node/2472895 from Drupal 7.
  // Punctuation characters that are allowed, but not as first/last character.
  $punctuation = '-_. ';
  $map = [
    // Replace (groups of) whitespace characters.
    '!\\s+!' => ' ',
    // Replace multiple dots.
    '!\\.+!' => '.',
    // Remove characters that are not alphanumeric or the allowed punctuation.
    "![^0-9A-Za-z{$punctuation}]!" => '',
  ];
  $sanitised = preg_replace(array_keys($map), array_values($map), $settings['filename']);
  $sanitised = trim($sanitised, $punctuation);
  if ($sanitised != $settings['filename']) {
    $message = $this
      ->t('The filename should not have multiple whitespaces in a row, should not have multiple dots in a row, and should use only alphanumeric charcters.');
    $form_state
      ->setErrorByName('filename', $message);
  }
}