Repository navigation
Expand file tree
/
Copy pathAbstractIterableOutputTask.php
More file actions
94 lines (78 loc) · 2.67 KB
/
Copy pathAbstractIterableOutputTask.php
File metadata and controls
94 lines (78 loc) · 2.67 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
<?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\IterableTaskInterface;
use CleverAge\ProcessBundle\Model\ProcessState;
use Iterator;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* Base class to handle output iterations.
*/
abstract class AbstractIterableOutputTask extends AbstractConfigurableTask implements IterableTaskInterface
{
protected ?\Iterator $iterator = null;
public function execute(ProcessState $state): void
{
$this->handleIteratorFromInput($state);
$iterator = $this->iterator;
if (!$iterator instanceof \Iterator) {
throw new \LogicException('No iterator initialized');
}
if ($iterator->valid()) {
$state->addErrorContextValue('iterator_key', $iterator->key());
$state->setOutput($iterator->current());
} else {
$state->setSkipped(true);
$this->iterator = null;
}
}
/**
* Moves the internal pointer to the next element,
* return true if the task has a next element
* return false if the task has terminated it's iteration.
*/
public function next(ProcessState $state): bool
{
if (!$this->iterator instanceof \Iterator) {
return false;
}
$this->iterator->next();
$state->removeErrorContext('iterator_key');
if (!$this->iterator->valid()) {
// Reset the iterator to allow the following iteration
$this->iterator = null;
return false;
}
return true;
}
/**
* Create or recreate an iterator from input.
*/
protected function handleIteratorFromInput(ProcessState $state): void
{
if ($this->iterator instanceof \Iterator) {
if ($this->iterator->valid()) {
return; // No action needed, execution is in progress
}
// Cleanup invalid iterator => prepare for new iteration cycle
$this->iterator = null;
}
$this->iterator = $this->initializeIterator($state);
}
/**
* Allow to not implement this method, not required by most tasks, removing inheritance would break back-compat.
*/
protected function configureOptions(OptionsResolver $resolver): void
{
}
abstract protected function initializeIterator(ProcessState $state): \Iterator;
}