You are here

public function CSVOfficeHoursField::transform in Office Hours 8

Performs the associated process.

Parameters

mixed $value: The value to be transformed.

\Drupal\migrate\MigrateExecutableInterface $migrate_executable: The migration in which this process is being executed.

\Drupal\migrate\Row $row: The row from the source to process. Normally, just transforming the value is adequate but very rarely you might need to change two columns at the same time or something like that.

string $destination_property: The destination property currently worked on. This is only used together with the $row above.

Return value

string|array The newly transformed value.

Overrides OfficeHoursField::transform

File

src/Plugin/migrate/process/CSVOfficeHoursField.php, line 101

Class

CSVOfficeHoursField
Processes a input array of office hours to the correct format for the field.

Namespace

Drupal\office_hours\Plugin\migrate\process

Code

public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
  if (!is_array($value)) {
    throw new MigrateException(sprintf('%s is not an array', var_export($value, TRUE)));
  }
  $slots_per_day = isset($this->configuration['slots_per_day']) ? $this->configuration['slots_per_day'] : 1;
  $delimiter = isset($this->configuration['delimiter']) ? $this->configuration['delimiter'] : '-';
  $has_comment = isset($this->configuration['comment']) ? $this->configuration['comment'] : FALSE;
  if (count($value) !== $slots_per_day * ($has_comment ? 2 : 1) * 7) {
    throw new MigrateException(sprintf('%s does not have the correct size', var_export($value, TRUE)));
  }
  $office_hours = [];
  for ($i = 0; $i < count($value); $i++) {
    if (!$has_comment || $i % 2 === 0) {

      // Process Hours.
      $time = explode($delimiter, trim($value[$i]));
      $office_hours[] = [
        'day' => floor($i / $slots_per_day / ($has_comment ? 2 : 1)),
        'starthours' => str_replace(':', '', $time[0]),
        'endhours' => str_replace(':', '', $time[1]),
        'comment' => '',
      ];
    }
    else {
      $comment_key = ($i - 1) / 2;
      $item =& $office_hours[$comment_key];
      $item['comment'] = trim($value[$i]);

      // Override empty values because it is not well handled if there
      // is a comment associated with a day. But if there is no comment
      // it has to be empty.
      if (!empty($item['comment'])) {
        $item['starthours'] = empty($item['starthours']) ? -1 : $item['starthours'];
        $item['endhours'] = empty($item['endhours']) ? -1 : $item['endhours'];
      }
    }
  }
  return $office_hours;
}