public function response($data, $totalCount = false, $query = false, $statusCode = 200) { if ($this->transformer) { $fractal = new Manager(); if ($totalCount === false) { $resource = new Item($data, $this->transformer); } else { $resource = new Collection($data, $this->transformer); } $response = $fractal->createData($resource)->toArray(); } else { $response = ['data' => $data]; } if ($totalCount !== false) { $response['totalCount'] = (int) $totalCount; } if ($query !== false) { $response['search'] = $query; } $response = json_encode($response, JSON_UNESCAPED_UNICODE); if ($response === false) { InternalServerError500::throwException("Response couldn't encoded as JSON"); } $this->app->response->status($statusCode); $this->app->response->body($response); }
public function sendCSVFile($csv, $outputName = 'file.csv', $columnNames = []) { $this->app->response->headers->set('Content-type', 'application/csv'); $this->app->response->headers->set('Content-Disposition', 'attachment; filename="' . $outputName . '"; modification-date="' . date('r') . '";'); if ($csv instanceof PDOStatement) { if (!($output = fopen('php://temp/maxmemory:' . 5 * 1024 * 1024, 'r+'))) { InternalServerError500::throwException("Can't open output stream"); } $flag = false; while ($row = $csv->fetch(PDO::FETCH_ASSOC)) { if (!$flag) { $columnNames = $columnNames ?: array_keys($row); fputcsv($output, $columnNames); $flag = true; } fputcsv($output, $row); } rewind($output); $return = stream_get_contents($output); $this->app->halt(200, $return); if (!fclose($output)) { InternalServerError500::throwException("Can't close php://output"); } } elseif (is_array($csv)) { if (!($output = fopen('php://temp/maxmemory:' . 5 * 1024 * 1024, 'r+'))) { InternalServerError500::throwException("Can't open output stream"); } if ($columnNames) { fputcsv($output, $columnNames); } foreach ($csv as $row) { fputcsv($output, $row); } rewind($output); $return = stream_get_contents($output); if (!fclose($output)) { InternalServerError500::throwException("Can't close php://output"); } $this->app->halt(200, $return); } else { $this->app->response->headers->set('Content-Length', strlen($csv)); $this->app->response->headers->set('Cache-Control', 'no-cache, must-revalidate'); $this->app->response->headers->set('Pragma', 'no-cache'); $this->app->response->headers->set('Expires', '0'); $this->app->halt(200, $csv); } $this->app->halt(200); }