-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMappedHeaderStrategy.php
More file actions
46 lines (38 loc) · 1.01 KB
/
MappedHeaderStrategy.php
File metadata and controls
46 lines (38 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
namespace SubjectivePHP\Csv;
use SplFileObject;
/**
* Header strategy that uses a map array to provide custom headers for a csv file.
*/
final class MappedHeaderStrategy implements HeaderStrategyInterface
{
/**
* @var array
*/
private $headerMap;
public function __construct(array $headerMap)
{
$this->headerMap = $headerMap;
}
public function getHeaders(SplFileObject $fileObject) : array
{
return array_values($this->headerMap);
}
public function isHeaderRow(array $row) : bool
{
$headers = array_keys($this->headerMap);
sort($row);
sort($headers);
return $row === $headers;
}
public function createDataRow(array $row) : array
{
$result = [];
$originalHeaders = array_keys($this->headerMap);
foreach ($originalHeaders as $index => $key) {
$newHeader = $this->headerMap[$key];
$result[$newHeader] = $row[$index] ?? null;
}
return $result;
}
}