Skip to content

Instantly share code, notes, and snippets.

@Unifex
Created June 18, 2018 21:23
Show Gist options
  • Save Unifex/46629d65ee3a36d3c1bd4598614ff67a to your computer and use it in GitHub Desktop.
Save Unifex/46629d65ee3a36d3c1bd4598614ff67a to your computer and use it in GitHub Desktop.
A Drupal 8 migration process plugin to to allow for fetching data from a CSV.
<?php
namespace Drupal\migrate_custom\Plugin\migrate\process;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
/**
* Load a CSV and return a col for a specific row.
*
* @MigrateProcessPlugin(
* id = "val_from_csv"
* )
*
* val_from_csv will allow you to load a csv into a keyed array of arrays and
* cache it. You can specify the column that the key is in and the column you
* want to return:
*
* @code
* process:
* type:
* field_extra_value:
* plugin: val_from_csv
* source: my_key_in_the_csv
* file: public:path/to/data.csv
* # Optional. Defaults to column 0
* key: int
* # Optional. Defaults to column 1
* val: int
*
* @endcode
*/
class ValueFromCsv extends ProcessPluginBase {
/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
// Which file are we reading from?
$file = $this->configuration['file'];
// What column is our key?
if (!$key_col = $this->configuration['key']) {
// Default to first col.
$key_col = 0;
}
// What column are we returning?
if (!$val_col = $this->configuration['val']) {
// Default to the second col.
$val_col = 1;
}
// Can we pull the data from a cache?
$cid = 'migrate:csv:' . preg_replace("/[^a-z0-9.]+/i", "", $file);
$data = NULL;
if ($cache = \Drupal::cache()
->get($cid)) {
$data = $cache->data;
}
else {
// Load the file as a csv.
$data = [];
if (($handle = fopen($file, "r")) !== FALSE) {
while (($row_data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[$row_data[$key_col]] = $row_data;
}
fclose($handle);
}
// Build the array as a keyed array.
ksort($data);
// Cache the $data.
\Drupal::cache()
->set($cid, $data);
}
if (!empty($data[$value])) {
// Return our val.
return $data[$value][$val_col];
}
else {
// No row for $value or the row doesn't have $val_col.
return NULL;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment