You are here

public function CSVUpdateForm::submitForm in Commerce Smart Importer 8

Form submit.

Overrides FormInterface::submitForm

File

src/Form/CSVUpdateForm.php, line 174

Class

CSVUpdateForm
Class CSVUpdateForm.

Namespace

Drupal\commerce_smart_importer\Form

Code

public function submitForm(array &$form, FormStateInterface $form_state) {
  $action = $_GET['action'];
  if ($action == 'check') {
    $fid = $form_state
      ->getValue('csv_file')[0];
    $file = $this->entityTypeManager
      ->getStorage('file')
      ->load($fid);
    $uri = $file
      ->getFileUri();
    $importing_parameters = new ImportingParameters();
    $importing_parameters
      ->disableAll();
    $external_folders = [
      CommerceSmartImporterConstants::TEMP_DIR . '/',
    ];
  }
  if ($action == 'load') {
    $uri = CommerceSmartImporterConstants::TEMP_DIR . '/' . $_GET['import_name'] . '/products.csv';
    $external_folders = [
      CommerceSmartImporterConstants::TEMP_DIR . '/' . $_GET['import_name'],
    ];
    $importing_parameters = new ImportingParameters();
    $importing_parameters->incorrectValues = FALSE;
    $importing_parameters->defaultValues = FALSE;
    $importing_parameters->exceedsCardinality = FALSE;
    $importing_parameters->duplicateValues = FALSE;
    if ($form_state
      ->getValue('image_action') == 0) {
      $importing_parameters->appendImages = FALSE;
    }
  }
  $config = $this->smartImporterService
    ->getConfig();
  $external_folders = array_merge($external_folders, $config['external_folders']);

  // Read CSV.
  $csvData = fopen($uri, 'r');
  $headers = fgetcsv($csvData, 1024);

  // Empty that extra line.
  fgetcsv($csvData, 1024);
  fclose($csvData);
  foreach ($headers as $key => $header) {
    if (mb_detect_encoding($header) == 'UTF-8') {
      $headers[$key] = mb_convert_encoding(trim($header), 'ASCII');
      $headers[$key] = str_replace('?', '', $headers[$key]);
    }
    else {
      $headers[$key] = trim($header);
    }
  }

  // Indexing labels.
  $fields = $this->smartImporterService
    ->getFieldDefinition(TRUE);
  foreach ($headers as $index => $header) {
    foreach ($fields['product'] as $key => $field) {
      if ($field['label'] == $header) {
        $fields['product'][$key]['index'] = $index;
      }
    }
    foreach ($fields['variation'] as $key => $field) {
      if ($field['label'] == $header) {
        $fields['variation'][$key]['index'] = $index;
      }
    }
  }
  foreach ($fields['product'] as $key => $field) {
    if (!array_key_exists('index', $field)) {
      unset($fields['product'][$key]);
    }
  }
  foreach ($fields['variation'] as $key => $field) {
    if (!array_key_exists('index', $field)) {
      unset($fields['variation'][$key]);
    }
  }
  if (count($fields['variation']) > 0) {
    $variation_has_identifier = $this
      ->hasIdentifier($fields, 'variation');
  }
  else {
    $variation_has_identifier = TRUE;
  }
  if ($variation_has_identifier && count($fields['variation']) > 0) {
    $product_has_identifier = TRUE;
  }
  elseif (count($fields['product']) > 0) {
    $product_has_identifier = $this
      ->hasIdentifier($fields, 'product');
  }
  else {
    $product_has_identifier = TRUE;
  }
  if ($product_has_identifier === FALSE) {
    $this
      ->messenger()
      ->addError($this
      ->t('Product has no identifier, and cannot be identified'));
  }
  if ($variation_has_identifier === FALSE) {
    $this
      ->messenger()
      ->addError($this
      ->t('Variation has no identifier, and cannot be identified'));
  }
  if (!$variation_has_identifier && !$product_has_identifier) {
    return;
  }
  $count = $this->smartImporterService
    ->countProductsAndVariations($uri);
  $products_per_batch = 25;
  $number_of_batches = ceil($count['variation_count'] / $products_per_batch);
  if ($action == 'check') {
    $upload_name = uniqid('Smart_Importer_temp_');
    if (!is_dir(CommerceSmartImporterConstants::TEMP_DIR . '/')) {
      mkdir(CommerceSmartImporterConstants::TEMP_DIR . '/');
    }
    mkdir(CommerceSmartImporterConstants::TEMP_DIR . '/' . $upload_name);
    $save = CommerceSmartImporterConstants::TEMP_DIR . '/' . $upload_name;
    $this->smartImporterService
      ->changeFilePathInFieldDefinition($fields, CommerceSmartImporterConstants::TEMP_DIR . '/' . $upload_name);
    if (!copy($uri, $save . '/products.csv')) {
      throw new Exception('Could not save file to temp folder');
    }
  }
  elseif ($action == 'load') {
    $save = CommerceSmartImporterConstants::TEMP_DIR . '/' . $_GET['import_name'];
  }

  // Making batch.
  $batch = [
    'title' => $this
      ->t('Updating all products'),
    'init_message' => $this
      ->t('Beginning...'),
    'progress_message' => $this
      ->t('Checked @current out of @total product groups'),
    'error_message' => $this
      ->t('Something went wrong'),
    'finished' => [
      $this,
      'finished',
    ],
    'progressive' => FALSE,
    'operations' => [],
  ];
  if ($action == 'check') {
    $batch['finished'] = [
      $this,
      'finished',
    ];
  }
  if ($action == 'load') {
    $batch['finished'] = [
      $this,
      'finishedImporting',
    ];
  }
  for ($i = 0; $i < $number_of_batches; $i++) {
    $batch['operations'][] = [
      [
        $this,
        'readCsvProductsToUpdate',
      ],
      [
        $uri,
        $fields,
        25,
        $importing_parameters,
        $external_folders,
        $save,
      ],
    ];
  }
  batch_set($batch);
}