You are here

public static function TransitionManager::validate in Lightning Workflow 8.2

Same name and namespace in other branches
  1. 8.3 modules/lightning_scheduler/src/TransitionManager.php \Drupal\lightning_scheduler\TransitionManager::validate()

Validates incoming transition data.

Parameters

array $element: The form element.

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

See also

lightning_scheduler_form_alter()

1 call to TransitionManager::validate()
TransitionManagerTest::testValidate in modules/lightning_scheduler/tests/src/Kernel/TransitionManagerTest.php
@covers ::validate

File

modules/lightning_scheduler/src/TransitionManager.php, line 113

Class

TransitionManager

Namespace

Drupal\lightning_scheduler

Code

public static function validate(array $element, FormStateInterface $form_state) {
  $data = Json::decode($element['#value']);
  if (json_last_error() !== JSON_ERROR_NONE) {
    $variables = [
      '%error' => json_last_error_msg(),
    ];
    $form_state
      ->setError($element, t('Invalid transition data: %error', $variables));
    return;
  }
  if (!is_array($data)) {
    $form_state
      ->setError($element, t('Expected scheduled transitions to be an array.'));
    return;
  }
  $minimum_date = NULL;
  $format_options = [
    'timezone' => drupal_get_user_timezone(),
  ];
  foreach ($data as $transition) {
    if (empty($transition['when'])) {
      $form_state
        ->setError($element, t('Scheduled transitions must have a date and time.'));
      return;
    }
    $date_time = new DrupalDateTime($transition['when'], 'UTC');
    if ($date_time
      ->hasErrors()) {
      $variables = [
        '%when' => $transition['when'],
      ];
      $form_state
        ->setError($element, t('"%when" is not a valid date and time.', $variables));
      return;
    }

    // The transition must take place after $minimum_date.
    if ($minimum_date instanceof DrupalDateTime && $date_time
      ->getTimestamp() < $minimum_date
      ->getTimestamp()) {
      $variables = [
        '@date' => $minimum_date
          ->format('F j, Y', $format_options),
        '@time' => $minimum_date
          ->format('g:i A', $format_options),
      ];
      $form_state
        ->setError($element, t('You cannot schedule a transition to take place before @time on @date.', $variables));
      return;
    }
    $minimum_date = $date_time;
  }
}