CSV.php in Migrate Source CSV 8
File
src/Plugin/migrate/source/CSV.php
View source
<?php
namespace Drupal\migrate_source_csv\Plugin\migrate\source;
use Drupal\migrate\Entity\MigrationInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use Drupal\migrate_source_csv\CSVFileObject;
class CSV extends SourcePluginBase {
protected $fields = [];
protected $keys = [];
public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
if (empty($this->configuration['path'])) {
throw new MigrateException('You must declare the "path" to the source CSV file in your source settings.');
}
if (empty($this->configuration['keys'])) {
throw new MigrateException('You must declare "keys" as a unique array of fields in your source settings.');
}
}
public function __toString() {
return $this->configuration['path'];
}
public function initializeIterator() {
$file = new CSVFileObject($this->configuration['path']);
$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);
if (!empty($this->configuration['header_row_count'])) {
$file
->setHeaderRowCount($this->configuration['header_row_count']);
$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);
}
if (!empty($this->configuration['column_names'])) {
$file
->setColumnNames($this->configuration['column_names']);
}
return $file;
}
public function getIDs() {
$ids = [];
foreach ($this->configuration['keys'] as $key) {
$ids[$key]['type'] = 'string';
}
return $ids;
}
public function fields() {
$fields = [];
foreach ($this
->getIterator()
->getColumnNames() as $column) {
$fields[key($column)] = reset($column);
}
if (!empty($this->configuration['fields'])) {
$fields = $this->configuration['fields'] + $fields;
}
return $fields;
}
}
Classes
Name |
Description |
CSV |
Source for CSV. |