You are here

public static function ChartDataCollectorTable::importCsvToTableSubmit in Charts 8.4

Same name and namespace in other branches
  1. 5.0.x src/Element/ChartDataCollectorTable.php \Drupal\charts\Element\ChartDataCollectorTable::importCsvToTableSubmit()

Submit callback for table csv import operations.

File

src/Element/ChartDataCollectorTable.php, line 417

Class

ChartDataCollectorTable
Provides a chart data collector table form element.

Namespace

Drupal\charts\Element

Code

public static function importCsvToTableSubmit(array $form, FormStateInterface $form_state) {
  $triggering_element = $form_state
    ->getTriggeringElement();
  $element_parents = array_slice($triggering_element['#parents'], 0, -2);
  $id_prefix = implode('-', $element_parents);
  $files = \Drupal::request()->files
    ->get('files');

  /** @var  \Symfony\Component\HttpFoundation\File\UploadedFile $file_upload */
  $file_upload = $files[$id_prefix];
  if (!ini_get("auto_detect_line_endings")) {
    ini_set("auto_detect_line_endings", '1');
  }
  $handle = $file_upload ? fopen($file_upload
    ->getPathname(), 'r') : NULL;
  if ($handle) {

    // Checking the encoding of the CSV file to be UTF-8.
    $encoding = 'UTF-8';
    if (function_exists('mb_detect_encoding')) {
      $file_contents = file_get_contents($file_upload
        ->getPathname());
      $encodings = [
        'UTF-8',
        'ISO-8859-1',
        'WINDOWS-1251',
      ];
      $encodings_list = implode(',', $encodings);
      $encoding = mb_detect_encoding($file_contents, $encodings_list);
    }

    // Populate CSV values.
    $rows_count = 0;
    $element_state = [];
    $separator = $triggering_element['#csv_separator'];
    while ($row = fgetcsv($handle, 0, $separator)) {
      foreach ($row as $column_value) {
        $element_state['data_collector_table'][$rows_count][] = [
          'data' => self::convertEncoding($column_value, $encoding),
        ];
      }
      $rows_count++;
    }
    fclose($handle);
    \Drupal::messenger()
      ->addMessage(t('Successfully imported @file', [
      '@file' => $file_upload
        ->getClientOriginalName(),
    ]));

    // Updating form state storage.
    self::setElementState($element_parents, $form_state, $element_state);

    // Making sure that the user input is updated as well.
    $input = $form_state
      ->getUserInput();
    NestedArray::setValue($input, $element_parents, $element_state);
    $form_state
      ->setUserInput($input);
  }
  else {
    \Drupal::messenger()
      ->addError(t('There was a problem importing the provided file data.'));
  }
  $form_state
    ->setRebuild();
}