GoogleSheets.php in Migrate Google Sheets 2.x
File
src/Plugin/migrate_plus/data_parser/GoogleSheets.php
View source
<?php
namespace Drupal\migrate_google_sheets\Plugin\migrate_plus\data_parser;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate_plus\Plugin\migrate_plus\data_parser\Json;
use GuzzleHttp\Exception\RequestException;
class GoogleSheets extends Json implements ContainerFactoryPluginInterface {
protected $headers = [];
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
protected function getSourceData($url) {
try {
$response = $this
->getDataFetcherPlugin()
->getResponseContent($url);
$response = substr($response, 47, strlen($response) - 47 - 2);
$array = json_decode($response, TRUE);
if (isset($array['table']) && isset($array['table']['rows'])) {
if (isset($array['table']['cols']) && $array['table']['parsedNumHeaders'] > 0) {
$columns = array_column($array['table']['cols'], 'label');
}
else {
$first_row = array_shift($array['table']['rows']);
$columns = array_column($first_row['c'], 'v');
}
$this->headers = array_map(function ($col) {
return strtolower($col);
}, $columns);
$array = $array['table']['rows'];
}
else {
$array = [];
}
return $array;
} catch (RequestException $e) {
throw new MigrateException($e
->getMessage(), $e
->getCode(), $e);
}
}
protected function fetchNextRow() {
$current = $this->iterator
->current();
if ($current) {
foreach ($this
->fieldSelectors() as $field_name => $selector) {
$column_index = array_search(strtolower($selector), $this->headers);
if ($column_index >= 0) {
$this->currentItem[$field_name] = $current['c'][$column_index]['v'];
}
else {
$this->currentItem[$field_name] = NULL;
}
}
$this->iterator
->next();
}
}
}