Completed
Pull Request — master (#31)
by Chad
01:44
created

MappedHeaderStrategy::isHeaderRow()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 1
1
<?php
2
3
namespace SubjectivePHP\Csv;
4
5
use SplFileObject;
6
7
/**
8
 * Header strategy that uses a map array to provide custom headers for a csv file.
9
 */
10
final class MappedHeaderStrategy implements HeaderStrategyInterface
11
{
12
    /**
13
     * @var array
14
     */
15
    private $headerMap;
16
17
    public function __construct(array $headerMap)
18
    {
19
        $this->headerMap = $headerMap;
20
    }
21
22
    public function getHeaders(SplFileObject $fileObject) : array
23
    {
24
        return array_values($this->headerMap);
25
    }
26
27
    public function isHeaderRow(array $row) : bool
28
    {
29
        $headers = array_keys($this->headerMap);
30
        sort($row);
31
        sort($headers);
32
        return $row === $headers;
33
    }
34
35
    public function createDataRow(array $row) : array
36
    {
37
        $result = [];
38
        $originalHeaders = array_keys($this->headerMap);
39
        foreach ($originalHeaders as $index => $key) {
40
            $newHeader = $this->headerMap[$key];
41
            $result[$newHeader] = $row[$index] ?? null;
42
        }
43
44
        return $result;
45
    }
46
}
47