1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* This file is part of the Csv-Machine package. |
5
|
|
|
* |
6
|
|
|
* (c) Dan McAdams <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace RoadBunch\Csv\Header; |
13
|
|
|
|
14
|
|
|
|
15
|
|
|
use RoadBunch\Csv\Exceptions\InvalidHeaderArrayException; |
16
|
|
|
use RoadBunch\Csv\Formatters\FormatterInterface; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Class Header |
20
|
|
|
* |
21
|
|
|
* @author Dan McAdams |
22
|
|
|
* @package RoadBunch\Csv |
23
|
|
|
*/ |
24
|
|
|
class Header implements HeaderInterface |
25
|
|
|
{ |
26
|
|
|
/** @var array */ |
27
|
|
|
protected $columns; |
28
|
|
|
/** @var FormatterInterface[] */ |
29
|
|
|
protected $formatters = []; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Header constructor. |
33
|
|
|
* |
34
|
|
|
* @param array $columns array of strings of column names |
35
|
|
|
* |
36
|
|
|
* @throws InvalidHeaderArrayException |
37
|
|
|
*/ |
38
|
7 |
|
public function __construct(array $columns = []) |
39
|
|
|
{ |
40
|
7 |
|
foreach ($columns as $column) { |
41
|
3 |
|
if (!is_string($column)) { |
42
|
3 |
|
throw new InvalidHeaderArrayException('Columns must be array of (string)'); |
43
|
|
|
} |
44
|
|
|
} |
45
|
6 |
|
$this->columns = $columns; |
46
|
6 |
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param string $column |
50
|
|
|
* |
51
|
|
|
* @return void |
52
|
|
|
*/ |
53
|
3 |
|
public function addColumn(string $column) |
54
|
|
|
{ |
55
|
3 |
|
if (!in_array($column, $this->columns)) { |
56
|
3 |
|
$this->columns[] = $column; |
57
|
|
|
} |
58
|
3 |
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param FormatterInterface $formatter |
62
|
|
|
*/ |
63
|
1 |
|
public function addFormatter(FormatterInterface $formatter) |
64
|
|
|
{ |
65
|
1 |
|
$this->formatters[] = $formatter; |
66
|
1 |
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @return array |
70
|
|
|
*/ |
71
|
5 |
|
public function getColumns(): array |
72
|
|
|
{ |
73
|
5 |
|
$returnColumns = $this->columns; |
74
|
5 |
|
if (!empty($this->formatters)) { |
75
|
1 |
|
foreach ($this->formatters as $formatter) { |
76
|
1 |
|
$returnColumns = $formatter->format($returnColumns); |
77
|
|
|
} |
78
|
|
|
} |
79
|
5 |
|
return $returnColumns; |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|