1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Improved\IteratorPipeline; |
6
|
|
|
|
7
|
|
|
use Improved as i; |
8
|
|
|
use Improved\Iterator\CombineIterator; |
9
|
|
|
use Improved\IteratorPipeline\Traits\FilteringTrait; |
10
|
|
|
use Improved\IteratorPipeline\Traits\MappingTrait; |
11
|
|
|
use Improved\IteratorPipeline\Traits\SortingTrait; |
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
|
5 |
|
public function then(callable $callback, ...$args): self |
36
|
|
|
{ |
37
|
5 |
|
$copy = clone $this; |
38
|
|
|
|
39
|
5 |
|
if ($callback instanceof self) { |
40
|
2 |
|
$copy->steps = array_merge($this->steps, $callback->steps); |
41
|
|
|
} else { |
42
|
5 |
|
$copy->steps[] = [$callback, $args]; |
43
|
|
|
} |
44
|
|
|
|
45
|
5 |
|
return $copy; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* Create a new pipeline |
50
|
|
|
* |
51
|
|
|
* @param iterable $iterable |
52
|
|
|
* @return Pipeline |
53
|
|
|
*/ |
54
|
5 |
|
public function with(iterable $iterable): Pipeline |
55
|
|
|
{ |
56
|
5 |
|
$pipeline = new Pipeline($iterable); |
57
|
|
|
|
58
|
5 |
|
foreach ($this->steps as [$callback, $args]) { |
59
|
5 |
|
$pipeline->then($callback, ...$args); |
60
|
|
|
} |
61
|
|
|
|
62
|
5 |
|
return $pipeline; |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* Invoke the builder. |
67
|
|
|
* |
68
|
|
|
* @param iterable $iterable |
69
|
|
|
* @return array |
70
|
|
|
*/ |
71
|
3 |
|
public function __invoke(iterable $iterable): array |
72
|
|
|
{ |
73
|
3 |
|
return $this->with($iterable)->toArray(); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* Use another iterator as keys and the current iterator as values. |
79
|
|
|
* |
80
|
|
|
* @param iterable $keys Keys will be turned into an array. |
81
|
|
|
* @return static |
82
|
|
|
*/ |
83
|
1 |
|
public function setKeys(iterable $keys) |
84
|
|
|
{ |
85
|
|
|
$combine = function ($values, $keys) { |
86
|
1 |
|
return new CombineIterator($keys, $values); |
87
|
1 |
|
}; |
88
|
|
|
|
89
|
1 |
|
return $this->then($combine, i\iterable_to_array($keys)); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|