content_csv_export_import-1.0.1-beta2/src/ContentExportImportCoreService.php

src/ContentExportImportCoreService.php
<?php

namespace Drupal\content_csv_export_import;

use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Entity\EntityFieldManager;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\commerce_price\Entity\Currency;
use Drupal\Core\Utility\Token;
use Drupal\taxonomy\Entity\Term;
use Masterminds\HTML5\Exception;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\Core\Controller\ControllerBase;
use Drupal\field\Entity\FieldConfig;
use Drupal\Core\Field\BaseFieldDefinition;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Config\ConfigFactory;
use Drupal\physical\Weight;
use Drupal\physical\WeightUnit;
use Drupal\physical\Area;
use Drupal\physical\AreaUnit;
use Drupal\physical\Length;
use Drupal\commerce_product\Entity\ProductAttributeValue;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\physical\LengthUnit;
use Drupal\physical\Volume;
use Drupal\physical\VolumeUnit;
use Drupal\Core\Entity\EntityTypeBundleInfo;
use Drupal\redirect\Entity\Redirect;
use Drupal\commerce_price\Price;
use Drupal\paragraphs\Entity\Paragraph;
use Drupal\node\Entity\Node;
use Drupal\field\Entity\FieldStorageConfig;

/**
 * Class ContentExportImportCoreService.
 */
class ContentExportImportCoreService extends ControllerBase {

  use DependencySerializationTrait;

  /**
   * Database service.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * Token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
   * Entity field manager service.
   *
   * @var \Drupal\Core\Entity\EntityFieldManager
   */
  protected $entityFieldManager;

  /**
   * Config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactoryService;

  /**
   * The entity type bundle info.
   *
   * @var \Drupal\Core\Entity\EntityTypeBundleInfo
   */
  protected $entityTypeBundleInfo;

  /**
   * CommerceSmartImporerService constructor.
   */
  public function __construct(Connection $connection,
                              Token $token,
                              EntityFieldManager $entityFieldManager,
                              ConfigFactory $configFactory,
                              EntityTypeBundleInfo $entityTypeBundleInfo) {
    $this->database = $connection;
    $this->token = $token;
    $this->entityFieldManager = $entityFieldManager;
    $this->configFactory = $configFactory;
    $this->entityTypeBundleInfo = $entityTypeBundleInfo;
  }

  /**
   * Create.
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('database'),
      $container->get('token'),
      $container->get('entity_field.manager'),
      $container->get('config.factory'),
      $container->get('entity_type.bundle.info')
    );
  }

  /**
   * Formats one field value based on field settings.
   */
  public function formatField($field, $product, $folders, $create_mode) {
    $exception = FALSE;
    $product = trim($product);
    $create = '';
    switch (trim($field['field_types'])) {
      case 'text':
      case 'fivestar':
      case 'string':
        try {
          $create = $this->createString($product, $field['field_settings']);
          if ($field['machine_names'] == 'sku') {
            $create = $this->createSku($create, $field['field_settings']);
          }
        }
        catch (Exception $e) {
          $create = $e->getMessage();
          $exception = TRUE;
        }
        break;

      case 'text_long':
        $create = $this->createTextSummary($product, $field['field_settings']);
        break;

      case 'string_long':
      case 'text_with_summary':
        $create = $this->createTextSummary($product, $field['field_settings']);
        break;

      case 'integer':
        $create = $this->createInteger($product, $field['field_settings']);
        break;

      case 'float':
      case 'decimal':
        $create = $this->createDecimal($product, $field['field_settings']);
        break;

      case 'image':
      case 'file':
        $create = $this->createFile($product, $field['field_settings'], $folders, $create_mode, $field['field_types']);
        break;

      case 'commerce_price':
        $product = explode(' ', $product);

        if (!array_key_exists(1, $product)) {
          if (is_numeric($product[0])) {
            $product[1] = 'ZAR';
          }
          else {
            throw new Exception('No price');
          }
        }
        if (is_numeric(trim($product[0]))) {
          $create = new Price(trim($product[0]), trim($product[1]));
        }
        else {
          $create = 'Price for one variation of ' . $field['label'] . ' is not number!';
          $exception = TRUE;
        }
        break;

      case 'list_float':
      case 'list_string':
      case 'list_integer':
        $create = $this->createList($product, $field['field_settings']);
        break;

      case 'timestamp':
        $create = $this->createTimestamp($product, $field['field_settings']);
        break;

      case 'email':
        try {
          $create = $this->createEmail($product, $field['field_settings']);
        }
        catch (Exception $e) {
          $create = $e->getMessage();
          $exception = TRUE;
        }
        break;

      case 'link':
        try {
          $create = $this->createUrl($product, $field['field_settings']);
        }
        catch (Exception $e) {
          $create = $e->getMessage();
          $exception = TRUE;
        }
        break;

      case 'path':
        try {
          $create = $this->createPath($product, $field['field_settings']);
        }
        catch (Exception $e) {
          $create = $e->getMessage();
          $exception = TRUE;
        }
        break;

      case 'boolean':
        if ($field['machine_names'] == 'status') {
          $create = (bool) $product;
        }
        else {
          $create = $this->createBool($product, $field['field_settings']);
        }
        break;

      case 'physical_dimensions':
        try {
          $create = $this->createPhysicalDimension($product, $field['field_settings']);
        }
        catch (Exception $e) {
          $create = $e->getMessage();
          $exception = TRUE;
        }
        break;

      case 'physical_measurement':
        switch ($field['field_settings']['measurement_type']) {
          case 'weight':
            try {
              $create = $this->createPhysicalMesurementWeight($product, $field['field_settings']);
            }
            catch (Exception $e) {
              $create = $e->getMessage();
              $exception = TRUE;
            }
            break;

          case 'area':
            try {
              $create = $this->createPhysicalMesurementArea($product, $field['field_settings']);
            }
            catch (Exception $e) {
              $create = $e->getMessage();
              $exception = TRUE;
            }
            break;

          case 'length':
            try {
              $create = $this->createPhysicalMesurementLength($product, $field['field_settings']);
            }
            catch (Exception $e) {
              $create = $e->getMessage();
              $exception = TRUE;
            }
            break;

          case 'volume':
            try {
              $create = $this->createPhysicalMesurementVolume($product, $field['field_settings']);
            }
            catch (Exception $e) {
              $create = $e->getMessage();
              $exception = TRUE;
            }
            break;
        }
        break;

      case 'entity_reference':
        if ($field['machine_names'] != 'variations') {
          switch ($field['field_settings']['target_type']) {
            case 'paragraphs_type':
              return $product;

            break;
            case 'taxonomy_term':
              try {
                $create = $this->createTaxonomyTerm($product,
                  reset($field['field_settings']['handler_settings']['target_bundles']), $create_mode);
              }
              catch (Exception $e) {
                $create = $e->getMessage();
                $exception = TRUE;
              }
              break;

            case 'commerce_product_attribute_value':
              try {
                $create = $this->createAttribute($product,
                  reset($field['field_settings']['handler_settings']['target_bundles']), $create_mode);
              }
              catch (Exception $e) {
                $create = $e->getMessage();
                $exception = TRUE;
              }
              break;

            case 'commerce_store':
              try {
                $create = $this->getStore($product);
              }
              catch (Exception $e) {
                $create = $e->getMessage();
                $exception = TRUE;
              }
              break;

            case 'commerce_product_type':
              if ($product != '') {
                $create = [
                  'target_id' => $product,
                ];
              }
              break;

            case 'commerce_product':
              if ($product != '') {
                $query = $this->database->select('commerce_product')
                  ->fields('commerce_product', ['type'])
                  ->condition('commerce_product.product_id', (int) $product, '=')
                  ->execute()->fetchAll();
                if (!empty($query)) {
                  $create = [
                    'target_id' => (int) $product,
                  ];
                }
              }
              break;
          }
        }

        break;

      case 'datetime':
        $create = $this->createDateTime($product, $field);
        break;

      case 'telephone':
        $create = $product;
        break;

      default:
        print 'Unsupported fields';
        \Drupal::logger('format field exception')->debug('<pre><code>' . print_r($field, TRUE) . '</code></pre>');
        throw new Exception("This field type is not supported!");
    }
    if ($exception) {
      \Drupal::logger('format field exception')->debug('<pre><code>' . $exception . '</code></pre>');
      throw new Exception($create);
    }
    else {
      return $create;
    }
  }

