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

HeaderStrategy::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
namespace SubjectivePHP\Csv;
4
5
use SplFileObject;
6
7
final class HeaderStrategy implements HeaderStrategyInterface
8
{
9
    /**
10
     * @var callable
11
     */
12
    private $getHeadersCallable;
13
14
    private function __construct(callable $getHeadersCallable)
15
    {
16
        $this->getHeadersCallable = $getHeadersCallable;
17
    }
18
19
    /**
20
     * Create header strategy which derives the headers from the first line of the file.
21
     *
22
     * @return HeaderstrategyInterface
23
     */
24
    public static function derive() : HeaderStrategyInterface
25
    {
26
        return new DeriveHeaderStrategy();
27
    }
28
29
    /**
30
     * Create header strategy which uses the provided headers array.
31
     *
32
     * @return HeaderstrategyInterface
33
     */
34
    public static function provide(array $headers) : HeaderStrategyInterface
35
    {
36
        return new self(
37
            function () use ($headers) : array {
38
                return $headers;
39
            }
40
        );
41
    }
42
43
    /**
44
     * Create header strategy which generates a numeric array whose size is the number of columns in the given file.
45
     *
46
     * @return HeaderstrategyInterface
47
     */
48
    public static function none() : HeaderStrategyInterface
49
    {
50
        return new self(
51
            function (SplFileObject $fileObject) : array {
52
                $firstRow = $fileObject->fgetcsv();
53
                $headers = array_keys($firstRow);
54
                $fileObject->rewind();
55
                return $headers;
56
            }
57
        );
58
    }
59
60
    /**
61
     * Extracts headers from the given SplFileObject.
62
     *
63
     * @param SplFileObject $fileObject The delimited file containing the headers.
64
     *
65
     * @return array
66
     */
67
    public function getHeaders(SplFileObject $fileObject) : array
68
    {
69
        return ($this->getHeadersCallable)($fileObject);
70
    }
71
}
72