You are here

public function ExportAnalyticsController::exportAsCsv in Apigee Edge 8

Exports as CSV and downloads the requested analytics data.

Parameters

int $data_id: The ID of the stored analytics data.

Return value

\Symfony\Component\HttpFoundation\Response The response object.

File

src/Controller/ExportAnalyticsController.php, line 82

Class

ExportAnalyticsController
Defines a controller for exporting and downloading analytics data.

Namespace

Drupal\apigee_edge\Controller

Code

public function exportAsCsv($data_id) : Response {
  $analytics = $this->store
    ->get($data_id);
  $file_name = "{$analytics['stats']['data'][0]['identifier']['values'][0]}_{$analytics['stats']['data'][0]['metric'][0]['name']}_analytics.csv";
  $data = [];

  // Write out the data.
  if (array_key_exists('TimeUnit', $analytics) && is_array($analytics['TimeUnit'])) {
    for ($i = 0; $i < count($analytics['TimeUnit']); $i++) {
      $data[] = [
        $this
          ->t('Date')
          ->render() => new DrupalDateTime('@' . $analytics['TimeUnit'][$i] / 1000),
        $analytics['metric']
          ->render() => $analytics['stats']['data'][0]['metric'][0]['values'][$i],
      ];
    }
  }
  $csv_encoder = new CsvEncoder();
  $file_content = $csv_encoder
    ->encode($data, 'csv');
  $response = new Response($file_content);
  $disposition = $response->headers
    ->makeDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file_name);
  $response->headers
    ->set('Content-Disposition', $disposition);
  return $response;
}