  /**
   * Creates physical dimension value based on field settings.
   */
  public function createPhysicalDimension($value, $field_settings) {
    $field_value = [];
    $value = explode(' ', $value);
    if (count($value) != 2) {
      throw new Exception('Dimension is in wrong format. Follow "LxWxH [unit]". For example 4x5x6 m.');
    }
    else {
      $split_value = explode('x', $value[0]);
      if (count($split_value) != 3) {
        throw new Exception('Length, width and height values are required in the format "LxWxH [unit]."');
      }
      else {
        $field_value['length'] = $split_value[0];
        $field_value['width'] = $split_value[1];
        $field_value['height'] = $split_value[2];
        $field_value['unit'] = $value[1];
        return $field_value;
      }
    }
  }

  /**
   * Creates string value based on field settings.
   */
  public function createString($data, $field_settings) {
    if (isset($field_settings['max_length'])) {
      if (strlen($data) > $field_settings['max_length']) {
        throw new Exception('Maximum number of characters of ' . $field_settings['max_length']);
      }
    }
    return trim($data);
  }

  /**
   * Creates string value based on field settings.
   */
  public function createDateTime($data, $field_settings) {
    if ($data != '') {
      // Print $data; print '<br>';
      // print date('Y-m-d', strtotime($data));exit;
      return date('Y-m-d', strtotime($data));
    }
    else {
      return $data;
    }
  }

  /**
   * Creates text summary value based on field settings.
   */
  public function createTextSummary($data, $field_settings) {
    return [
      'value' => trim($data),
      'format' => 'full_html',
    ];
  }

  /**
   * Creates image value based on field settings.
   */
  public function createFile($data, $field_settings, $folders, $create_mode, $file_type = 'file') {
    // kint($data);
    if (empty($data)) {
      return NULL;
    }

    if ($create_mode) {
      if (filter_var(trim($data), FILTER_VALIDATE_URL)) {
        $data = basename($data);
      }
    }
    $saveFolder = $this->token->replace($field_settings['file_directory']);
    if (strpos($saveFolder, 'temporary://') === FALSE) {
      $saveFolder = 'public://' . $saveFolder;
    }
    foreach ($folders as $key => $folder) {
      if (!is_array($folder) && strpos($folder, 'temporary://') === FALSE && strpos($folder, 'public://') === FALSE) {
        $folders[$key] = 'public://' . $folder;
      }
    }
    // kint($saveFolder);
    if (!is_dir($saveFolder)) {
      mkdir($saveFolder, 0777, TRUE);
    }

    foreach ($folders as $key => $images) {
      $full_dir = scandir($images);
      $dir = array_diff($full_dir, ['.', '..']);
      // Print 'I`m here in scandir if <br>';.
      foreach ($dir as $file) {
        if (is_file($images . '/' . $file)) {
          if (strtolower($data) == strtolower($file)) {
            $imageData = file_get_contents($images . '/' . $file);
            $imagesPath = $saveFolder;
            $fileSave = file_save_data($imageData, $imagesPath . '/' . $data, FileSystemInterface::EXISTS_REPLACE);

            // If ($config['flush_image_cache'] === '1' && $file_type === 'image') {
            //                    $this->flushImageStyleUri($fileSave->getFileUri());
            //                  }
            if ($fileSave != NULL) {
              return ['target_id' => $fileSave->id()];
            }
          }
        }
      }
    }
    // exit;.
    \Drupal::logger('create file failed')->debug('Image ' . $data . ' was not found!');
    // Throw new Exception('Image ' . $data . ' was not found!');.
    return NULL;
  }

  /**
   * Creates Taxonomy term value based on field settings.
   */
  public function createTaxonomyTerm($name, $reference, $create = TRUE) {
    $vocabularies = Vocabulary::loadMultiple();
    if (isset($vocabularies[$reference])) {
      $vocab = $vocabularies[$reference];
    }
    else {
      foreach ($vocabularies as $key => $vocabulary) {
        if ($vocabulary->get('name') == $reference) {
          $reference = $key;
          $vocab = $vocabulary;
          break;
        }
      }
    }

    if (!isset($vocab)) {
      throw new Exception('Vocabulary does not exist');
    }
    $query = $this->entityTypeManager()->getStorage('taxonomy_term')->getQuery();
    $query->condition('vid', $reference);
    $query->condition('name', $name);
    $taxonomyId = $query->execute();

    if (empty($taxonomyId) && $create) {
      $term = Term::create([
        'vid' => $reference,
        'name' => $name,
      ]);
      $term->save();
      $taxonomyId = $term->id();
    }
    if (!$create) {
      return ['target_id' => uniqid()];
    }
    return is_array($taxonomyId) ? ['target_id' => current($taxonomyId)] : ['target_id' => $taxonomyId];
  }

  /**
   *
   */
  public function getStore($value) {
    if (is_numeric($value)) {
      $query = $this->database->select('commerce_store_field_data', 'cs')
        ->fields('cs', ['store_id'])
        ->condition('cs.store_id', $value)
        ->range(0, 1)
        ->execute();
      $store_ids = $query->fetchAll();
      if (count($store_ids) > 0) {
        return ['target_id' => reset($store_ids)->store_id];
      }
    }
    $query = $this->database->select('commerce_store_field_data', 'cs')
      ->fields('cs', ['store_id', 'name'])
      ->condition('cs.name', $value)
      ->range(0, 1)
      ->execute();
    $store_ids = $query->fetchAll();
    if (count($store_ids) > 0) {
      return ['target_id' => reset($store_ids)->store_id];
    }
    return '';
  }

  /**
   * Creates vocabulary.
   */
  public function createVocabulary($name, $vid = FALSE) {
    if ($vid === FALSE) {
      $vid = strtolower($name);
      $vid = str_replace(' ', '_', $vid);
    }
    $vocabularies = Vocabulary::loadMultiple();
    if (!isset($vocabularies[$vid])) {
      $vocabulary = Vocabulary::create([
        'vid' => $vid,
        'description' => '',
        'name' => $name,
      ]);
      $vocabulary->save();
    }

    return $vid;
  }

  /**
   * Creates integer value based on field settings.
   */
  public function createInteger($number, $field_settings) {
    $pass = TRUE;
    if (!is_numeric($number)) {
      $error = 'Must be number';
      throw new Exception($error);
    }
    else {
      if (!empty($field_settings['min'])) {
        if ($number < $field_settings['min']) {
          $error = 'Must be greater than ' . $field_settings['min'];
          $pass = FALSE;
        }
      }
      if (!empty($field_settings['max'])) {
        if ($number > $field_settings['max']) {
          $error = 'Must be smaller than ' . $field_settings['max'];
          $pass = FALSE;
        }
      }
    }
    if ($field_settings['unsigned'] == TRUE) {
      $number = abs($number);
    }
    if ($pass) {
      return round($number);
    }
    else {
      throw new Exception($error);
    }
  }

  /**
   * Creates decimal value based on field settings.
   */
  public function createDecimal($number, $field_settings) {
    $pass = TRUE;
    if (!is_numeric($number)) {
      $error = 'Must be number';
      throw new Exception($error);
    }
    else {
      if (!empty($field_settings['min'])) {
        if ($number < $field_settings['min']) {
          $error = 'Must be greater than ' . $field_settings['min'];
          $pass = FALSE;
        }
      }
      if (!empty($field_settings['max'])) {
        if ($number > $field_settings['max']) {
          $error = 'Must be smaller than ' . $field_settings['max'];
          $pass = FALSE;
        }
      }
    }
    if ($pass) {
      return $number;
    }
    else {
      throw new Exception($error);
    }
  }

  /**
   * Creates timestamp value based on field settings.
   */
  public function createTimestamp($stamp, $field_settings) {
    if (is_numeric($stamp) && (int) $stamp == $stamp) {
      return $stamp;
    }
    else {
      throw new Exception("Timestamp is not valid");
    }
  }

  /**
   * Checks sku validity.
   */
  public function createSku($value, $field_definition) {
    if ($this->getVariationIdBySku($value) !== FALSE) {
      throw new Exception("Sku already exists");
      // $value .= uniqid();
    }
    return $value;
  }

  /**
   * Creates email value based on field settings.
   */
  public function createEmail($email, $field_settings) {
    if (filter_var(trim($email), FILTER_VALIDATE_EMAIL)) {
      return trim($email);
    }
    else {
      throw new Exception("Timestamp is not valid");
    }
  }

  /**
   * Creates url value based on field settings.
   */
  public function createUrl($url, $field_settings, $name = 'link') {

    if (filter_var(trim($url), FILTER_VALIDATE_URL)) {
      if ($field_settings['title'] == 1) {
        return [
          "uri" => trim($url),
          "title" => $name,
          "options" => ["target" => "_blank"],
        ];
      }
      else {
        return ["uri" => trim($url), "options" => ["target" => "_blank"]];
      }
    }
    else {
      throw new Exception("Url is not valid");
    }
  }

