CSV.php 5.06 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\migrate_source_csv\Plugin\migrate\source;

5 6
use Drupal\Component\Plugin\ConfigurablePluginInterface;
use Drupal\Component\Utility\NestedArray;
7 8
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
9
use Drupal\migrate\Plugin\MigrationInterface;
10 11 12 13 14 15 16 17 18 19 20

/**
 * Source for CSV.
 *
 * If the CSV file contains non-ASCII characters, make sure it includes a
 * UTF BOM (Byte Order Marker) so they are interpreted correctly.
 *
 * @MigrateSource(
 *   id = "csv"
 * )
 */
21
class CSV extends SourcePluginBase implements ConfigurablePluginInterface {
22 23 24 25 26 27 28 29 30

  /**
   * List of available source fields.
   *
   * Keys are the field machine names as used in field mappings, values are
   * descriptions.
   *
   * @var array
   */
31
  protected $fields = [];
32 33 34 35 36 37

  /**
   * List of key fields, as indexes.
   *
   * @var array
   */
38
  protected $keys = [];
39

40 41 42 43 44 45 46 47 48 49 50 51 52 53
  /**
   * The file class to read the file.
   *
   * @var string
   */
  protected $fileClass = '';

  /**
   * The file object that reads the CSV file.
   *
   * @var \SplFileObject
   */
  protected $file = NULL;

54 55 56 57 58
  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
59
    $this->setConfiguration($configuration);
60 61

    // Path is required.
62
    if (empty($this->getConfiguration()['path'])) {
63 64 65 66
      throw new MigrateException('You must declare the "path" to the source CSV file in your source settings.');
    }

    // Key field(s) are required.
67
    if (empty($this->getConfiguration()['keys'])) {
68 69 70
      throw new MigrateException('You must declare "keys" as a unique array of fields in your source settings.');
    }

71
    $this->fileClass = $this->getConfiguration()['file_class'];
72 73 74
  }

  /**
75
   * Return a string representing the source file path.
76 77 78 79 80
   *
   * @return string
   *   The file path.
   */
  public function __toString() {
81
    return $this->getConfiguration()['path'];
82 83 84 85 86 87 88
  }

  /**
   * {@inheritdoc}
   */
  public function initializeIterator() {
    // File handler using header-rows-respecting extension of SPLFileObject.
89
    $this->file = new $this->fileClass($this->getConfiguration()['path']);
90 91

    // Set basics of CSV behavior based on configuration.
92 93 94
    $delimiter = $this->getConfiguration()['delimiter'];
    $enclosure = $this->getConfiguration()['enclosure'];
    $escape = $this->getConfiguration()['escape'];
95
    $this->file->setCsvControl($delimiter, $enclosure, $escape);
96
    $this->file->setFlags($this->getConfiguration()['file_flags']);
97 98 99

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

      // Find the last header line.
104 105
      $this->file->rewind();
      $this->file->seek($this->file->getHeaderRowCount() - 1);
106

107
      $row = $this->file->current();
108 109
      foreach ($row as $header) {
        $header = trim($header);
110
        $column_names[] = [$header => $header];
111
      }
112
      $this->file->setColumnNames($column_names);
113 114
    }
    // An explicit list of column name(s) will override any header row(s).
115 116
    if ($this->getConfiguration()['column_names']) {
      $this->file->setColumnNames($this->getConfiguration()['column_names']);
117 118
    }

119
    return $this->file;
120 121 122 123 124 125
  }

  /**
   * {@inheritdoc}
   */
  public function getIDs() {
126
    $ids = [];
127
    foreach ($this->getConfiguration()['keys'] as $delta => $value) {
128 129 130 131 132 133
      if (is_array($value)) {
        $ids[$delta] = $value;
      }
      else {
        $ids[$value]['type'] = 'string';
      }
134 135 136 137 138 139 140 141
    }
    return $ids;
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
142
    $fields = [];
143
    foreach ($this->getIterator()->getColumnNames() as $column) {
144
      $fields[key($column)] = reset($column);
145 146 147 148
    }

    // Any caller-specified fields with the same names as extracted fields will
    // override them; any others will be added.
149
    $fields = $this->getConfiguration()['fields'] + $fields;
150 151 152 153

    return $fields;
  }

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    // We must preserve integer keys for column_name mapping.
    $this->configuration = NestedArray::mergeDeepArray([$this->defaultConfiguration(), $configuration], TRUE);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'fields' => [],
      'keys' => [],
      'column_names' => [],
      'header_row_count' => 0,
      'file_flags' => \SplFileObject::READ_CSV | \SplFileObject::READ_AHEAD | \SplFileObject::DROP_NEW_LINE | \SplFileObject::SKIP_EMPTY,
      'delimiter' => ',',
      'enclosure' => '"',
      'escape' => '\\',
      'path' => '',
      'file_class' => 'Drupal\migrate_source_csv\CSVFileObject',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return [];
  }
193
}