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

HeaderStrategy   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 0

Importance

Changes 0
Metric Value
wmc 5
lcom 2
cbo 0
dl 0
loc 71
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A derive() 0 10 1
A provide() 0 8 1
A none() 0 11 1
A getHeaders() 0 4 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 self(
27
            function (SplFileObject $fileObject) : array {
28
                $row = $fileObject->fgetcsv();
29
                $fileObject->rewind();
30
                return $row;
31
            }
32
        );
33
    }
34
35
    /**
36
     * Create header strategy which uses the provided headers array.
37
     *
38
     * @return HeaderstrategyInterface
39
     */
40
    public static function provide(array $headers) : HeaderStrategyInterface
41
    {
42
        return new self(
43
            function (SplFileObject $fileObject) use ($headers) : array {
0 ignored issues
show
Unused Code introduced by
The parameter $fileObject is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
44
                return $headers;
45
            }
46
        );
47
    }
48
49
    /**
50
     * Create header strategy which generates a numeric array whose size is the number of columns in the given file.
51
     *
52
     * @return HeaderstrategyInterface
53
     */
54
    public static function none() : HeaderStrategyInterface
55
    {
56
        return new self(
57
            function (SplFileObject $fileObject) : array {
58
                $firstRow = $fileObject->fgetcsv();
59
                $headers = array_keys($firstRow);
60
                $fileObject->rewind();
61
                return $headers;
62
            }
63
        );
64
    }
65
66
    /**
67
     * Extracts headers from the given SplFileObject.
68
     *
69
     * @param SplFileObject $fileObject The delimited file containing the headers.
70
     *
71
     * @return array
72
     */
73
    public function getHeaders(SplFileObject $fileObject) : array
74
    {
75
        return ($this->getHeadersCallable)($fileObject);
76
    }
77
}
78