Csv::pass()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 1
dl 0
loc 17
rs 9.7
c 0
b 0
f 0
ccs 10
cts 10
cp 1
crap 3
1
<?php
2
declare(strict_types=1);
3
4
namespace SlayerBirden\DataFlow\Writer;
5
6
use SlayerBirden\DataFlow\DataBagInterface;
7
use SlayerBirden\DataFlow\IdentificationTrait;
8
use SlayerBirden\DataFlow\PipeInterface;
9
use SlayerBirden\DataFlow\Writer\Exception\WriteErrorException;
10
11
class Csv implements PipeInterface
12
{
13
    use IdentificationTrait;
14
    /**
15
     * @var string
16
     */
17
    private $id;
18
    /**
19
     * @var \SplFileObject
20
     */
21
    private $file;
22
    /**
23
     * @var array
24
     */
25
    private $header;
26
27 2
    public function __construct(string $id, \SplFileObject $file, array $header)
28
    {
29 2
        $this->id = $id;
30 2
        $this->file = $file;
31 2
        $this->header = $header;
32 2
    }
33
34 2
    public function pass(DataBagInterface $dataBag): DataBagInterface
35
    {
36 2
        $values = array_values(array_intersect_key($dataBag->toArray(), array_flip($this->header)));
37 2
        $return = $this->file->fputcsv($values);
38
39 2
        if ($return === false || $return === 0) {
40 1
            throw new WriteErrorException(
41 1
                sprintf(
42 1
                    'Failed to write into file %s, data: %s.',
43 1
                    $this->file->getFilename(),
44 1
                    json_encode($values)
45
                )
46
            );
47
        }
48
49 1
        return $dataBag;
50
    }
51
}
52