CsvExtractor   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 38
ccs 21
cts 21
cp 1
rs 10
c 0
b 0
f 0
wmc 9

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A isValidLine() 0 3 2
A slugify() 0 5 1
A extract() 0 15 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Darkilliant\ImportBundle\Extractor;
6
7
use Cocur\Slugify\Slugify;
8
9
/**
10
 * @internal
11
 */
12
class CsvExtractor implements ExtractorInterface
13
{
14
    private $slugify;
15
16 2
    public function __construct(Slugify $slugify)
17
    {
18 2
        $this->slugify = $slugify;
19 2
    }
20
21 2
    public function extract(string $csvFilePath, string $delimiter = ',', array $columsNames = null, bool $skipFirstLine = true): \Traversable
22
    {
23 2
        $csvFileObjects = new \SplFileObject($csvFilePath);
24 2
        $csvFileObjects->setFlags((\SplFileObject::READ_CSV | \SplFileObject::SKIP_EMPTY | \SplFileObject::DROP_NEW_LINE | \ SplFileObject::READ_AHEAD));
25 2
        $csvFileObjects->setCsvControl($delimiter);
26
27 2
        $arrayKeys = array_map([$this, 'slugify'], $columsNames ?? (array) $csvFileObjects->current());
28 2
        $arrayKeys = array_map('trim', $arrayKeys);
29
30 2
        foreach ($csvFileObjects as $loopIndex => $csvFileObjectRow) {
31 2
            $currentData = (array) $csvFileObjectRow;
32 2
            if ((!$skipFirstLine || $csvFileObjects->key() > 0) && true === $this->isValidLine($currentData)) {
33 2
                $currentData = array_map('trim', $currentData);
34 2
                $arrayToYield = array_combine($arrayKeys, $currentData);
35 2
                yield $loopIndex => $arrayToYield;
36
            }
37
        }
38 2
    }
39
40 2
    private function slugify($key)
41
    {
42 2
        $key = str_replace('/', '_', $key);
43
44 2
        return $this->slugify->slugify($key, '_');
45
    }
46
47 2
    private function isValidLine(array $csvFileObjectRow): bool
48
    {
49 2
        return (count(array_keys($csvFileObjectRow, '')) === count($csvFileObjectRow)) ? false : true;
50
    }
51
}
52