  /**
   * Creates alias based on field settings.
   */
  public function createPath($url, $field_settings) {
    $url = trim($url);
    if ($url != filter_var($url, FILTER_SANITIZE_URL)) {
      throw new Exception("There are some illegal characters in url");
    }
    if (substr((string) $url, 0, 1) !== '/') {
      throw new Exception("URL alias must start with /");
    }
    return ['alias' => $url];
  }

  /**
   * Creates bool value based on field settings.
   */
  public function createBool($bool, $field_settings) {
    if ($bool == 1 || $bool == 0) {
      return $bool;
    }
    elseif ($bool == 'on_label' || $field_settings['on_label'] == $bool) {
      return 1;
    }
    elseif ($bool == 'off_label' || $field_settings['off_label'] == $bool) {
      return 0;
    }
    else {
      throw new Exception("Not valid boolean");
    }
  }

  /**
   * Creates Weight Physical Mesurement value based on field settings.
   */
  public function createPhysicalMesurementWeight($value, $field_settings) {
    $value = explode(' ', $value);
    if (count($value) != 2) {
      throw new Exception('Physical mesurement must have only value and unit(format: value unit)');
    }
    try {
      WeightUnit::assertExists($value[1]);
      return new Weight($value[0], $value[1]);
    }
    catch (\InvalidArgumentException $e) {
      throw new Exception($e->getMessage());
    }
  }

  /**
   * Creates Area Physical Mesurement value based on field settings.
   */
  public function createPhysicalMesurementArea($value, $field_settings) {
    $value = explode(' ', $value);
    if (count($value) != 2) {
      throw new Exception('Physical mesurement must have only value and unit(format: value unit)');
    }
    try {
      AreaUnit::assertExists($value[1]);
      return new Area($value[0], $value[1]);
    }
    catch (\InvalidArgumentException $e) {
      throw new Exception($e->getMessage());
    }
  }

  /**
   * Creates Length Physical Mesurement value based on field settings.
   */
  public function createPhysicalMesurementLength($value, $field_settings) {
    $value = explode(' ', $value);
    if (count($value) != 2) {
      throw new Exception('Physical mesurement must have only value and unit(format: value unit)');
    }
    try {
      LengthUnit::assertExists($value[1]);
      return new Length($value[0], $value[1]);
    }
    catch (\InvalidArgumentException $e) {
      throw new Exception($e->getMessage());
    }
  }

  /**
   * Creates Length Physical Mesurement value based on field settings.
   */
  public function createPhysicalMesurementVolume($value, $field_settings) {
    $value = explode(' ', $value);
    if (count($value) != 2) {
      throw new Exception('Physical mesurement must have only value and unit(format: value unit)');
    }
    try {
      VolumeUnit::assertExists($value[1]);
      return new Volume($value[0], $value[1]);
    }
    catch (\InvalidArgumentException $e) {
      throw new Exception($e->getMessage());
    }
  }

  /**
   * Creates list value based on field settings.
   */
  public function createList($data, $field_settings) {
    foreach ($field_settings['allowed_values'] as $key => $allowed_value) {
      if ($key == trim($data) || $allowed_value == trim($data)) {
        return $key;
      }
    }
    throw new Exception('Value is not allowed');
  }

  /**
   * Replaces _ from names when there are more than one file with same name.
   */
  private function replaceDuplicateInNames($basename) {
    $dotIndex = (int) strrpos($basename, '.');
    $underscoreIndex = (int) strrpos($basename, '_');
    $temp_name = substr($basename, 0, $underscoreIndex);
    $temp_name .= substr($basename, $dotIndex, strlen($basename) - $dotIndex);

    return $temp_name;
  }

  /**
   * Generates new sku.
   */
  public function generateSku() {

    $method = 1;

    $prefix = 'sku_';

    if ($method == 0) {
      // Auto increment.
      if ($this->config('commerce_smart_importer.settings')->get('increment_saver') == NULL) {
        $this->configFactoryService
          ->getEditable('commerce_smart_importer.settings')
          ->set('increment_saver', 0)
          ->save();
      }
      $increment = $this->config('commerce_smart_importer.settings')->get('increment_saver');

      do {
        $increment++;
        $query = $this->entityTypeManager->getStorage('commerce_product_variation')->getQuery();
        $query->condition('sku', $prefix . $increment);
      } while (!empty($query->execute()));
      return $prefix . $increment;
    }
    elseif ($method == 1) {

      $randomDigitsNumber = 9;

      do {
        $sku = '';
        for ($i = 0; $i < $randomDigitsNumber; $i++) {
          $sku .= mt_rand(0, 9);
        }
        $query = $this->entityTypeManager()->getStorage('commerce_product_variation')->getQuery();
        $query->condition('sku', $prefix . $sku);
      } while (!empty($query->execute()));
      return $prefix . $sku;
    }
  }

  /**
   * Gets all Terms from one vocabulary.
   */
  public function getReferencedTaxonomyTerms($entity = 'all', $type = 'default') {

    $entity_fields = $this->entityFieldManager
      ->getFieldDefinitions('node', $type);

    $taxonomies = [];
    foreach ($entity_fields as $key => $entity_field) {
      if ($entity_field->getType() == 'entity_reference') {
        if ($entity_field->getSettings()['target_type'] == 'taxonomy_term') {
          $field = [];
          if ($entity_field->getLabel() instanceof TranslatableMarkup) {
            $field['name'] = $entity_field->getLabel()->getUntranslatedString();
          }
          else {
            $field['name'] = is_object($entity_field->getLabel()) ? current($entity_field->getLabel()) : $entity_field->getLabel();
          }
          $field['machine_name'] = $key;
          $field['target_bundles'] = $entity_field->getSettings()['handler_settings']['target_bundles'];
          $taxonomies[] = $field;
        }
      }
    }
    return $taxonomies;
  }

  /**
   * Formats field definition for given product and variation type.
   */
  public function getFieldDefinition($with_identifiers = FALSE, $bundle, $type, $operation_mode) {
    $excluded_fields = $this->getExcludedFieldNames($with_identifiers, $type, $operation_mode);
    if ($type == 'commerce_product') {
      $product_field_definitions = $this->entityFieldManager->getFieldDefinitions('commerce_product', $bundle);
      $fields['product'] = [];
      foreach ($product_field_definitions as $field_name => $product_field_definition) {
        if (!in_array($field_name, $excluded_fields)) {
          $fields['product'][] = $this->formatFieldDefinition($product_field_definition, $field_name, $type);
        }
      }
      $variation_field_definitions = $this->entityFieldManager->getFieldDefinitions('commerce_product_variation', $bundle);
      foreach ($variation_field_definitions as $field_name => $variation_field_definition) {
        if (!in_array($field_name, $excluded_fields) && $field_name != 'product_id') {
          if ($field_name == 'price') {
            $price = $this->formatFieldDefinition($variation_field_definition, $field_name, $type);
          }
          else {
            $fields['variation'][] = $this->formatFieldDefinition($variation_field_definition, $field_name, $type);
          }
        }
      }
      if (isset($price)) {
        $fields['variation'][] = $price;
      }
      else {
        throw new Exception("Missing price object in variation");
      }

      $help_fields['label'] = 'Currency';
      $help_fields['machine_names'] = 'currency';
      $help_fields['field_types'] = 'currency';
      $help_fields['required'] = TRUE;
      $help_fields['cardinality'] = 1;
      $fields['variation'][] = $help_fields;

    }
    else {
      $node_field_definitions = $this->entityFieldManager->getFieldDefinitions('node', $bundle);
      $fields['node'] = [];
      foreach ($node_field_definitions as $field_name => $node_field_definition) {
        if (!in_array($field_name, $excluded_fields)) {
          $fields['node'][] = $this->formatFieldDefinition($node_field_definition, $field_name, $type);
        }
      }
      $paragraph_field_definitions = [];
      $paragraph_excluded_fields = $this->getExcludedFieldNames($with_identifiers, 'paragraph');
      foreach ($fields['node'] as $field_key => $node_field_data) {
        if ($node_field_data['field_types'] == 'entity_reference_revisions') {
          unset($fields['node'][$field_key]);
          $target_bundles = array_keys($node_field_data['field_settings']['handler_settings']['target_bundles']);
          foreach ($target_bundles as $target_bundle) {
            $temp_paragraph_field_definitions = $this->entityFieldManager->getFieldDefinitions('paragraph', $target_bundle);
            foreach ($temp_paragraph_field_definitions as $field_name => $temp_paragraph_field_definition) {
              if (!in_array($field_name, $paragraph_excluded_fields) || $field_name == 'type') {
                $fields['paragraph'][$target_bundle][] = $this->formatFieldDefinition($temp_paragraph_field_definition, $field_name, 'paragraph');
              }
            }
          }
        }
      }
    }

    if ($this->moduleHandler()->moduleExists('redirect')) {
      $help_fields['label'] = 'Redirection';
      $help_fields['machine_names'] = 'redirection';
      $help_fields['field_types'] = 'redirection';
      $help_fields['required'] = FALSE;
      $help_fields['cardinality'] = -1;
      $help_fields['field_settings']['read-only'] = FALSE;
      if ($type == 'commerce_product') {
        $fields['product'][] = $help_fields;
      }
      else {
        $fields['node'][] = $help_fields;
      }

    }
    $this->renameDuplicateFieldDefinitions($fields, $type);
    // kint($fields);exit;
    return $fields;
  }

