You are here

protected function DateRecurOccurrences::saveItem in Recurring Dates Field 8.2

Same name and namespace in other branches
  1. 3.x src/DateRecurOccurrences.php \Drupal\date_recur\DateRecurOccurrences::saveItem()
  2. 3.0.x src/DateRecurOccurrences.php \Drupal\date_recur\DateRecurOccurrences::saveItem()
  3. 3.1.x src/DateRecurOccurrences.php \Drupal\date_recur\DateRecurOccurrences::saveItem()

Create table rows from occurrences for a single field value.

Parameters

\Drupal\date_recur\Plugin\Field\FieldType\DateRecurItem $item: Date recur field item.

string $tableName: The name of table to store occurrences.

1 call to DateRecurOccurrences::saveItem()
DateRecurOccurrences::onSave in src/DateRecurOccurrences.php
Respond to a field value insertion or update.

File

src/DateRecurOccurrences.php, line 124

Class

DateRecurOccurrences
Manages occurrences tables and the data that populates them.

Namespace

Drupal\date_recur

Code

protected function saveItem(DateRecurItem $item, string $tableName) : void {

  // Type suggested, see https://www.drupal.org/project/drupal/issues/3094067.

  /** @var string|int $fieldDelta */
  $fieldDelta = $item
    ->getName();
  assert(is_int($fieldDelta));
  $fieldName = $item
    ->getFieldDefinition()
    ->getName();
  $entity = $item
    ->getEntity();
  $fields = [
    'entity_id',
    'field_delta',
    'delta',
    $fieldName . '_value',
    $fieldName . '_end_value',
  ];
  $baseRow = [
    'entity_id' => $entity
      ->id(),
    'field_delta' => $fieldDelta,
  ];
  if ($entity
    ->getEntityType()
    ->isRevisionable() && $entity instanceof RevisionableInterface) {
    $fields[] = 'revision_id';
    $baseRow['revision_id'] = $entity
      ->getRevisionId();
  }
  $occurrences = $this
    ->getOccurrencesForCacheStorage($item);
  $rows = array_map(function (DateRange $occurrence, $delta) use ($baseRow, $fieldName, $item) : array {
    $row = $baseRow;
    $row['delta'] = $delta;
    $row[$fieldName . '_value'] = $this
      ->massageDateValueForStorage($occurrence
      ->getStart(), $item);
    $row[$fieldName . '_end_value'] = $this
      ->massageDateValueForStorage($occurrence
      ->getEnd(), $item);
    return $row;
  }, $occurrences, array_keys($occurrences));
  $insert = $this->database
    ->insert($tableName)
    ->fields($fields);
  foreach ($rows as $row) {
    $insert
      ->values($row);
  }
  $insert
    ->execute();
}