You are here

public function CSV::initializeIterator in Migrate Source CSV 8

Same name and namespace in other branches
  1. 8.3 src/Plugin/migrate/source/CSV.php \Drupal\migrate_source_csv\Plugin\migrate\source\CSV::initializeIterator()
  2. 8.2 src/Plugin/migrate/source/CSV.php \Drupal\migrate_source_csv\Plugin\migrate\source\CSV::initializeIterator()

Initializes the iterator with the source data.

Return value

\Iterator Returns an iteratable object of data for this source.

Overrides SourcePluginBase::initializeIterator

File

src/Plugin/migrate/source/CSV.php, line 74
Contains \Drupal\migrate_source_csv\Plugin\migrate\source\CSV.

Class

CSV
Source for CSV.

Namespace

Drupal\migrate_source_csv\Plugin\migrate\source

Code

public function initializeIterator() {

  // File handler using header-rows-respecting extension of SPLFileObject.
  $file = new CSVFileObject($this->configuration['path']);

  // Set basics of CSV behavior based on configuration.
  $delimiter = !empty($this->configuration['delimiter']) ? $this->configuration['delimiter'] : ',';
  $enclosure = !empty($this->configuration['enclosure']) ? $this->configuration['enclosure'] : '"';
  $escape = !empty($this->configuration['escape']) ? $this->configuration['escape'] : '\\';
  $file
    ->setCsvControl($delimiter, $enclosure, $escape);

  // Figure out what CSV column(s) to use. Use either the header row(s) or
  // explicitly provided column name(s).
  if (!empty($this->configuration['header_row_count'])) {
    $file
      ->setHeaderRowCount($this->configuration['header_row_count']);

    // Find the last header line.
    $file
      ->rewind();
    $file
      ->seek($file
      ->getHeaderRowCount() - 1);
    $row = $file
      ->current();
    foreach ($row as $header) {
      $header = trim($header);
      $column_names[] = [
        $header => $header,
      ];
    }
    $file
      ->setColumnNames($column_names);
  }

  // An explicit list of column name(s) will override any header row(s).
  if (!empty($this->configuration['column_names'])) {
    $file
      ->setColumnNames($this->configuration['column_names']);
  }
  return $file;
}