  /**
   * Helper function for getFieldDefinition, formats one field.
   *
   * @see getFieldDefinition()
   */
  private function formatFieldDefinition($field_definition, $machine_name, $entity_type) {
    $field = [];
    if ($field_definition->getLabel() instanceof TranslatableMarkup) {
      $label = $field_definition->getLabel()->getUntranslatedString();
    }
    else {
      $label = is_object($field_definition->getLabel()) ? current($field_definition->getLabel()) : $field_definition->getLabel();
    }

    switch ($machine_name) {
      case 'product_id':
        $field['label'] = 'ID(product)';
        break;

      case 'variation_id':
        $field['label'] = 'ID(variation)';
        break;

      default:
        $field['label'] = $label;
    }
    $field['machine_names'] = $machine_name;
    $field['field_types'] = $field_definition->getType();
    $field['field_settings'] = $field_definition->getSettings();

    if ($field_definition instanceof FieldConfig) {
      $fieldStorage = $field_definition->getFieldStorageDefinition();
      $field['required'] = $field_definition->get('required');
      $field['cardinality'] = $fieldStorage->get('cardinality');
      $field['field_settings']['default_value'] = $field_definition->get('default_value');
      $field['field_settings']['default_value'] = is_array($field['field_settings']['default_value']) ? current($field['field_settings']['default_value']) : $field['field_settings']['default_value'];
    }
    elseif ($field_definition instanceof BaseFieldDefinition) {
      $field['cardinality'] = $field_definition->getCardinality();
      $field['required'] = $field_definition->isRequired();
      if ($machine_name == 'sku') {
        $field['field_settings']['default_value'] = 'generateSKU';
      }
      elseif (!isset($field['field_settings']['default_value'])) {
        if ($field_definition->getDefaultValueCallback() == NULL) {
          $field['field_settings']['default_value'] = FALSE;
        }
      }
    }
    $identifiers = $this->getIdentifierFields($entity_type);
    if ($entity_type == 'commerce_product') {
      if (in_array($machine_name, $identifiers['product']) || in_array($machine_name, $identifiers['variation'])) {
        $field['field_settings']['read-only'] = TRUE;
      }
      else {
        $field['field_settings']['read-only'] = FALSE;
      }
    }
    else {
      if (in_array($machine_name, $identifiers['node'])) {
        $field['field_settings']['read-only'] = TRUE;
      }
      else {
        $field['field_settings']['read-only'] = FALSE;
      }
    }
    return $field;
  }

  /**
   * Helper function for getFieldDefinition, returns excluded fields.
   *
   * @see getFieldDefinition()
   */
  private function getExcludedFieldNames($with_identifiers = FALSE, $entity_type, $operation_mode = 'create') {
    $route_name = \Drupal::routeMatch()->getRouteName();
    $excluded_fields = [
      'uuid',
      'langcode',
      'type',
      // 'status',
      'uid',
      'created',
      'changed',
      'default_langcode',
      'metatag',
    ];
    if ($entity_type == 'commerce_product') {
      $type_specific_fields = [
        'variations',
        // 'default_variation',
        // 'field_user',
        // 'stores'
      ];
      if ($route_name == 'content_csv_export_import.content_csv_import_form' && $operation_mode == 'create') {
        $type_specific_fields[] = 'product_id';
        $type_specific_fields[] = 'variation_id';
      }
    }
    else {
      $type_specific_fields = [
        'vid',
        'revision_timestamp',
        'revision_uid',
        'revision_log',
        'workspace',
        'revision_translation_affected',
        'revision_default',
        'sticky',
        'promote',
        'comment',
      ];
      if ($route_name == 'content_csv_export_import.content_csv_import_form' && $operation_mode == 'create') {
        $type_specific_fields[] = 'nid';
      }
    }
    if ($entity_type == 'paragraph') {
      $ptype_specific_fields = [
        'id',
        'revision_id',
        'parent_id',
        'parent_type',
        'behavior_settings',
      ];
      $type_specific_fields = array_merge($type_specific_fields, $ptype_specific_fields);
    }
    $excluded_fields = array_merge($excluded_fields, $type_specific_fields);

    if ($with_identifiers) {
      $identifiers = $this->getIdentifierFields($entity_type);
      foreach ($excluded_fields as $key => $excluded_field) {
        if ($entity_type == 'commerce_product') {
          if (in_array($excluded_field, $identifiers['product']) || in_array($excluded_field, $identifiers['variation'])) {
            unset($excluded_fields[$key]);
          }
        }
        else {
          if (in_array($excluded_field, $identifiers['node'])) {
            unset($excluded_fields[$key]);
          }
        }
      }
    }
    // kint($excluded_fields);exit;
    return $excluded_fields;
  }

  /**
   * Renames field definitions if there are more fields with same label.
   */
  private function renameDuplicateFieldDefinitions(&$fields, $entity_type) {
    // kint($fields);
    $used_labels = [];
    $duplicate_labels = [];
    $type_duplicate_labels = [];
    $subtype_duplicate_labels = [];
    $type_labels = [];
    $subtype_labels = [];
    if ($entity_type == 'node') {
      $type = 'node';
      $subtype = 'paragraph';
    }
    else {
      $type = 'product';
      $subtype = 'variation';
    }
    foreach ($fields[$type] as $key => $field) {
      if (in_array($field['label'], $used_labels)) {
        $duplicate_labels[] = $field['label'];
        if (in_array($field['label'], $type_labels)) {
          $type_duplicate_labels[] = $field['label'];
        }
      }
      else {
        $used_labels[] = $field['label'];
        $type_labels[] = $field['label'];
      }
    }
    if ($subtype == 'variation') {
      foreach ($fields[$subtype] as $key => $field) {
        if (in_array($field['label'], $used_labels)) {
          $duplicate_labels[] = $field['label'];
          if (in_array($field['label'], $subtype_labels)) {
            $subtype_duplicate_labels[] = $field['label'];
          }
        }
        else {
          $used_labels[] = $field['label'];
          $subtype_labels[] = $field['label'];
        }
      }
    }
    else {
      if (isset($fields[$subtype])) {
        foreach ($fields[$subtype] as $bundle => $fieldData) {
          foreach ($fieldData as $key => $field) {
            if (in_array($field['label'], $used_labels)) {
              $duplicate_labels[] = $field['label'];
              if (in_array($field['label'], $subtype_labels)) {
                $subtype_duplicate_labels[] = $field['label'];
              }
              else {
                $subtype_labels[] = $field['label'];
              }
            }
            else {
              $used_labels[] = $field['label'];
              $subtype_labels[] = $field['label'];
            }
          }
        }
      }
    }

    foreach ($fields[$type] as $key => $field) {
      if (in_array($field['label'], $duplicate_labels)) {
        $fields[$type][$key]['label'] .= '(' . $fields[$type][$key]['machine_names'] . ')';
      }
    }
    if ($entity_type == 'commerce_product') {
      foreach ($fields[$subtype] as $key => $field) {
        if (in_array($field['label'], $duplicate_labels) && in_array($field['label'], $subtype_duplicate_labels)) {
          $fields[$subtype][$key]['label'] .= '(' . $fields[$subtype][$key]['machine_names'] . ')';
        }
      }
    }
    else {
      if (isset($fields[$subtype])) {
        foreach ($fields[$subtype] as $bundle => $bundleFieldData) {
          foreach ($bundleFieldData as $key => $field) {
            if (in_array($field['label'], $duplicate_labels) && in_array($field['label'], $subtype_duplicate_labels)) {
              if (in_array($fields[$subtype][$bundle][$key]['machine_names'], ['type', 'status', 'parent_field_name'])) {
                $fields[$subtype][$bundle][$key]['label'] .= '(' . $bundle . ')';
              }
              else {
                $fields[$subtype][$bundle][$key]['label'] .= '(' . $fields[$subtype][$bundle][$key]['machine_names'] . ')';
              }
            }
          }
        }
      }
    }

    // kint($fields);exit;
  }

