StrictColumnWidthsParser::getColumns()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
namespace TraderInteractive\ColumnParser\LineParser;
4
5
/**
6
 * This splits a single line based on the pre-determined column widths.
7
 */
8
class StrictColumnWidthsParser
9
{
10
    /**
11
     * @var array
12
     */
13
    private $columnWidths;
14
15
    /**
16
     * Initialize the line parser.
17
     *
18
     * @param array $columnWidths The widths of each column in bytes.
19
     */
20
    public function __construct(array $columnWidths)
21
    {
22
        $this->columnWidths = $columnWidths;
23
    }
24
25
    /**
26
     * Fetches the data from the line using the column widths to split the data.
27
     *
28
     * The last column's width is ignored and the full width of the line is used.  Each column is trimmed of whitespace.
29
     *
30
     * @param string $line The line of data.
31
     * @return array The data by column.
32
     */
33
    public function getColumns(string $line) : array
34
    {
35
        $columns = [];
36
37
        $columnStart = 0;
38
        $lastColumnIndex = count($this->columnWidths) - 1;
39
        foreach ($this->columnWidths as $i => $columnWidth) {
40
            $actualWidth = $i === $lastColumnIndex ? strlen($line) : $columnWidth;
41
            $columns[] = trim(substr($line, $columnStart, $actualWidth));
42
            $columnStart += $actualWidth;
43
        }
44
45
        return $columns;
46
    }
47
}
48