Repository navigation
Expand file tree
/
Copy pathIterableBatchTask.php
More file actions
103 lines (85 loc) · 2.8 KB
/
Copy pathIterableBatchTask.php
File metadata and controls
103 lines (85 loc) · 2.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<?php
declare(strict_types=1);
/*
* This file is part of the CleverAge/ProcessBundle package.
*
* Copyright (c) Clever-Age
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace CleverAge\ProcessBundle\Task;
use CleverAge\ProcessBundle\Model\AbstractConfigurableTask;
use CleverAge\ProcessBundle\Model\FlushableTaskInterface;
use CleverAge\ProcessBundle\Model\IterableTaskInterface;
use CleverAge\ProcessBundle\Model\ProcessState;
use Psr\Log\LoggerInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* A Batch task that iterate on flush
* It's mainly an example task since it's not useful as-is, but the processInput method may allow custom overrides.
*/
class IterableBatchTask extends AbstractConfigurableTask implements FlushableTaskInterface, IterableTaskInterface
{
protected ?\SplQueue $outputQueue = null;
protected bool $flushMode = false;
public function __construct(
protected LoggerInterface $logger,
) {
}
#[\Override]
public function initialize(ProcessState $state): void
{
parent::initialize($state);
$this->outputQueue = new \SplQueue();
}
public function flush(ProcessState $state): void
{
$this->flushMode = true;
if ($this->outputQueue->isEmpty()) {
$state->setSkipped(true);
} else {
$state->setOutput($this->outputQueue->dequeue());
}
}
public function execute(ProcessState $state): void
{
$batchCount = $this->getOption($state, 'batch_count');
// Register new input
if (!$this->flushMode) {
$this->outputQueue->enqueue($this->processInput($state));
}
// Detect flushing
if (null !== $batchCount && ($this->outputQueue instanceof \SplQueue ? \count($this->outputQueue) : 0) >= $batchCount) {
$this->flushMode = true;
}
// Flush or skip
if ($this->flushMode) {
$state->setOutput($this->outputQueue->dequeue());
} else {
$state->setSkipped(true);
}
}
public function next(ProcessState $state): bool
{
// Stop flushing once over
if (($this->outputQueue instanceof \SplQueue ? \count($this->outputQueue) : 0) === 0) {
$this->flushMode = false;
}
return $this->flushMode;
}
protected function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'batch_count' => 10,
]);
$resolver->setAllowedTypes('batch_count', 'integer');
}
/**
* Override this method to add a custom processing behavior.
*/
protected function processInput(ProcessState $state): mixed
{
return $state->getInput();
}
}