  /**
   * Creates product.
   */
  public function createNewEntity($field_definitions, $entity, ImportingParameters $parameters, $external_folders, $bundle, $import_type, $subType, $operation_mode, &$context) {

    if ($operation_mode == 'update' && $import_type == 'product' && ($field_definitions[$import_type][0]['machine_names'] == 'product_id')) {
      $pid_delete = $entity[$import_type][$field_definitions[$import_type][0]['index']];
      $variation_query = $this->database->query('SELECT variation_id FROM commerce_product_variation_field_data WHERE product_id=' . $pid_delete)
        ->fetchAll();
      foreach ($variation_query as $variation) {
        $delete_variants[] = $variation->variation_id;
      }
      $variation_storage = $this->entityTypeManager()->getStorage('commerce_product_variation');
      $load_delete_variants = $variation_storage->loadMultiple($delete_variants);
      $variation_storage->delete($load_delete_variants);
    }
    $results = [];
    $each_field_log = [];
    \Drupal::logger('createNewProduct')->debug('<pre><code>' . print_r($entity, TRUE) . '</code></pre>');
    // Products.
    $is_entity_creatable = TRUE;
    $redirections = [];
    foreach ($field_definitions[$import_type] as $key => $field_definition) {
      if ($field_definition['field_types'] == 'currency' || !array_key_exists('index', $field_definition)) {
        continue;
      }
      if ($field_definition['field_types'] === 'redirection') {
        $redirections = explode('|', $entity[$import_type][$field_definition['index']]);
        continue;
      }
      $values = explode('|', $entity[$import_type][$field_definition['index']]);
      // Formats field and checks for validity.
      if ($bundle != NULL) {
        $each_field_log[$key] = $this->formatMultipleFieldValues($values, $field_definition, $parameters, $external_folders, 'custom');
      }
      else {
        $each_field_log[$key] = $this->formatMultipleFieldValues($values, $field_definition, $parameters, $external_folders);
      }
      $this->duplicateValuesPass($each_field_log[$key]);
      $this->cardinalityPass($each_field_log[$key], $field_definition);
      $this->useDefaultValuePass($each_field_log[$key], $field_definition);
      $this->requiredPass($each_field_log[$key], $field_definition);
    }
    if ($is_entity_creatable) {
      $is_entity_creatable = $parameters->matchParameters($each_field_log);
    }
    $each_field_log['has_log'] = FALSE;
    foreach ($each_field_log as $each_field_logg) {
      if ($each_field_logg['has_log']) {
        $each_field_log['has_log'] = TRUE;
        break;
      }
    }
    // $this->changeFieldHasLog($each_field_log);
    // Varitions.
    $subType_each_field_log = [];

    foreach ($entity[$subType . 's'] as $key => $sub_type_data) {
      $subType_each_field_log[$key] = [];
      $subType_each_field_log[$key]['creatable'] = TRUE;
      if ($import_type == 'product') {
        if (!$this->variationCurrencyValidityPass($sub_type_data, $field_definitions)) {
          $subType_each_field_log[$key]['currency'] = FALSE;
        }
        else {
          $subType_each_field_log[$key]['currency'] = TRUE;
        }
      }
      if ($import_type == 'product') {
        foreach ($field_definitions[$subType] as $field_key => $field_definition) {
          if ($field_definition['field_types'] == 'currency' || !array_key_exists('index', $field_definition)) {
            continue;
          }
          if (is_array($sub_type_data[$field_definition['index']])) {
            continue;
          }
          $values = explode('|', $sub_type_data[$field_definition['index']]);
          $subType_each_field_log[$key][$field_key] = $this->formatMultipleFieldValues($values, $field_definition, $parameters, $external_folders, $bundle);

          $this->duplicateValuesPass($subType_each_field_log[$key][$field_key]);
          $this->cardinalityPass($subType_each_field_log[$key][$field_key], $field_definition);
          $this->useDefaultValuePass($subType_each_field_log[$key][$field_key], $field_definition);
          $this->requiredPass($subType_each_field_log[$key][$field_key], $field_definition);
          if ($field_definition['machine_names'] === 'sku') {
            $subType_each_field_log[$key][$field_key]['sku'] = TRUE;
          }
        }
      }
      else {
        foreach ($field_definitions[$subType] as $subtypeBundle => $subTypeBundleData) {
          foreach ($subTypeBundleData as $field_key => $field_definition) {
            if ($field_definition['field_types'] == 'currency' || !array_key_exists('index', $field_definition)) {
              continue;
            }
            if (!isset($sub_type_data[$field_definition['index']]) || is_array($sub_type_data[$field_definition['index']])) {
              continue;
            }
            $values = explode('|', $sub_type_data[$field_definition['index']]);

            $subType_each_field_log[$key][$field_key] = $this->formatMultipleFieldValues($values, $field_definition, $parameters, $external_folders, $bundle);

            $this->duplicateValuesPass($subType_each_field_log[$key][$field_key]);
            $this->cardinalityPass($subType_each_field_log[$key][$field_key], $field_definition);
            $this->useDefaultValuePass($subType_each_field_log[$key][$field_key], $field_definition);
            $this->requiredPass($subType_each_field_log[$key][$field_key], $field_definition);

          }
        }
      }

      if ($subType_each_field_log[$key]['creatable']) {
        // kint($variation_each_field_log[$key]);.
        $subType_each_field_log[$key]['creatable'] = $parameters->matchParameters($subType_each_field_log[$key]);
      }
      // $this->changeFieldHasLog($variation_each_field_log[$key]);
      $subType_each_field_log[$key]['has_log'] = FALSE;
      \Drupal::logger('Each log debug')->debug('<pre><code>' . print_r($subType_each_field_log, TRUE) . '</code></pre>');
      foreach ($subType_each_field_log[$key] as $subType_each_field_logg) {
        if (isset($subType_each_field_logg['has_log']) && $subType_each_field_logg['has_log']) {
          $subType_each_field_log[$key]['has_log'] = TRUE;
          break;
        }
      }
    }
    // Print 'Variation Log';
    // kint($variation_each_field_log);exit;
    if (!$each_field_log['has_log']) {
      foreach ($subType_each_field_log as $one_field_log) {
        if ($one_field_log['has_log']) {
          $each_field_log['has_log'] = TRUE;
          break;
        }
      }
    }
    $error_log = [
      $import_type => $each_field_log,
      $subType => $subType_each_field_log,
    ];
    // kint($error_log);exit;
    foreach ($error_log[$import_type] as $entity_error_log_custom) {
      if (!empty($entity_error_log_custom['not_valid'])) {
        // kint($product_error_log_custom);
        \Drupal::logger('Failed Product Logs' . $bundle)->warning('<pre><code>' . print_r($entity_error_log_custom, TRUE) . '</code><pre>');
      }
    }

    foreach ($error_log[$subType] as $entity_error_log_customs) {
      foreach ($entity_error_log_customs as $entity_error_log_custom) {
        if (!empty($entity_error_log_custom['not_valid'])) {
          // kint($product_error_log_custom);
          \Drupal::logger('Failed variation Logs' . $bundle)->warning('<pre><code>' . print_r($entity_error_log_custom, TRUE) . '</code><pre>');
        }
      }
    }//exit;
    // kint($variation_each_field_log);exit;
    $entity_data = $this->formatValuesArray($each_field_log, $field_definitions[$import_type]);
    $subType_data = [];
    $valid_subtypes = TRUE;
    // kint($parameters->notValidVariations);
    // kint($subType_each_field_log);exit;
    $paragraph_create = [];
    foreach ($subType_each_field_log as $subType_field_log) {
      if ($subType_field_log['creatable']) {
        if ($import_type == 'product') {
          $subType_data[] = $this->formatValuesArray($subType_field_log, $field_definitions[$subType]);
        }
        else {
          $temp = $this->formatValuesArray($subType_field_log, $field_definitions[$subType][$subType_field_log[0]['values'][0]]);
          $subType_data[] = $temp;
        }
      }
      if (!$subType_field_log['creatable']) {
        $valid_subtypes = FALSE;
      }
    }

    $created = FALSE;
    $valid_import = FALSE;
    if ($valid_subtypes) {
      if ($is_entity_creatable && count($entity_data) > 0) {
        $entity_data['uid'] = $this->currentUser()->id();
        if ($import_type == 'product') {
          $stores = [];
          if (!array_key_exists('stores', $entity_data) || !is_array($entity_data['stores']) || count($entity_data['stores']) === 0) {
            $store_ids = $this->getAllStoreIds();
            foreach ($store_ids as $store_id) {
              $stores[] = ['target_id' => $store_id];
            }
            $entity_data['stores'] = $stores;
          }
        }

        $entity_data['type'] = $bundle;
        // kint($variation_data);
        //        kint($product_data);
        //        exit;
        if ($import_type == 'product') {
          if ($operation_mode == 'update' && isset($entity_data['product_id'])) {
            // kint($entity_data['product_id']);.
            $entityCreation = Product::load((string) $entity_data['product_id']);
            // kint($entityCreation);exit;
            unset($entity_data['product_id']);
            foreach ($entity_data as $product_field_machine_name => $product_field_value) {
              $entityCreation->set($product_field_machine_name, $product_field_value);
            }
          }
          else {
            $entityCreation = Product::create($entity_data);
          }
          foreach ($subType_data as $subtype_datum) {
            $subtype_datum['type'] = $bundle;
            // Print $variation_datum['type'];exit;.
            $variationCreationTemp = ProductVariation::create($subtype_datum);
            if ($variationCreationTemp->validate()) {
              $variationCreationTemp->save();
              $valid_import = TRUE;
              $entityCreation->addVariation($variationCreationTemp);
            }
          }
        }
        else {
          foreach ($subType_data as $paragraph_data) {
            $parent_field_name = $paragraph_data['parent_field_name'];
            unset($paragraph_data['parent_field_name']);
            $temp_paragraph_create = Paragraph::create($paragraph_data);
            if ($temp_paragraph_create->save()) {
              $entity_data[$parent_field_name][] = [
                'target_id' => $temp_paragraph_create->id(),
                'target_revision_id' => $temp_paragraph_create->getRevisionId(),
              ];
            }
          }
          if ($operation_mode == 'update' && isset($entity_data['nid'])) {
            $entityCreation = Node::load((string) $entity_data['nid']);
            if ($entityCreation) {
              unset($entity_data['nid']);
              foreach ($entity_data as $node_field_machine_name => $node_field_value) {
                $entityCreation->set($node_field_machine_name, $node_field_value);
              }

            }
          }
          else {
            $entityCreation = Node::create($entity_data);
          }
          $valid_import = TRUE;
        }

        if ($valid_import) {
          $entityCreation->save();
          if ($this->moduleHandler()->moduleExists('redirect')) {
            $this->createEntityRedirection($entityCreation, $redirections);
          }
          $created = TRUE;
        }
        else {
          \Drupal::logger('Failedd')->warning('<pre><code>' . print_r('Variation creation failedd' . '---' . $bundle, TRUE) . '</code><pre>');
        }
      }
      else {
        \Drupal::logger('InValid creation ' . $bundle)->warning('<pre><code>' . print_r($is_product_creatable, TRUE) . '</code><pre>');
        \Drupal::logger('InValid creation ' . $bundle)->warning('<pre><code>' . print_r($variation_data, TRUE) . '</code><pre>');
      }
    }
    else {
      \Drupal::logger('Failed creation ' . $bundle)->warning('<pre><code>' . print_r($each_field_log, TRUE) . '</code><pre>');
      print $bundle . '<br>';
      // print_r($parameters);
      // kint($each_field_log);
      // kint($bundle);
      // kint($parameters);
      // exit;
    }
    if (isset($entityCreation)) {
      $results[] = $entityCreation->id();
      $context['results']['messages'][] = $entityCreation->getTitle() . ' with Id ' . $entityCreation->id() . ' ' . $operation_mode . 'd successfully!';
      $context['results'][] = $entityCreation->getTitle();
    }
    else {
      \Drupal::logger('Product creation failedddd')->warning('<pre><code>' . print_r($entity, TRUE) . '</code><pre>');
      $results[] = $entity;
      $context['results'][] = $entity;
    }
  }

