CsvExtractor::extract()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 3
nop 4
dl 0
loc 15
ccs 12
cts 12
cp 1
crap 5
rs 9.6111
c 0
b 0
f 0
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