MultispacedHeadersParser::getRows()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 7
nc 2
nop 0
1
<?php
2
3
namespace TraderInteractive\ColumnParser;
4
5
use TraderInteractive\ColumnParser\LineParser\StrictColumnWidthsParser;
6
use TraderInteractive\ColumnParser\HeaderParser\MultispacedParser;
7
8
/**
9
 * This parses a string where there are at least two spaces between the columns.  The first line in the string is the
10
 * headers.  Each header is expected to be separated by at least two spaces.  A single space is treated as interior
11
 * space of the header (i.e. multiple-word headers).
12
 */
13
class MultispacedHeadersParser implements HeaderColumnParser
14
{
15
    /**
16
     * @var array
17
     */
18
    private $lines;
19
20
    /**
21
     * @var string
22
     */
23
    private $headerLine;
24
25
    /**
26
     * @param string $contents The contents holding the data.
27
     */
28
    public function __construct(string $contents)
29
    {
30
        $allLines = array_filter(explode("\n", $contents));
31
        $this->lines = array_slice($allLines, 1);
32
        $this->headerLine = empty($allLines) ? '' : $allLines[0];
33
    }
34
35
    public function getRows() : array
36
    {
37
        $headers = (new MultispacedParser())->getMap($this->headerLine);
38
        $lineParser = new StrictColumnWidthsParser(array_values($headers));
39
40
        $rows = [];
41
        foreach ($this->lines as $line) {
42
            $rows[] = array_combine(array_keys($headers), $lineParser->getColumns($line));
43
        }
44
45
        return $rows;
46
    }
47
48
    public function getHeaders() : array
49
    {
50
        return array_keys((new MultispacedParser())->getMap($this->headerLine));
51
    }
52
}
53