  /**
   * Helper function for createNewProduct.
   *
   * Formats multiple values.
   */
  public function formatMultipleFieldValues($values, $field_definition, ImportingParameters $parameters, $external_folders, $bundle) {
    $log['values'] = [];
    $log['not_valid'] = [];
    $log['has_log'] = FALSE;

    foreach ($values as $key => $value) {
      if ($value != '') {
        try {
          if (in_array($field_definition['field_types'], ['fivestar'])) {
            $log['values'][] = (int) $value;
          }
          else {
            $log['values'][] = $this->formatField($field_definition, $value, $external_folders, $parameters->createNode);
          }
        }
        catch (Exception $e) {
          \Drupal::logger('format multiple field values')->debug('<pre><code>' . $e->getMessage() . '</code><pre>');
          $log['not_valid'][] = [
            'log' => $e->getMessage(),
            'order' => $key + 1,
          ];
          $log['has_log'] = TRUE;
        }
      }
      elseif ($field_definition['machine_names'] == 'weight') {
        try {
          $log['values'][] = $this->formatField($field_definition, '0 kg', $external_folders, $parameters->createProduct);
        }
        catch (Exception $e) {
          $log['not_valid'][] = [
            'log' => $e->getMessage(),
            'order' => (string) ($key + 1),
          ];
          $log['has_log'] = TRUE;
        }
      }
    }
    return $log;
  }

  /**
   * Helper function for createNewProduct.
   *
   * Checks if field log contains duplicate values, returns corrected.
   */
  public function duplicateValuesPass(&$field_log) {
    $new_values = [];
    $field_log['duplicates'] = TRUE;
    foreach ($field_log['values'] as $value) {
      if (!in_array($value, $new_values)) {
        $new_values[] = $value;
      }
      else {
        $field_log['duplicates'] = FALSE;
        $field_log['has_log'] = TRUE;
      }
    }
    $field_log['values'] = $new_values;
  }

  /**
   * Helper function for createNewProduct.
   *
   * Checks if field log satisfies cardinality, returns corrected.
   */
  public function cardinalityPass(&$field_log, $field_definition) {
    if ($field_definition['cardinality'] == -1) {
      $field_log['cardinality'] = TRUE;
    }
    elseif ($field_definition['cardinality'] < count($field_log['values'])) {
      $field_log['values'] = array_slice($field_log['values'], 0, $field_definition['cardinality']);
      $field_log['cardinality'] = FALSE;
      $field_log['has_log'] = TRUE;
    }
    else {
      $field_log['cardinality'] = TRUE;
    }
  }

  /**
   * Helper function for createNewProduct.
   *
   * If needed this will use default value.
   */
  public function useDefaultValuePass(&$field_log, $field_definition) {
    $default_index = $field_definition['field_types'] == 'image' ? 'default_image' : 'default_value';

    if (count($field_log['values']) == 0 && $field_definition['field_settings'][$default_index] !== FALSE) {
      if ($field_definition['field_settings'][$default_index] == 'generateSKU') {
        $field_log['values'] = [$this->generateSku()];
        $field_log['default_value'] = FALSE;
        $field_log['has_log'] = TRUE;
      }
      else {
        $field_log['values'] = $field_definition['field_settings'][$default_index];
        $field_log['default_value'] = FALSE;
        $field_log['has_log'] = TRUE;
      }
    }
    else {
      $field_log['default_value'] = TRUE;
    }
  }

  /**
   * Helper function for createNewProduct.
   */
  public function requiredPass(&$field_log, $field_definition) {
    if (count($field_log['values']) == 0 && $field_definition['required'] == TRUE) {
      $field_log['required'] = FALSE;
      $field_log['has_log'] = TRUE;
    }
    else {
      $field_log['required'] = TRUE;
    }
  }

  /**
   * Checks if currency is valid and reformats price.
   */
  private function variationCurrencyValidityPass(&$variation, $field_definitions) {
    $currency = '';
    foreach ($field_definitions['variation'] as $field_definition) {
      if ($field_definition['field_types'] == 'currency') {
        $currency = $variation[$field_definition['index']];
        break;
      }
    }
    $currency = $this->checkCurrencyValidity($currency);
    if ($currency === FALSE) {
      return FALSE;
    }
    foreach ($field_definitions['variation'] as $field_definition) {
      if ($field_definition['field_types'] == 'commerce_price') {
        if (isset($field_definition['index'])) {
          if (strpos($variation[$field_definition['index']], $currency) === FALSE && $variation[$field_definition['index']] != '') {
            $variation[$field_definition['index']] = $variation[$field_definition['index']] . ' ' . $currency;
          }
        }
      }
    }
    return TRUE;
  }

  /**
   * Overrides value if is available.
   */
  private function overrideValue(&$values, $override_values, $field_definition) {
    if (isset($override_values[$field_definition['machine_names']])) {
      $values = explode('|', $override_values[$field_definition['machine_names']]);
    }
  }

  /**
   * Helper function for createNewProduct.
   *
   * Formats values from field log.
   */
  private function formatValuesArray($field_log, $field_definitions) {
    $values = [];
    foreach ($field_definitions as $key => $field_definition) {
      if (array_key_exists($key, $field_log)) {
        $values[$field_definition['machine_names']] = count($field_log[$key]['values']) == 1 ? current($field_log[$key]['values']) : $field_log[$key]['values'];
      }
    }
    return $values;
  }

