<commit_before><?php

namespace Edge\Mvc\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class OutputCsv extends AbstractPlugin
{
    /**
     * Convert an array to a CSV an output directly to the browser
     *
     * NB: This function is terminal
     *
     * @param array  $data
     * @param string $filename
     */
    public function __invoke(array $data, $filename)
    {
        $filename = rawurlencode($filename);

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=\"{$filename}\"");
        header("Expires: 0");
        header("Pragma: public");

        $fh = fopen('php://output', 'w');

        $header = false;

        foreach ($data as $row) {
            if (!$header) {
                fputcsv($fh, array_keys($row));
                $header = true;
            }

            fputcsv($fh, $row);
        }
        fclose($fh);

        exit;
    }
}<commit_msg>Throw exception for empty data<commit_after><?php

namespace Edge\Mvc\Controller\Plugin;

use Edge\Exception;
use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class OutputCsv extends AbstractPlugin
{
    /**
     * Convert an array to a CSV an output directly to the browser
     *
     * NB: This function is terminal
     *
     * @param array  $data
     * @param string $filename
     */
    public function __invoke(array $data, $filename)
    {
        if (empty($data)) {
            throw new Exception\RuntimeException('No data found for CSV output');
        }

        $filename = rawurlencode($filename);

        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: text/csv");
        header("Content-Disposition: attachment; filename=\"{$filename}\"");
        header("Expires: 0");
        header("Pragma: public");

        $fh = fopen('php://output', 'w');

        $header = false;

        foreach ($data as $row) {
            if (!$header) {
                fputcsv($fh, array_keys($row));
                $header = true;
            }

            fputcsv($fh, $row);
        }
        fclose($fh);

        exit;
    }
}
{'fraction_non_alphanumeric': 0.1373873873873874, 'fraction_numerical': 0.002702702702702703, 'mean_word_length': 2.084722222222222, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5002338', 'n_tokens_mistral': 657, 'n_tokens_neox': 629, 'n_words': 158}