You are here

protected function GdprTasksSarWorker::build in General Data Protection Regulation 7

Build the export files.

Parameters

\GDPRTask $task: The task.

1 call to GdprTasksSarWorker::build()
GdprTasksSarWorker::initialise in modules/gdpr_tasks/src/Plugin/QueueWorker/GdprTasksSarWorker.php
Initialise our request.

File

modules/gdpr_tasks/src/Plugin/QueueWorker/GdprTasksSarWorker.php, line 76

Class

GdprTasksSarWorker
Queue worker callback for processing SARs requests.

Code

protected function build(\GDPRTask $task) {
  $wrapper = $task
    ->wrapper();
  $field_info = field_info_field('gdpr_tasks_sar_export');
  $directory = $field_info['settings']['uri_scheme'] . '://gdpr_sars/';
  $directory .= basename($task
    ->wrapper()->gdpr_tasks_sar_export->file->url
    ->value(), '.zip');

  // Gather our entities.
  // @todo: Move this inline.
  $all_data = gdpr_tasks_collect_rta_data($task
    ->getOwner());

  // Build our export files.
  $csvs = array();
  foreach ($all_data as $plugin_id => $data) {
    if ($plugin_id == '_assets') {
      $wrapper->gdpr_tasks_sar_export_assets = $data;
      continue;
    }

    // Build the headers if required.
    if (!isset($csvs[$data['file']]['_header'][$data['plugin_name']])) {
      $csvs[$data['file']]['_plugin_id'][$data['plugin_name']] = $data['plugin_name'];
      $csvs[$data['file']]['_header'][$data['plugin_name']] = $data['label'];
    }

    // Initialise and fill out the row to make sure things come in a
    // consistent order.
    if (!isset($csvs[$data['file']][$data['row_id']])) {
      $csvs[$data['file']][$data['row_id']] = array();
    }
    $csvs[$data['file']][$data['row_id']] += array_fill_keys(array_keys($csvs[$data['file']]['_header']), '');

    // Put our piece of information in place.
    $csvs[$data['file']][$data['row_id']][$data['plugin_name']] = $data['value'];
  }

  // Gather existing files.
  $files = array();
  foreach ($wrapper->gdpr_tasks_sar_export_parts as $item) {
    $filename = basename($item->file->url
      ->value(), '.csv');
    $files[$filename] = $item->file
      ->value();
  }

  // Write our CSV files.
  foreach ($csvs as $filename => $data) {
    if (!isset($files[$filename])) {

      // Create an empty file.
      $file = file_save_data('', "{$directory}/{$filename}.csv", FILE_EXISTS_REPLACE);

      // Track the file.
      $task->gdpr_tasks_sar_export_parts[LANGUAGE_NONE][] = array(
        'fid' => $file->fid,
        'display' => TRUE,
      );
    }
    else {
      $file = $files[$filename];
    }
    $this
      ->writeCsv($file->uri, $data);

    // Clear file cache so filesize can be recalculated.
    clearstatcache(TRUE, $file->uri);
    file_save($file);
  }

  // Update the status.
  $task->status = 'reviewing';
  $task
    ->save();
}