You are here

public static function YamlFormResultsExportController::batchProcess in YAML Form 8

Batch API callback; Write the header and rows of the export to the export file.

Parameters

\Drupal\yamlform\YamlFormInterface $yamlform: The form.

\Drupal\Core\Entity\EntityInterface|null $source_entity: A form source entity.

array $export_options: An associative array of export options.

mixed|array $context: The batch current context.

File

src/Controller/YamlFormResultsExportController.php, line 270

Class

YamlFormResultsExportController
Controller routines for form submission export.

Namespace

Drupal\yamlform\Controller

Code

public static function batchProcess(YamlFormInterface $yamlform, EntityInterface $source_entity = NULL, array $export_options, &$context) {

  /** @var \Drupal\yamlform\YamlFormSubmissionExporterInterface $submission_exporter */
  $submission_exporter = \Drupal::service('yamlform_submission.exporter');
  $submission_exporter
    ->setYamlForm($yamlform);
  $submission_exporter
    ->setSourceEntity($source_entity);
  $submission_exporter
    ->setExporter($export_options);
  if (empty($context['sandbox'])) {
    $context['sandbox']['progress'] = 0;
    $context['sandbox']['current_sid'] = 0;
    $context['sandbox']['max'] = $submission_exporter
      ->getQuery()
      ->count()
      ->execute();

    // Store entity ids and not the actual yamlform or source entity in the
    // $context to prevent "The container was serialized" errors.
    // @see https://www.drupal.org/node/2822023
    $context['results']['yamlform_id'] = $yamlform
      ->id();
    $context['results']['source_entity_type'] = $source_entity ? $source_entity
      ->getEntityTypeId() : NULL;
    $context['results']['source_entity_id'] = $source_entity ? $source_entity
      ->id() : NULL;
    $context['results']['export_options'] = $export_options;
    $submission_exporter
      ->writeHeader();
  }

  // Write CSV records.
  $query = $submission_exporter
    ->getQuery();
  $query
    ->condition('sid', $context['sandbox']['current_sid'], '>');
  $query
    ->range(0, $submission_exporter
    ->getBatchLimit());
  $entity_ids = $query
    ->execute();
  $yamlform_submissions = YamlFormSubmission::loadMultiple($entity_ids);
  $submission_exporter
    ->writeRecords($yamlform_submissions);

  // Track progress.
  $context['sandbox']['progress'] += count($yamlform_submissions);
  $context['sandbox']['current_sid'] = $yamlform_submissions ? end($yamlform_submissions)
    ->id() : 0;
  $context['message'] = t('Exported @count of @total submissions...', [
    '@count' => $context['sandbox']['progress'],
    '@total' => $context['sandbox']['max'],
  ]);

  // Track finished.
  if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
    $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
  }
}