You are here

public function ImportController::__construct in Term CSV Export Import 8

Same name and namespace in other branches
  1. 8.3 src/Controller/ImportController.php \Drupal\term_csv_export_import\Controller\ImportController::__construct()
  2. 8.2 src/Controller/ImportController.php \Drupal\term_csv_export_import\Controller\ImportController::__construct()

File

src/Controller/ImportController.php, line 18

Class

ImportController
Class ImportController.

Namespace

Drupal\term_csv_export_import\Controller

Code

public function __construct($data, $vocabulary) {
  $this->vocabulary = $vocabulary;
  $temp = fopen('php://memory', 'rw');
  fwrite($temp, $data);
  rewind($temp);
  $csvArray = [];
  while (!feof($temp)) {
    if ($csvRow = fgetcsv($temp)) {
      $csvArray[] = $csvRow;
    }
  }
  fclose($temp);
  $keys_noid = [
    'name',
    'description__value',
    'description__format',
    'weight',
    'parent_name',
  ];
  $keys_id = [
    'tid',
    'uuid',
    'name',
    'description__value',
    'description__format',
    'weight',
    'parent_name',
    'parent_tid',
  ];
  $keys = [];
  if (!array_diff($keys_noid, $csvArray[0])) {
    drupal_set_message(t('The header keys were not included in the import.'), 'warning');
    $keys = $csvArray[0];
    unset($csvArray[0]);
  }
  foreach ($csvArray as $csvLine) {
    $num_of_lines = count($csvLine);
    if (empty($keys)) {
      if (in_array($num_of_lines, [
        8,
        9,
      ])) {
        $keys = $keys_id;
      }
      elseif (in_array($num_of_lines, [
        5,
        6,
      ])) {
        $keys = $keys_noid;
      }
      else {
        drupal_set_message(t('Line with "@part" could not be parsed. Incorrect number of values: @count.', [
          '@part' => implode(',', $csvLine),
          '@count' => count($csvLine),
        ]), 'error');
        continue;
      }
      if (in_array($num_of_lines, [
        6,
        9,
      ])) {
        $keys[] = 'fields';
      }
    }
    $this->data[] = array_combine($keys, $csvLine);
  }
}