You are here

public function IntervalsForm::validateIntervals in Subscriptions 2.0.x

Element validation callback.

File

src/Form/IntervalsForm.php, line 50

Class

IntervalsForm
Defines the intervals settings form.

Namespace

Drupal\subscriptions\Form

Code

public function validateIntervals($element, FormStateInterface $form_state, $form) {

  // Get the form value.
  $intervals = explode("\n", $form_state
    ->cleanValues()
    ->getValue('intervals', ''));
  $intervals = array_filter($intervals);

  // Regex for matching seconds|label values.
  $pattern = '/^([0-9]+)\\|(.+)$/';
  $errors = [];

  // Check each line individually.
  foreach ($intervals as &$interval) {

    // Trim whitespace off of each line.
    $interval = trim($interval);
    if (empty($interval)) {
      continue;
    }
    $match = preg_match($pattern, $interval);

    // If the line did not match the regex, add it as an error.
    if ($match != TRUE) {
      $errors[] = $interval;
    }
  }

  // If any errors built up, set an error message.
  if (!empty($errors)) {
    $error_message = $this
      ->formatPlural(count($errors), 'Invalid format: @interval', 'Invalid formats: @interval', [
      '@interval' => implode(', ', $errors),
    ]);
    $form_state
      ->setError($element, $error_message);
  }

  // Clean up the final value and set it back in the form state.
  $intervals = array_values(array_filter($intervals));
  $form_state
    ->setValueForElement($element, implode("\n", $intervals));
}