You are here

public static function TransitionManager::validate in Lightning Scheduler 8

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 tests/src/Kernel/TransitionManagerTest.php
@covers ::validate

File

src/TransitionManager.php, line 90

Class

TransitionManager
@internal This is an internal part of Lightning Scheduler and may be changed or removed at any time without warning. It should not be used by external code in any way.

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;
  foreach ($data as $transition) {
    if (empty($transition['when'])) {
      $form_state
        ->setError($element, t('Scheduled transitions must have a date and time.'));
      return;
    }
    if (!preg_match('/^[0-9]+$/', $transition['when'])) {
      $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 (isset($minimum_date) && $transition['when'] < $minimum_date) {
      $variables = [
        '@date' => date('F j, Y', $minimum_date),
        '@time' => date('g:i A', $minimum_date),
      ];
      $form_state
        ->setError($element, t('You cannot schedule a transition to take place before @time on @date.', $variables));
      return;
    }
    $minimum_date = $transition['when'];
  }
}