content_csv_export_import-1.0.1-beta2/src/Form/ExportContentByIdsForm.php

src/Form/ExportContentByIdsForm.php
<?php

namespace Drupal\content_csv_export_import\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\content_csv_export_import\ContentExportImportCoreService;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\node\Entity\Node;

/**
 * Class ExportContentByIdsForm.
 */
class ExportContentByIdsForm extends FormBase {

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

  /**
   * Smart importer service.
   *
   * @var \Drupal\content_csv_export_import\Plugin\ContentExportImportCoreService
   */
  protected $contentDataExportService;
  /**
   * Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * Entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * CSVExportForm constructor.
   */
  public function __construct(Connection $connection,
                              ContentExportImportCoreService $contentDataExportService,
                              ConfigFactory $configFactory,
                              EntityTypeManagerInterface $entityTypeManager
                              ) {
    $this->database = $connection;
    $this->contentExportImportService = $contentDataExportService;
    $this->configFactory = $configFactory;
    $this->entityTypeManager = $entityTypeManager;

  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'export_node_by_ids_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $route_name = \Drupal::routeMatch()->getRouteName();
    if ($route_name == 'system.admin_content') {
      $form['ids_seperated_by_comma'] = [
        '#type' => 'hidden',
      ];
      $form['entity_type'] = [
        '#type' => 'hidden',
        '#value' => 'node',
      ];
    }
    elseif ($route_name == 'entity.commerce_product.collection') {
      $form['ids_seperated_by_comma'] = [
        '#type' => 'hidden',
      ];
      $form['entity_type'] = [
        '#type' => 'hidden',
        '#value' => 'commerce_product',
      ];
    }
    else {
      $form['ids_seperated_by_comma'] = [
        '#type' => 'textarea',
      ];
      $form['entity_type'] = [
        '#type' => 'radios',
        '#title' => $this->t('Choose entity type'),
        '#options' => [
          'node' => $this->t('Node'),
          'commerce_product' => $this->t('Product'),
        ],
        '#required' => TRUE,
      ];
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Export the selected to CSV'),
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state->getValues() as $key => $value) {
      // @todo Validate fields.
    }
    parent::validateForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $id_values = $form_state->getValue('ids_seperated_by_comma');
    $ids = array_map('intval', explode(',', $id_values));
    $entities = [];
    $fileNames = [];
    $random_string = uniqid();
    $entity_type = $form_state->getValue('entity_type');
    // kint($form_state->getValues());
    // kint($entity_type);
    // exit;
    $batch = [
      'title' => $this->t('Exporting selected entities'),
      'init_message' => $this->t('Beginning...'),
      'progress_message' => $this->t('exported @current out of @total entities'),
      'error_message' => $this->t('Something went wrong'),
      'progressive' => FALSE,
      'operations' => [],
      'finished' => [$this, 'exportEntitiesFinishedCallback'],
    ];
    // Grouping ids by product types.
    if ($entity_type == 'node') {
      $db_table = 'node';
      $db_field = 'nid';
      $folderNameType = 'node';
    }
    else {
      $db_table = 'commerce_product';
      $db_field = 'product_id';
      $folderNameType = 'product';
    }
    // kint($ids);
    foreach ($ids as $id) {
      $id = trim($id);
      $query = $this->database->select($db_table)
        ->fields($db_table, ['type'])
        ->condition($db_table . '.' . $db_field, $id, '=')
        ->execute()->fetchAll();
      foreach ($query as $query_result) {
        $entities[$query_result->type][] = $id;
      }
    }
    // Initialising Batch process.
    foreach ($entities as $bundle => $entity_ids) {
      $fields = $this->contentExportImportService->getFieldDefinition(FALSE, $bundle, $entity_type, 'create');
      // kint($fields);
      $field_value = [];
      $header = [];
      $dest_folderName = 'export-' . str_replace('_', '-', $folderNameType) . '-' . $random_string;
      // Image folder and download folder creation.
      $default_export_folder = 'public://export-' . $folderNameType;
      if (!is_dir($default_export_folder)) {
        \Drupal::service('file_system')->mkdir($default_export_folder, 0755);
      }
      \Drupal::service('file_system')->mkdir('public://export-' . $folderNameType . '/' . $dest_folderName, 0755);
      \Drupal::service('file_system')->mkdir('public://export-' . $folderNameType . '/' . $dest_folderName . '/inline-images', 0755);
      // Download folder setup.
      $folderName = 'public://export-' . $folderNameType . '/' . $dest_folderName;
      // CSV File name.
      $fileName = 'export-' . $folderNameType . '-' . str_replace(' ', '-', $bundle) . '-' . $random_string . '.csv';
      $fileNames[] = $fileName;
      // Prepare file to write.
      $absolute_path = \Drupal::service('file_system')->realpath('public://export-' . $folderNameType . '/' . $dest_folderName . '/' . $fileName);
      $file = fopen($absolute_path, 'w');
      // Prepare header.
      foreach ($fields[$folderNameType] as $entity_header) {
        if (!in_array($entity_header['label'], $header)) {
          $header[] = $entity_header['label'];
        }
      }
      // kint($fields['paragraph']);exit;.
      if ($folderNameType == 'node' && isset($fields['paragraph'])) {
        foreach ($fields['paragraph'] as $paragraphBundle => $paragraph_headers) {
          foreach ($paragraph_headers as $paragraph_header) {
            if (!in_array($paragraph_header['label'], $header)) {
              $header[] = $paragraph_header['label'];
            }
          }
        }
      }
      // kint($header);
      if ($folderNameType == 'product') {
        foreach ($fields['variation'] as $variation_header) {
          if (!in_array($variation_header['label'], $header)) {
            $header[] = $variation_header['label'];
          }
        }
      }

      fputcsv($file, $header);
      fputcsv($file, ['']);
      fclose($file);

      foreach ($entity_ids as $entity_id) {
        // *
        $batch['operations'][] = [
        [
          $this,
          'exportEntities',
        ],
        [
          $fields,
          $entity_id,
          $absolute_path,
          $folderName,
          $entity_type,
        ],
        ];
        // */
        /*
        $context['results'] = [];
        $this->exportEntities( $fields,
        $entity_id,
        $absolute_path,
        $folderName,
        $entity_type, $context);exit;
        exit;
         */
      }

    }
    batch_set($batch);
  }

