You are here

public function CivicrmEntity::civicrmApiNormalize in CiviCRM Entity 8.3

1 call to CivicrmEntity::civicrmApiNormalize()
CivicrmEntity::validate in src/Entity/CivicrmEntity.php
Validates the currently set values.

File

src/Entity/CivicrmEntity.php, line 183

Class

CivicrmEntity
Entity class for CiviCRM entities.

Namespace

Drupal\civicrm_entity\Entity

Code

public function civicrmApiNormalize() {
  $params = [];

  /** @var \Drupal\Core\Field\FieldItemListInterface $items */
  foreach ($this
    ->getFields() as $field_name => $items) {
    $items
      ->filterEmptyItems();
    if ($items
      ->isEmpty()) {
      continue;
    }
    $storage_definition = $items
      ->getFieldDefinition()
      ->getFieldStorageDefinition();
    if (!$storage_definition
      ->isBaseField()) {

      // Do not try to pass any FieldConfig (or else) to CiviCRM API.
      continue;
    }
    $main_property_name = $storage_definition
      ->getMainPropertyName();
    $list = [];

    /** @var \Drupal\Core\Field\FieldItemInterface $item */
    foreach ($items as $delta => $item) {
      $main_property = $item
        ->get($main_property_name);
      if ($main_property instanceof DateTimeIso8601 && !is_array($main_property
        ->getValue())) {

        // CiviCRM wants the datetime in the timezone of the user, but Drupal
        // stores it in UTC.
        $value = (new \DateTime($main_property
          ->getValue(), new \DateTimeZone('UTC')))
          ->setTimezone(new \DateTimeZone(date_default_timezone_get()))
          ->format('Y-m-d H:i:s');
      }
      else {
        $value = $main_property
          ->getValue();
      }
      $list[$delta] = $value;
    }

    // Remove the wrapping array if the field is single-valued.
    if ($storage_definition
      ->getCardinality() === 1) {
      $list = reset($list);
    }
    if (!empty($list)) {
      $params[$field_name] = $list;
    }
  }
  return $params;
}