StrictColumnWidthsParser   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 40
c 0
b 0
f 0
wmc 4
lcom 1
cbo 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getColumns() 0 14 3
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