  /**
   *
   */
  public function exportEntities($field_definitions, $entity_id, $fileName, $folderName, $entity_type, &$context) {
    $file = fopen($fileName, 'a');
    $entity_data = [];
    $context['results']['folderName'] = $folderName;
    if ($entity_type == 'commerce_product') {
      $type = 'product';
      $product_temp_data = [];
      $product_temp_data['product'] = $entity_id;

      $variation_query = $this->database->query('SELECT variation_id FROM commerce_product_variation_field_data WHERE product_id=' . $entity_id)
        ->fetchAll();
      foreach ($variation_query as $variation) {
        $product_temp_data['variation'][] = $variation->variation_id;
      }
      $entity_data[] = $product_temp_data;
      // kint($entity_data);exit;
    }
    else {
      $type = 'node';
      $temp_data = [];
      $temp_data['node'] = $entity_id;
      $moduleHandler = \Drupal::service('module_handler');
      if ($moduleHandler->moduleExists('paragraphs')) {
        $paragraph_query = $this->database->query('SELECT id,type FROM paragraphs_item_field_data WHERE status = 1 and parent_id=' . $entity_id)
        ->fetchAll();
      }
      else {
        $paragraph_query = [];
      }

      $paragraph_field_names = [];
      $tempParaIds = [];
      foreach ($paragraph_query as $paragraph) {
        $pid = $paragraph->id;
        $getAssociatedFieldName = $this->contentExportImportService->getNodeAttachedToParagraph($pid);
        if (!empty($getAssociatedFieldName)) {
          $tempParaIds[$paragraph->id] = $paragraph->type;
          $paragraph_field_names[] = $getAssociatedFieldName['field_name'];
          $bundles[] = $paragraph->type;
        }
      }
      $temp_data['paragraphs'] = [];
      $paragraph_field_names = array_unique($paragraph_field_names);
      $order_para_ids = [];
      foreach ($paragraph_field_names as $para_field_name) {
        $entity_load = Node::load($entity_id);
        foreach ($entity_load->get($para_field_name)->getValue() as $paragraph_id_data) {
          $temp_data['paragraphs'][$paragraph_id_data['target_id']] = $tempParaIds[$paragraph_id_data['target_id']];
        }
      }
      if (!empty($bundles)) {
        $bundles = array_unique($bundles);
      }
      $entity_data[] = $temp_data;
    }

    $empty_entity = array_fill(0, count($field_definitions[$type]), '');
    $rows = [];
    foreach ($entity_data as $entity_datum) {
      $first = TRUE;
      if ($entity_type == 'commerce_product') {
        foreach ($entity_datum['variation'] as $variation_id) {
          if ($first) {
            $temp_row = $this->contentExportImportService->exportMultipleFields($entity_type, $entity_datum['product'], $field_definitions[$type], $folderName);
            $first = FALSE;
          }
          else {
            $temp_row = $empty_entity;
          }
          $temp_row = array_merge($temp_row, $this->contentExportImportService->exportMultipleFields('commerce_product_variation', $variation_id, $field_definitions['variation'], $folderName));
          $rows[] = $temp_row;
        }
      }
      else {
        $bundleCount = (isset($field_definitions['paragraph'])) ? count($field_definitions['paragraph']) : 0;
        if ($bundleCount > 1) {
          foreach ($field_definitions['paragraph'] as $bundle => $bundleFieldData) {
            $empty_bundle_entity[$bundle] = array_fill(0, count($bundleFieldData), '');
          }
        }
        $bundleNames = (isset($field_definitions['paragraph'])) ? array_keys($field_definitions['paragraph']) : [];

        $first = TRUE;
        $firstBundle = TRUE;
        $firstBundle = '';
        if (!empty($entity_datum['paragraphs'])) {
          foreach ($entity_datum['paragraphs'] as $paragraph_id => $paragraph_type) {
            if ($first) {
              $temp_row = $this->contentExportImportService->exportMultipleFields('node', $entity_datum['node'], $field_definitions['node'], $folderName);
              // kint($temp_row);exit;
              $first = FALSE;
            }
            else {
              $temp_row = $empty_entity;
              foreach ($bundleNames as $paragraphBundle) {
                if ($paragraphBundle == $paragraph_type) {
                  break;
                }
                else {
                  $temp_row = array_merge($temp_row, array_fill(0, count($field_definitions['paragraph'][$paragraphBundle]), ''));
                }
              }
            }
            $temp_row = array_merge($temp_row, $this->contentExportImportService->exportMultipleFields('paragraph', $paragraph_id, $field_definitions['paragraph'][$paragraph_type], $folderName));
            $rows[] = $temp_row;
          }
        }
        else {
          $temp_row = $this->contentExportImportService->exportMultipleFields('node', $entity_datum['node'], $field_definitions['node'], $folderName);
          $rows[] = $temp_row;
        }
      }
    }
    // kint($rows);exit;
    // \Drupal::logger('product')->debug('<pre><code>' . print_r($rows, TRUE) . '</code></pre>');.
    foreach ($rows as $row) {
      fputcsv($file, $row);
    }
    fclose($file);
  }

