CallableExtractor::getTraversable()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 13
rs 10
1
<?php
2
3
/*
4
 * This file is part of YaEtl
5
 *     (c) Fabrice de Stefanis / https://github.com/fab2s/YaEtl
6
 * This source file is licensed under the MIT license which you will
7
 * find in the LICENSE file or at https://opensource.org/licenses/MIT
8
 */
9
10
namespace fab2s\YaEtl\Extractors;
11
12
use fab2s\NodalFlow\NodalFlowException;
13
use fab2s\NodalFlow\Nodes\PayloadNodeAbstract;
14
15
/**
16
 * Class CallableExtractor
17
 */
18
class CallableExtractor extends PayloadNodeAbstract implements ExtractorInterface
19
{
20
    /**
21
     * The underlying executable or traversable Payload
22
     *
23
     * @var callable
24
     */
25
    protected $payload;
26
27
    /**
28
     * @var array
29
     */
30
    protected $nodeIncrements = [
31
        'num_records' => 'num_iterate',
32
        'num_extract' => 0,
33
    ];
34
35
    /**
36
     * @var iterable
37
     */
38
    protected $extracted;
39
40
    /**
41
     * CallableExtractorAbstract constructor.
42
     *
43
     * @param callable $payload
44
     * @param bool     $isAReturningVal
45
     *
46
     * @throws NodalFlowException
47
     */
48
    public function __construct(callable $payload, bool $isAReturningVal = true)
49
    {
50
        parent::__construct($payload, $isAReturningVal, true);
51
    }
52
53
    /**
54
     * @param mixed|null $param
55
     *
56
     * @return bool false in case no more records can be fetched
57
     */
58
    public function extract($param = null): bool
59
    {
60
        $extracted = \call_user_func($this->payload, $param);
61
62
        if (!is_iterable($extracted)) {
63
            return false;
64
        }
65
66
        $this->extracted = $extracted;
67
68
        return true;
69
    }
70
71
    /**
72
     * get the traversable to traverse within the Flow
73
     *
74
     * @param mixed $param
75
     *
76
     * @return \Generator
77
     */
78
    public function getTraversable($param = null): iterable
79
    {
80
        if (!$this->extract($param)) {
81
            // we still return an empty generator here
82
            return;
83
        }
84
85
        if ($this->getCarrier()) {
86
            $this->getCarrier()->getFlowMap()->incrementNode($this->getId(), 'num_extract');
87
        }
88
89
        foreach ($this->extracted as $record) {
90
            yield $record;
91
        }
92
    }
93
}
94