Csv   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 41
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0
wmc 4
lcom 1
cbo 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A pass() 0 17 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