Completed
Push — master ( ed679a...7a298e )
by Andrew
02:18
created

StringReader::read()   D

Complexity

Conditions 9
Paths 4

Size

Total Lines 40
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 9.0076

Importance

Changes 6
Bugs 0 Features 1
Metric Value
dl 0
loc 40
ccs 21
cts 22
cp 0.9545
rs 4.909
c 6
b 0
f 1
cc 9
eloc 19
nc 4
nop 2
crap 9.0076
1
<?php
2
3
namespace CsvParser\Reader;
4
5
class StringReader implements ReaderInterface
6
{
7 11
    public static function read(\CsvParser\Parser $parser, $string)
8
    {
9 11
        $data = array();
10
11
        // shorten some vars for use later
12 11
        $d = $parser->fieldDelimiter;
13 11
        $e = $parser->fieldEnclosure;
14 11
        $l = $parser->lineDelimiter;
15
16
        // get headings and body (if \n line feeds, also support reading on carriage returns)
17 11
        list($headings, $body) = $l=="\n" ? preg_split('/[\n\r]/', $string, 2) : explode($l, $string, 2);
18
19
        // format array of headings/keys
20 11
        $headings = str_getcsv($headings, $d, $e);
21 11
        $numDelims = count($headings) -1; // number of field delims to find per line
22
23
        // tricky bit of regex, optionally matching the text enclosure (ref as \2 after first match),
24
        // and catches any content inside this enclosure, even if that would be the field or line delim
25
        // then repeating this match followed by the field delim for the number of columns we need (minus 1) and then the match again this time without the field delim
26
        // then splits the lines only when not in the enclosure
27 11
        preg_match_all('/(('. $e .')?[\s\S]*?\2?'. $d .'){'. $numDelims .'}\2?[\s\S]*?\2?('. ($l=="\n" ? '\n|\r' : $l) .'|$)/', $body, $lines);
28
29
        // any lines found? loop them
30 11
        if ( ! empty($lines) && ! empty($lines[0])) {
31 11
            foreach ($lines[0] as $i => $line) {
32 11
                if ($line==='') {
33
                    continue; // blank line...
34
                }
35 11
                $fields = str_getcsv($line, $d, $e);
36 11
                $data[$i] = array();
37
                // loop the headings to map to columns
38 11
                foreach ($headings as $j => $heading) {
39 11
                    $field = isset($fields[$j]) ? $fields[$j] : '';
40 11
                    $data[$i][$heading] = $field;
41 11
                }
42 11
            }
43 11
        }
44
45 11
        return new \CsvParser\Csv($data);
46
    }
47
}
48