Failed Conditions
Push — master ( dcb275...c3bea1 )
by Arnold
02:34
created

PipelineBuilder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 69
ccs 15
cts 15
cp 1
rs 10
c 0
b 0
f 0
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A with() 0 9 2
A then() 0 6 1
A __invoke() 0 3 1
A setKeys() 0 7 1
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