  /**
   * Changes if log should be logged.
   */
  private function changeFieldHasLog(&$fields_log) {
    // \Drupal::logger('Field Log')->warning($fields_log);
    $fields_log['has_log'] = FALSE;
    foreach ($fields_log as $field_log) {
      if ($field_log['has_log']) {
        $fields_log['has_log'] = TRUE;
        return;
      }
    }
  }

  /**
   * Add redirections that will lead to product.
   */
  public function createEntityRedirection($entity_object, array $redirections) {
    $url = 'internal:' . $entity_object->toUrl()->toString();
    foreach ($redirections as $redirection) {
      if (empty($redirection)) {
        continue;
      }
      if (substr((string) $redirection, 0, 1) === '/') {
        $redirection = substr($redirection, 1);
      }
      Redirect::create([
        'redirect_source' => $redirection,
        'redirect_redirect' => $url,
        'language' => 'und',
        'status_code' => '301',
      ])->save();
    }
  }

  /**
   * Exports groups of entity based on field_deifnitions.
   */
  public function exportMultipleFields($entity_type, $entity_id, $field_definitions, $folderName = NULL) {
    if (empty($field_definitions)) {
      return [];
    }
    $entity = $this->entityTypeManager()->getStorage($entity_type)->load($entity_id);
    $values = [];
    foreach ($field_definitions as $field_definition) {
      $values[] = $this->exportField($entity, $field_definition, $folderName);
      // If ($entity_type == 'paragraph') {kint($field_definitions);kint($values);exit;}
    }
    return $values;
  }

  /**
   * Force different types of fields to string.
   */
  public function exportField($entity, $field_definition, $folderName = NULL) {
    $value = '';
    switch ($field_definition['field_types']) {
      case 'text':
      case 'text_long':
      case 'string_long':
      case 'float':
      case 'decimal':
      case 'timestamp':
      case 'email':
      case 'link':
      case 'boolean':
      case 'string':
      case 'text_with_summary':
      case 'weight':
      case 'list_string':
      case 'list_float':
      case 'list_integer':
      case 'integer':
        $value = $this->exportDefaultField($entity, $field_definition, $folderName);
        break;

      case 'commerce_price':
        $value = $this->exportPrice($entity, $field_definition);
        break;

      case 'currency':
        $value = $this->exportCurrency($entity);
        break;

      case 'entity_reference':
        $value = $this->exportEntity($entity, $field_definition);
        break;

      case 'image':
      case 'file':
        $value = $this->exportImage($entity, $field_definition, $folderName);
        break;

      case 'physical_measurement':
        $value = $this->exportPhysicalMeasurement($entity, $field_definition);
        break;

      case 'redirection':
        $value = '';
        break;

      default:
        $value = $this->exportDefaultField($entity, $field_definition, $folderName);
        break;

    }
    return $value;
  }

  /**
   * Helper function for exportField.
   *
   * Most of fields type export.
   */
  public function exportDefaultField($entity, $field_definition, $folderName = NULL) {
    $folder = $folderName;
    $values = [];
    if (!$entity->hasField($field_definition['machine_names'])) {
      return '';
    }
    foreach ($entity->get($field_definition['machine_names'])->getValue() as $item) {
      $values[] = current($item);
    }
    $values = implode('|', $values);
    if (in_array($field_definition['field_types'], ['text_long', 'text_with_summary'])) {
      $currentHost = \Drupal::request()->getSchemeAndHttpHost();
      $folder_abs_path = \Drupal::service('file_system')->realpath($folderName);
      // Print $folder_abs_path;exit;.
      foreach ($entity->get($field_definition['machine_names'])->getValue() as $item) {
        preg_match_all('/<img[^>]+>/i', $item['value'], $imgTags);
        $image_sources = [];
        for ($i = 0; $i < count($imgTags[0]); $i++) {
          // Get the source string.
          preg_match('/src="([^"]+)/i', $imgTags[0][$i], $imgage);
          // Remove opening 'src=' tag, can`t get the regex right.
          $temp_image = str_ireplace('src="', '', $imgage[0]);
          $temp_image_uri = str_replace('/drupal/sites/default/files/', 'public://', $temp_image);
          $temp_image_url = \Drupal::service('file_system')->realpath($temp_image_uri);
          $temp_image_name = basename($temp_image_url);
          $temp_folderName = str_replace('public://', '', str_replace('/' . $temp_image_name, '', $temp_image_uri));
          $dest_img_name = ($temp_folderName != '') ? $temp_folderName . ']]' . $temp_image_name : $temp_image_name;
          // \Drupal::logger('export formatted HTML images')->debug('<pre><code>' . print_r($imgage, TRUE) . '</code></pre>');
          // \Drupal::logger('export formatted HTML dest')->debug($folder_abs_path . '/inline-images/');
          // \Drupal::logger('export formatted HTML temp image name')->debug($temp_image_name);
          copy($temp_image_url, $folder_abs_path . '/inline-images/' . $temp_image_name);
          if (!in_array($temp_image, $image_sources)) {
            $image_sources[] = $temp_image;
            // $data = str_replace($source_host, $current_parsed_url['path'], $data);
          }
        }
      }
      // $values = implode('|', $values);
    }
    return $values;
  }

  /**
   * Helper function for exportField.
   *
   * Exports Formatted HTML.
   */
  public function exportFormattedHTML($entity, $field_definition, $folderName = NULL) {
    if (in_array($field_definition['field_types'], ['text_long', 'text_with_summary'])) {
      $currentHost = \Drupal::request()->getSchemeAndHttpHost();
      $folder_abs_path = \Drupal::service('file_system')->realpath($folderName);
      foreach ($entity->get($field_definition['machine_names'])->getValue() as $item) {
        $values[] = $item['value'];
        preg_match_all('/<img[^>]+>/i', $item['value'], $imgTags);
        $image_sources = [];
        for ($i = 0; $i < count($imgTags[0]); $i++) {
          // Get the source string.
          preg_match('/src="([^"]+)/i', $imgTags[0][$i], $imgage);
          // Remove opening 'src=' tag, can`t get the regex right.
          $temp_image = str_ireplace('src="', '', $imgage[0]);
          $temp_image_uri = str_replace('/sites/default/files/', 'public://', $temp_image);
          $temp_image_url = \Drupal::service('file_system')->realpath($temp_image_uri);
          $temp_image_name = basename($temp_image_url);
          $temp_folderName = str_replace('public://', '', str_replace('/' . $temp_image_name, '', $temp_image_uri));
          $dest_img_name = ($temp_folderName != '') ? $temp_folderName . ']]' . $temp_image_name : $temp_image_name;
          \Drupal::logger('export formatted HTML temp image')->debug($temp_image_url);
          \Drupal::logger('export formatted HTML dest')->debug($folder_abs_path . '/inline-images/');
          copy($temp_image_url, $folder_abs_path . '/inline-images/' . $temp_image_name);
          if (!in_array($temp_image, $image_sources)) {
            $image_sources[] = $temp_image;
            // $data = str_replace($source_host, $current_parsed_url['path'], $data);
          }
        }
      }
      // $values = implode('|', $values);
    }
    else {
      $values = [];
      if (!$entity->hasField($field_definition['machine_names'])) {
        return '';
      }
      foreach ($entity->get($field_definition['machine_names'])->getValue() as $item) {
        $values[] = current($item);
      }
      $values = implode('|', $values);
    }
    return $values;
  }

  /**
   * Helper function for exportField.
   *
   * Exports price.
   */
  public function exportPrice($entity, $field_definition) {
    $values = [];
    foreach ($entity->get($field_definition['machine_names'])->getValue() as $item) {
      $field = $item;
      $values[] = number_format($field['number'], 2, '.', '');
    }
    $values = implode('|', $values);
    return $values;
  }

  /**
   * Helper function for exportField.
   *
   * Exports Currency.
   */
  public function exportCurrency($entity) {
    $value = $entity->get('price');
    $field = current($value->getValue());
    return $field['currency_code'];
  }

