Csv::write()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 4
dl 0
loc 12
ccs 6
cts 6
cp 1
crap 2
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * Derafu: Biblioteca PHP (Núcleo).
7
 * Copyright (C) Derafu <https://www.derafu.org>
8
 *
9
 * Este programa es software libre: usted puede redistribuirlo y/o modificarlo
10
 * bajo los términos de la Licencia Pública General Affero de GNU publicada por
11
 * la Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o
12
 * (a su elección) cualquier versión posterior de la misma.
13
 *
14
 * Este programa se distribuye con la esperanza de que sea útil, pero SIN
15
 * GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD
16
 * PARA UN PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública
17
 * General Affero de GNU para obtener una información más detallada.
18
 *
19
 * Debería haber recibido una copia de la Licencia Pública General Affero de GNU
20
 * junto a este programa.
21
 *
22
 * En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
23
 */
24
25
namespace Derafu\Lib\Core\Helper;
26
27
use League\Csv\CannotInsertRecord;
28
use League\Csv\Exception;
29
use League\Csv\Reader;
30
use League\Csv\Writer;
31
use LogicException;
32
use RuntimeException;
33
34
/**
35
 * Clase para manejar archivos CSV utilizando League\Csv.
36
 */
37
class Csv
38
{
39
    /**
40
     * Carga un CSV desde un string.
41
     *
42
     * @param string $csvString El contenido del CSV como string.
43
     * @param string $separator Separador a utilizar para diferenciar entre una
44
     * columna u otra.
45
     * @param string $textDelimiter Delimitador del texto para "rodear" cada
46
     * campo del CSV.
47
     * @return array El arreglo de datos del CSV.
48
     * @throws Exception Si ocurre un error durante la lectura del CSV.
49
     */
50 1
    public static function load(
51
        string $csvString,
52
        string $separator = ';',
53
        string $textDelimiter = '"'
54
    ): array {
55
        try {
56 1
            $csv = Reader::createFromString($csvString);
57 1
            $csv->setDelimiter($separator);
58 1
            $csv->setEnclosure($textDelimiter);
59 1
            return iterator_to_array($csv->getRecords());
60
        } catch (\Exception $e) {
61
            throw new RuntimeException(sprintf(
62
                'Error al leer el CSV desde el string: %s',
63
                $e->getMessage()
64
            ));
65
        }
66
    }
67
68
    /**
69
     * Lee un archivo CSV.
70
     *
71
     * @param string $file Archivo a leer.
72
     * @param string $separator Separador a utilizar para diferenciar entre una
73
     * columna u otra.
74
     * @param string $textDelimiter Delimitador del texto para "rodear" cada
75
     * campo del CSV.
76
     * @return array El arreglo de datos del archivo CSV.
77
     * @throws Exception Si ocurre un error durante la lectura del CSV.
78
     */
79 5
    public static function read(
80
        string $file,
81
        string $separator = ';',
82
        string $textDelimiter = '"'
83
    ): array {
84 5
        $csv = Reader::createFromPath($file, 'r');
85 4
        $csv->setDelimiter($separator);
86 4
        $csv->setEnclosure($textDelimiter);
87 4
        return iterator_to_array($csv->getRecords());
88
    }
89
90
    /**
91
     * Genera un CSV a partir de un arreglo y lo entrega como string.
92
     *
93
     * @param array $data Arreglo utilizado para generar el CSV.
94
     * @param string $separator Separador a utilizar.
95
     * @param string $textDelimiter Delimitador del texto.
96
     * @return string CSV generado como string.
97
     * @throws CannotInsertRecord Si ocurre un error durante la generación del
98
     * CSV.
99
     */
100 7
    public static function generate(
101
        array $data,
102
        string $separator = ';',
103
        string $textDelimiter = '"'
104
    ): string {
105 7
        $csv = Writer::createFromString('');
106 7
        $csv->setDelimiter($separator);
107 7
        $csv->setEnclosure($textDelimiter);
108 7
        $csv->insertAll($data);
109 7
        return $csv->toString();
110
    }
111
112
    /**
113
     * Escribe un CSV a un archivo desde un arreglo.
114
     *
115
     * @param array $data Arreglo utilizado para generar la planilla.
116
     * @param string $file Nombre del archivo que se debe generar.
117
     * @param string $separator Separador a utilizar.
118
     * @param string $textDelimiter Delimitador del texto.
119
     * @return void
120
     */
121 3
    public static function write(
122
        array $data,
123
        string $file,
124
        string $separator = ';',
125
        string $textDelimiter = '"'
126
    ): void {
127 3
        $csvString = self::generate($data, $separator, $textDelimiter);
128
129 3
        if (@file_put_contents($file, $csvString) === false) {
130 1
            throw new LogicException(sprintf(
131 1
                'No se pudo escribir el archivo CSV en la ruta: %s',
132 1
                $file
133 1
            ));
134
        }
135
    }
136
137
    /**
138
     * Envía un CSV al navegador web.
139
     *
140
     * @param array $data Arreglo utilizado para generar la planilla.
141
     * @param string $file Nombre del archivo.
142
     * @param string $separator Separador a utilizar.
143
     * @param string $textDelimiter Delimitador del texto.
144
     * @return void
145
     */
146 1
    public static function send(
147
        array $data,
148
        string $file,
149
        string $separator = ';',
150
        string $textDelimiter = '"',
151
        bool $sendHttpHeaders = true,
152
    ): void {
153 1
        $csvString = self::generate($data, $separator, $textDelimiter);
154
155 1
        if ($sendHttpHeaders) {
156
            header('Content-Type: text/csv');
157
            header('Content-Disposition: attachment; filename="' . $file . '.csv"');
158
            header('Pragma: no-cache');
159
            header('Expires: 0');
160
        }
161
162 1
        echo $csvString;
163
    }
164
}
165