  /**
   * Creates and Downloads the zip folder.
   *
   * @param mixed $success
   * @param mixed $results
   * @param mixed $operations
   */
  public static function exportEntitiesFinishedCallback($success, $results, $operations) {

    if (!empty($results)) {
      $contents_folder = $results['folderName'];
      $folderName = $results['folderName'] . '.zip';
      $zip = new \ZipArchive();
      $zip_abs_path = \Drupal::service('file_system')->realpath($folderName);
      $zip_contents_path = \Drupal::service('file_system')->realpath($contents_folder);
      $only_folder_name = str_replace('.zip', '', basename($zip_contents_path));

      if ($zip->open($zip_abs_path, \ZipArchive::CREATE) === TRUE) {
        // Store the path into the variable.
        $files = new \RecursiveIteratorIterator(
          new \RecursiveDirectoryIterator($zip_contents_path),
          \RecursiveIteratorIterator::LEAVES_ONLY
        );
        foreach ($files as $name => $file) {
          // Skip directories (they would be added automatically)
          $filePath = $file->getRealPath();
          $relativePath = substr($filePath, strlen($zip_contents_path) + 1);

          if (!$file->isDir()) {
            // Add current file to archive.
            $zip->addFile($filePath, $relativePath);
          }
          else {
            if ($relativePath !== FALSE) {
              $zip->addEmptyDir($relativePath);
            }
          }
        }
        $zip->close();
      }

      // Downloading zip file.
      header('Content-disposition: attachment; filename=' . basename($folderName));
      header('Content-type: application/zip');
      readfile($zip_abs_path);
      exit;

    }
  }

}

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

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