-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSV.php
128 lines (113 loc) · 2.94 KB
/
CSV.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?php
namespace CleantalkSP\Common\Helpers;
use CleantalkSP\Common\Validate;
/**
* Class CSV
* Gather static functions designed to ease work with CSV
*
* @version 1.0.0
* @package CleantalkSP\Common\Helpers
* @author Cleantalk team (welcome@cleantalk.org)
* @copyright (C) CleanTalk team (http://cleantalk.org)
* @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html
* @see https://github.com/CleanTalk/security-malware-firewall
*/
class CSV
{
public static function sanitizeFromEmptyLines($buffer)
{
$buffer = (array) $buffer;
foreach ($buffer as $indx => &$line) {
$line = trim($line);
if ($line === '') {
unset($buffer[$indx]);
}
}
return $buffer;
}
/**
* Parse Comma-separated values
*
* @param $buffer
*
* @return false|string[]
*/
public static function parseCSV($buffer)
{
$buffer = explode("\n", $buffer);
$buffer = self::sanitizeFromEmptyLines($buffer);
foreach ($buffer as &$line) {
if ($line !== '') {
$line = str_getcsv($line, ',', '\'');
}
}
return $buffer;
}
/**
* Parse Newline-separated values
*
* @param $buffer
*
* @return false|string[]
*/
public static function parseNSV($buffer)
{
$buffer = str_replace(array("\r\n", "\n\r", "\r", "\n"), "\n", $buffer);
$buffer = explode("\n", $buffer);
return $buffer;
}
/**
* Pops line from buffer without formatting
*
* @param $csv
*
* @return false|string
*/
public static function popLineFromCSV(&$csv)
{
$pos = strpos($csv, "\n");
$line = substr($csv, 0, $pos);
$csv = substr_replace($csv, '', 0, $pos + 1);
return $line;
}
/**
* Pops line from the csv buffer and fromat it by map to array
*
* @param $csv
*
* @return array
*/
public static function getMapFromCSV(&$csv)
{
$line = static::popLineFromCSV($csv);
// Validate each element of the map
$map = array();
foreach (explode(',', $line) as $elem) {
if (Validate::isWord($elem)) {
$map[] = $elem;
} else {
return array('error' => 'CSV_BAD_MAP_ELEM');
}
}
return $map;
}
/**
* Pops line from the csv buffer and fromat it by map to array
*
* @param string $csv
* @param array $map
*
* @return array|false
*/
public static function popLineFromCSVToArray(&$csv, $map = array())
{
$line = trim(static::popLineFromCSV($csv));
$line = strpos($line, '\'') === 0
? str_getcsv($line, ',', '\'')
: explode(',', $line);
if ($map) {
$line = array_combine($map, $line);
}
return $line;
}
}