Completed
Pull Request — master (#27)
by jean
12:06
created

XmlExtractorStep::execute()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Darkilliant\ImportBundle\Step;
6
7
use Darkilliant\ImportBundle\Extractor\XmlExtractor;
8
use Darkilliant\ProcessBundle\State\ProcessState;
9
use Darkilliant\ProcessBundle\Step\AbstractConfigurableStep;
10
use Darkilliant\ProcessBundle\Step\IterableStepInterface;
11
use Symfony\Component\OptionsResolver\OptionsResolver;
12
13
class XmlExtractorStep extends AbstractConfigurableStep implements IterableStepInterface
14
{
15
    private $extractor;
16
17
    public function __construct(XmlExtractor $extractor)
18
    {
19
        $this->extractor = $extractor;
20
    }
21
22
    public function configureOptionResolver(OptionsResolver $resolver): OptionsResolver
23
    {
24
        $resolver->setRequired(['filepath', 'node_name']);
25
26
        return parent::configureOptionResolver($resolver);
27
    }
28
29
    public function execute(ProcessState $state)
30
    {
31
        $state->setIterator($this->extractor->extract(
32
            $state->getOptions()['filepath'],
33
            $state->getOptions()['node_name']
34
        ));
35
    }
36
37
    public function next(ProcessState $state)
38
    {
39
        $state->setData($state->getIterator()->current());
40
41
        $state->setContext('item_index', $state->getIterator()->key());
42
43
        $state->getIterator()->next();
44
    }
45
46
    public function getProgress(ProcessState $state)
47
    {
48
        return $state->getIterator()->key();
49
    }
50
51
    public function valid(ProcessState $state)
52
    {
53
        return $state->getIterator()->valid();
54
    }
55
56
    public function count(ProcessState $state)
57
    {
58
        $file = $state->getOptions()['filepath'];
59
        $node = '<'.$state->getOptions()['node_name'];
60
61
        if (!file_exists($file) || !is_file($file)) {
62
            return 0;
63
        }
64
65
        $cat = (false !== strpos($file, '.gz')) ? 'zcat' : 'cat';
66
        $count = `$cat $file | grep "$node" | wc -l`;
67
68
        if ((int) $count < 1) {
69
            return 0;
70
        }
71
72
        return (int) $count;
73
    }
74
}
75