UniqueFilterStep::execute()   A
last analyzed

Complexity

Conditions 6
Paths 7

Size

Total Lines 32
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 17
nc 7
nop 1
dl 0
loc 32
ccs 18
cts 18
cp 1
crap 6
rs 9.0777
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Darkilliant\ProcessBundle\Step;
6
7
use Darkilliant\ProcessBundle\Exception\NonUniqueException;
8
use Darkilliant\ProcessBundle\State\ProcessState;
9
use Symfony\Component\OptionsResolver\OptionsResolver;
10
11
class UniqueFilterStep extends AbstractConfigurableStep
12
{
13
    private $collector;
14
15 1
    public function configureOptionResolver(OptionsResolver $resolver): OptionsResolver
16
    {
17 1
        $resolver->setRequired(['fields', 'data', 'throw_error']);
18 1
        $resolver->setDefault('data', null);
19 1
        $resolver->setDefault('throw_error', false);
20
21 1
        return parent::configureOptionResolver($resolver);
22
    }
23
24 3
    public function execute(ProcessState $state)
25
    {
26 3
        $fields = $state->getOptions()['fields'];
27 3
        $data = $state->getOptions()['data'] ?: $state->getData();
28
29 3
        if (!is_array($data)) {
30 1
            return;
31
        }
32
33 2
        $collected = '';
34 2
        foreach ($fields as $field) {
35 2
            $collected .= '|'.$data[$field];
36
        }
37
38 2
        if (isset($this->collector[$collected])) {
39 2
            if ($state->getOption('throw_error')) {
40 1
                throw new NonUniqueException(
41 1
                    sprintf('skipped, this data is not unique (%s)', $collected)
42
                );
43
            }
44
45 1
            $state->warning(
46 1
                'skipped, this data is not unique',
47 1
                ['collected' => $collected]
48
            );
49
50 1
            $state->markIgnore();
51
52 1
            return;
53
        }
54
55 2
        $this->collector[$collected] = 1;
56 2
    }
57
58 1
    public function finalize(ProcessState $state)
59
    {
60 1
        $this->collector = [];
61 1
    }
62
}
63