  /**
   * Helper function for exportField.
   *
   * Exports entity name(title).
   */
  public function exportEntity($entity, $field_definition) {
    $values = [];

    foreach ($entity->get($field_definition['machine_names'])->getValue() as $item) {

      $entity = $this->entityTypeManager()->getStorage($field_definition['field_settings']['target_type'])->load($item['target_id']);
      // \Drupal::logger('export entity')->debug('<pre><code>' . print_r($entity, TRUE) . '</code></pre>');
      if (in_array($field_definition['field_settings']['target_type'], ['commerce_product_type', 'commerce_product'])) {
        $values[] = $item['target_id'];
      }
      elseif ($field_definition['field_settings']['target_type'] == 'paragraphs_type') {
        $values[] = $entity->id();
      }
      else {
        if (!$entity || !method_exists($entity, 'hasField')) {
          // \Drupal::logger('export entity check failed')->debug('<pre><code>' . print_r($field_definition, TRUE) . '</code></pre>');
          continue;
        }
        if ($entity->hasField('name')) {
          $values[] = $entity->getName();
        }
        elseif ($entity->hasField('title')) {
          $values[] = $entity->getTitle();
        }
      }

    }

    $values = implode('|', $values);

    return $values;
  }

  /**
   * Helper function for exportField.
   *
   * Exports filename.
   */
  public function exportImage($entity, $field_definition, $folderName = NULL) {
    $values = [];
    foreach ($entity->get($field_definition['machine_names'])->getValue() as $item) {
      if ($item['target_id'] != NULL) {
        $file_object = $this->entityTypeManager()->getStorage('file')->load($item['target_id']);
        if ($file_object != NULL) {
          $file_uri = $file_object->uri->value;
          if (file_exists($file_uri)) {
            \Drupal::service('file_system')->copy($file_uri, $folderName, FILE_EXISTS_REPLACE);
            $values[] = $file_object->getFilename();
          }
        }
      }
    }
    $values = implode('|', $values);
    return $values;
  }

  /**
   * Exports physical mesurement.
   */
  public function exportPhysicalMeasurement($entity, $field_definition) {
    if (!empty($entity->get($field_definition['machine_names'])->getValue())) {
      $value = $entity->get($field_definition['machine_names'])->getValue();
      return current($value)['number'] . ' ' . current($value)['unit'];
    }
    else {
      return '';
    }
  }

  /**
   * Caution: Erase all products on site.
   *
   * @deprecated
   */
  public function eraseAllProductsOnSite($pass) {
    if ($pass == 'mrmotmrmot23#42234d') {
      $results = $this->database->select('commerce_product')
        ->fields('commerce_product', ['product_id'])
        ->execute()->fetchAll();

      $count = count($results);
      $batches = ceil($count / 70);
      $batch = [
        'title' => $this->t('ERASING ALL DATA'),
        'init_message' => $this->t('Beginning...'),
        'progress_message' => $this->t('ERASED @current out of @total products'),
        'error_message' => $this->t('Something went wrong'),
        'progressive' => FALSE,
        'finished' => [$this, 'finished'],
        'operations' => [],
      ];

      for ($i = 0; $i < $batches; $i++) {
        $batch['operations'][] = [[$this, 'productEraser'], [70]];
      }
      batch_set($batch);
    }
  }

  /**
   * Caution: Erases first 70 products on site.
   *
   * @deprecated
   */
  public function productEraser($number) {

    $results = $this->database->select('commerce_product')
      ->fields('commerce_product', ['product_id'])
      ->range(0, $number)
      ->execute()->fetchAll();
    $ids = [];
    foreach ($results as $result) {
      $ids[] = $result->product_id;
    }
    $products = Product::loadMultiple($ids);
    foreach ($products as $result) {
      $result->delete();
    }
  }

  /**
   * Returnst identifiers fields machine names.
   */
  public function getIdentifierFields($type) {
    if ($type == 'commerce_product') {
      return [
        'product' => ['product_id'],
        'variation' => ['sku', 'variation_id'],
      ];
    }
    else {
      return [
        'node' => ['id'],
      ];
    }
  }

  /**
   * Returns variation id by sku.
   */
  public function getVariationIdBySku($id) {
    $query = $this->database->query("SELECT variation_id FROM commerce_product_variation_field_data WHERE sku='" . $id . "'");
    $sku = $query->fetchAll();

    if (!empty($sku)) {
      return $sku[0]->variation_id;
    }
    else {
      return FALSE;
    }
  }

  /**
   * Returns list of bundles for entity.
   */
  public function getEntityBundles($entity_name) {
    $bundles = $this->entityTypeBundleInfo->getBundleInfo($entity_name);
    $entityBundles = [];
    foreach ($bundles as $key => $bundle) {
      $entityBundles[$key] = $bundle['label'];
    }
    return $entityBundles;
  }

  /**
   *
   */
  public function getAllStoreIds() {
    $store_results = $this->database->query("SELECT store_id FROM commerce_store_field_data")->fetchAll();
    $stores = [];
    foreach ($store_results as $store_result) {
      $stores[] = current($store_result);
    }
    return $stores;
  }

  /**
   *
   */
  public function createCustomMedia($imgSrc, $dir = NULL, $img_bundle, $title, $returnValue = NULL) {
    $encoded_imgSrc = urldecode($imgSrc);
    $ch = curl_init($imgSrc);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    curl_exec($ch);
    $retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($retcode == 200) {
      $file_data_config = file_get_contents($imgSrc);
      if ($dir == NULL) {
        $dir = 'public://' . date('Y') . '-' . date('m') . '/';
      }
      else {
        $dir = 'public://' . $dir . '/';
      }
      $ext = pathinfo(parse_url($imgSrc, PHP_URL_PATH), PATHINFO_EXTENSION);
      $title = basename($encoded_imgSrc);
      $file = file_save_data($file_data_config, $dir . $title, FILE_EXISTS_RENAME);

      if ($file == NULL) {
        print $retcode . '-- Img Src --<br>';
        print $imgSrc . '-- Base Name --<br>';
        print basename($imgSrc) . '  Img Name --<br>';
        // \Drupal::logger('creating_custom_media')->error('Creation of image failed for ' . $imgSrc);
      }
      else {
        if ($returnValue == 'path') {
          return file_create_url($file->getFileUri());
        }
        else {
          return $file->id();
        }

      }
    }
    else {
      \Drupal::logger('creating_custom_media')->error('Image not found for ' . $imgSrc);
    }

  }

  /**
   * Counts Entities and sub entities (Paragraphs and variations`) in CSV file.
   */
  public function countEntitiesAndSubEntities($file) {
    $linecount = 0;
    $entityCount = 0;
    $handle = fopen($file, "r");
    $data = [];
    if ($handle) {
      while (($line = fgetcsv($handle)) !== FALSE) {
        $data[] = $line;
        // $linecount++;
        if (!empty($line[0])) {
          $entityCount++;
        }
        else {
          if (!empty(end($line))) {
            $linecount++;
          }
        }
      }//kint($data);exit;
      fclose($handle);
      return [
        'entity_count' => $entityCount - 1,
        'sub_entity_count' => $linecount,
      ];
    }

  }

  /**
   * Checks if currency is valid and returns formated.
   */
  public function checkCurrencyValidity($code) {
    /** @var \Drupal\commerce_price\Entity\Currency $currecies */
    $currecies = Currency::loadMultiple();
    foreach ($currecies as $currency) {
      if ($code == $currency->getCurrencyCode() || strtolower($code) == strtolower($currency->getName()) ||
        $code == $currency->getNumericCode() || $code == $currency->getSymbol()) {
        return $currency->getCurrencyCode();
      }
    }
    return FALSE;
  }

  /**
   * Returns node attached to the paragraph.
   */
  public function getNodeAttachedToParagraph($target_id) {
    $target_type = 'paragraph';
    $map = \Drupal::service('entity_field.manager')->getFieldMapByFieldType('entity_reference_revisions');
    $fields = $map['node'];
    $results = [];
    foreach ($fields as $field_name => $field) {
      // We are only interested in configured fields, not base fields.
      $config = FieldStorageConfig::loadByName('node', $field_name);
      if ($config && $config->getSetting('target_type') == $target_type) {
        $ids = \Drupal::entityQuery('node')
          ->condition($field_name, $target_id)
          ->execute();
        if (!empty($ids)) {
          $id_vals = array_values($ids);
          $results = [
            'field_name' => $field_name,
            'node_id' => reset($id_vals),
          ];
          return $results;
        }
      }
    }
    return $results;
  }

  /**
   * Creates attribute for product.
   */
  public function createAttribute($name, $reference, $create = TRUE)
  {
    $attributeId = $this->entityTypeManager()->getStorage('commerce_product_attribute_value')->getQuery()
      ->condition('attribute', $reference)
      ->condition('name', $name)
      ->execute();

    if (!empty($attributeId)) {
      $attributeId = array_keys($attributeId);
      $attributeId = array_shift($attributeId);
      $attributeId = ProductAttributeValue::load($attributeId);
      return $attributeId;
    } else {
      $attributeId = ProductAttributeValue::create([
        'attribute' => $reference,
        'name' => $name,
      ]);
      if (!$create) {
        $attributeId->save();
      }
      return $attributeId;
    }
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc