You are here

public static function DateRecurModularUtilityTrait::buildDatesFromFields in Recurring Date Field Modular Widgets 2.x

Same name and namespace in other branches
  1. 8 src/DateRecurModularUtilityTrait.php \Drupal\date_recur_modular\DateRecurModularUtilityTrait::buildDatesFromFields()
  2. 3.x src/DateRecurModularUtilityTrait.php \Drupal\date_recur_modular\DateRecurModularUtilityTrait::buildDatesFromFields()

Build a datetime object by getting the date and time from two fields.

Parameters

array $dayField: Form path to the day field.

array $timeField: Form path to the time field.

string $timeZone: Time zone for the day.

\Drupal\Core\Form\FormStateInterface $formState: Form state object.

Return value

\DateTime A date object.

Throws

\Exception Exceptions thrown if input is invalid.

2 calls to DateRecurModularUtilityTrait::buildDatesFromFields()
DateRecurModularSierraWidget::transferStateToTempstore in src/Plugin/Field/FieldWidget/DateRecurModularSierraWidget.php
Transfers element state to tempstore ready for modal to consume.
DateRecurModularSierraWidget::validateModularWidget in src/Plugin/Field/FieldWidget/DateRecurModularSierraWidget.php
Validates the widget.

File

src/DateRecurModularUtilityTrait.php, line 40

Class

DateRecurModularUtilityTrait
Trait containing convenience methods for dealing with date recur widgets.

Namespace

Drupal\date_recur_modular

Code

public static function buildDatesFromFields(array $dayField, array $timeField, string $timeZone, FormStateInterface $formState) : \DateTime {
  $tz = new \DateTimeZone($timeZone);
  $completeForm = $formState
    ->getCompleteForm();
  $fieldA = NestedArray::getValue($completeForm, $dayField);
  $fieldB = NestedArray::getValue($completeForm, $timeField);
  assert($fieldA['#type'] === 'date');
  assert($fieldB['#type'] === 'date' && $fieldB['#attributes']['type'] === 'time');
  $valueA = $formState
    ->getValue($fieldA['#parents']);
  $valueB = $formState
    ->getValue($fieldB['#parents']);

  // Create base day object.
  $baseDay = \DateTime::createFromFormat('Y-m-d', $valueA, $tz);
  if (!$baseDay) {
    throw new \Exception('Input for date is invalid.');
  }
  $baseDay
    ->setTime(0, 0, 0);
  $baseDayParts = explode('-', $baseDay
    ->format('Y-n-j'));
  $baseDayParts = array_map('intval', $baseDayParts);

  // Fix the time. HTML element allows omitting seconds.
  if (!empty($valueB) && strlen($valueB) == 5) {
    $valueB .= ':00';
  }
  $time = \DateTime::createFromFormat('H:i:s', $valueB, $tz);
  if (!$time) {
    throw new \Exception('Input for time is invalid.');
  }
  $time
    ->setDate(...$baseDayParts);
  return $time;
}