1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ipl\IteratorPipeline; |
6
|
|
|
|
7
|
|
|
use Ipl\Iterator\CombineIterator; |
8
|
|
|
use Ipl\IteratorPipeline\Traits\FilteringTrait; |
9
|
|
|
use Ipl\IteratorPipeline\Traits\MappingTrait; |
10
|
|
|
use Ipl\IteratorPipeline\Traits\SortingTrait; |
11
|
|
|
use function Ipl\iterable_to_array; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* The `PipelineBuilder` can be used to create a blueprint for pipelines. |
15
|
|
|
*/ |
16
|
|
|
class PipelineBuilder |
17
|
|
|
{ |
18
|
|
|
use MappingTrait; |
19
|
|
|
use FilteringTrait; |
20
|
|
|
use SortingTrait; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
protected $steps = []; |
26
|
|
|
|
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Define the next step via a callback that returns an array or Traversable object. |
30
|
|
|
* |
31
|
|
|
* @param callable $callback |
32
|
|
|
* @param mixed ...$args |
33
|
|
|
* @return static |
34
|
|
|
*/ |
35
|
3 |
|
public function then(callable $callback, ...$args): self |
36
|
|
|
{ |
37
|
3 |
|
$copy = clone $this; |
38
|
3 |
|
$copy->steps[] = [$callback, $args]; |
39
|
|
|
|
40
|
3 |
|
return $copy; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Create a new pipeline |
45
|
|
|
* |
46
|
|
|
* @param iterable $iterable |
47
|
|
|
* @return Pipeline |
48
|
|
|
*/ |
49
|
3 |
|
public function with(iterable $iterable): Pipeline |
50
|
|
|
{ |
51
|
3 |
|
$pipeline = new Pipeline($iterable); |
52
|
|
|
|
53
|
3 |
|
foreach ($this->steps as [$callback, $args]) { |
54
|
3 |
|
$pipeline->then($callback, ...$args); |
55
|
|
|
} |
56
|
|
|
|
57
|
3 |
|
return $pipeline; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* Invoke the builder. |
62
|
|
|
* |
63
|
|
|
* @param iterable $iterable |
64
|
|
|
* @return array |
65
|
|
|
*/ |
66
|
2 |
|
public function __invoke(iterable $iterable): array |
67
|
|
|
{ |
68
|
2 |
|
return $this->with($iterable)->toArray(); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Use another iterator as keys and the current iterator as values. |
74
|
|
|
* |
75
|
|
|
* @param iterable $keys Keys will be turned into an array. |
76
|
|
|
* @return static |
77
|
|
|
*/ |
78
|
1 |
|
public function setKeys(iterable $keys) |
79
|
|
|
{ |
80
|
|
|
$combine = function ($values, $keys) { |
81
|
1 |
|
return new CombineIterator($keys, $values); |
82
|
1 |
|
}; |
83
|
|
|
|
84
|
1 |
|
return $this->then($combine, iterable_to_array($keys)); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|