Spreadsheet.php 6.87 KB
Newer Older
1 2 3 4 5 6
<?php

namespace Drupal\migrate_spreadsheet\Plugin\migrate\source;

use Drupal\Component\Plugin\ConfigurablePluginInterface;
use Drupal\Component\Utility\NestedArray;
7 8
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
9 10 11
use Drupal\migrate\MigrateException;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use Drupal\migrate\Plugin\MigrationInterface;
12
use Drupal\migrate_spreadsheet\SpreadsheetIterator;
13
use Drupal\migrate_spreadsheet\SpreadsheetIteratorInterface;
14
use PhpOffice\PhpSpreadsheet\IOFactory;
15
use Symfony\Component\DependencyInjection\ContainerInterface;
16 17 18 19 20 21 22 23 24 25 26

/**
 * Provides a source plugin that migrate from spreadsheet files.
 *
 * This source plugin uses the PhpOffice/PhpSpreadsheet library to read
 * spreadsheet files.
 *
 * @MigrateSource(
 *   id = "spreadsheet"
 * )
 */
27 28 29 30 31 32 33 34
class Spreadsheet extends SourcePluginBase implements ConfigurablePluginInterface, ContainerFactoryPluginInterface {

  /**
   * The file system service.
   *
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;
35

36 37 38 39 40 41 42 43 44 45 46 47 48 49
  /**
   * The migrate spreadsheet iterator.
   *
   * @var \Drupal\migrate_spreadsheet\SpreadsheetIteratorInterface
   */
  protected $spreadsheetIterator;

  /**
   * Flag to determine if the iterator has been initialized.
   *
   * @var bool
   */
  protected $iteratorIsInitialized = FALSE;

50 51 52 53 54 55 56 57 58
  /**
   * Constructs a spreadsheet migration source plugin object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
59
   * @param \Drupal\migrate\Plugin\MigrationInterface $migration
60
   *   The current migration.
61 62
   * @param \Drupal\Core\File\FileSystemInterface $file_system
   *   The file system service.
63 64
   * @param \Drupal\migrate_spreadsheet\SpreadsheetIteratorInterface $spreadsheet_iterator
   *   The migrate spreadsheet iterator.
65
   */
66
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration, FileSystemInterface $file_system, SpreadsheetIteratorInterface $spreadsheet_iterator) {
67 68
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
    $this->setConfiguration($configuration);
69
    $this->fileSystem = $file_system;
70
    $this->spreadsheetIterator = $spreadsheet_iterator;
71 72 73 74 75 76 77 78 79 80 81
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration = NULL) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $migration,
82
      $container->get('file_system'),
83
      new SpreadsheetIterator()
84
    );
85 86 87 88 89 90 91 92 93
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'file' => NULL,
      'worksheet' => NULL,
94
      'origin' => 'A2',
95
      'header_row' => NULL,
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
      'columns' => [],
      'keys' => [],
      'row_index_column' => NULL,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    $this->configuration = NestedArray::mergeDeep(
      $this->defaultConfiguration(),
      $configuration
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function __toString() {
    return $this->configuration['file'] . ':' . $this->configuration['worksheet'];
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $config = $this->getConfiguration();

    if (empty($config['keys'])) {
      if (empty($config['row_index_column'])) {
        throw new \RuntimeException("Row index should act as key but no name has been provided. Set 'row_index_column' in source config to provide a name for this column.");
      }
      // If no keys are defined, we'll use the 'zero based' index of the
      // spreadsheet current row.
      return [$config['row_index_column'] => ['type' => 'integer']];
    }

141
    return $config['keys'];
142 143 144 145 146 147
  }

  /**
   * {@inheritdoc}
   */
  public function fields() {
148 149 150 151 152 153 154
    // No column headers provided in config, read worksheet for header row.
    if (!$columns = $this->getConfiguration()['columns']) {
      $this->initializeIterator();
      $columns = array_keys($this->spreadsheetIterator->getHeaders());
    }
    // Add $row_index_column if it's been configured.
    if ($row_index_column = $this->getConfiguration()['row_index_column']) {
155 156
      $columns[] = $row_index_column;
    }
157 158 159 160 161 162 163
    return array_combine($columns, $columns);
  }

  /**
   * {@inheritdoc}
   */
  public function initializeIterator() {
164 165 166 167 168 169 170 171 172 173 174 175 176 177
    if (!$this->iteratorIsInitialized) {
      $configuration = $this->getConfiguration();
      $configuration['worksheet'] = $this->loadWorksheet();
      $configuration['keys'] = array_keys($configuration['keys']);

      // The 'file' and 'plugin' items are not part of iterator configuration.
      unset($configuration['file'], $configuration['plugin']);
      $this->spreadsheetIterator->setConfiguration($configuration);

      // Flag that the iterator has been initialized.
      $this->iteratorIsInitialized = TRUE;
    }

    return $this->spreadsheetIterator;
178 179 180 181 182
  }

  /**
   * Loads the worksheet.
   *
183
   * @return \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
   *   The source worksheet.
   *
   * @throws \Drupal\migrate\MigrateException
   *   When it's impossible to load the file or the worksheet does not exist.
   */
  protected function loadWorksheet() {
    $config = $this->getConfiguration();

    // Check that the file exists.
    if (!file_exists($config['file'])) {
      throw new MigrateException("File with path '{$config['file']}' doesn't exist.");
    }

    // Check that a non-empty worksheet has been passed.
    if (empty($config['worksheet'])) {
      throw new MigrateException('No worksheet was passed.');
    }

    // Load the workbook.
    try {
204 205
      $file_path = $this->fileSystem->realpath($config['file']);

206
      // Identify the type of the input file.
207
      $type = IOFactory::identify($file_path);
208 209 210 211 212 213 214 215 216 217 218 219

      // Create a new Reader of the file type.
      /** @var \PhpOffice\PhpSpreadsheet\Reader\BaseReader $reader */
      $reader = IOFactory::createReader($type);

      // Advise the Reader that we only want to load cell data.
      $reader->setReadDataOnly(TRUE);

      // Advise the Reader of which worksheet we want to load.
      $reader->setLoadSheetsOnly($config['worksheet']);

      /** @var \PhpOffice\PhpSpreadsheet\Spreadsheet $workbook */
220
      $workbook = $reader->load($file_path);
221

222
      return $workbook->getSheet(0);
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    }
    catch (\Exception $e) {
      $class = get_class($e);
      throw new MigrateException("Got '$class', message '{$e->getMessage()}'.");
    }
  }

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

}