Skip to content

Commit

Permalink
Allow inserting pipes using a class name as matcher (#1664)
Browse files Browse the repository at this point in the history
  • Loading branch information
DerManoMann authored Oct 11, 2024
1 parent 3b6f380 commit f37bfd6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 13 deletions.
11 changes: 1 addition & 10 deletions src/Generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,16 +354,7 @@ public function addProcessor($processor, ?string $before = null): Generator
if (!$before) {
$processors->add($processor);
} else {
$matcher = function (array $pipes) use ($before) {
foreach ($pipes as $ii => $current) {
if ($current instanceof $before) {
return $ii;
}
}

return null;
};
$processors->insert($processor, $matcher);
$processors->insert($processor, $before);
}

$this->processorPipeline = $processors;
Expand Down
19 changes: 17 additions & 2 deletions src/Pipeline.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,25 @@ public function remove($pipe = null, ?callable $matcher = null): Pipeline
}

/**
* @param callable $matcher Callable to determine the position to insert (returned as `int`)
* @param callable|class-string $matcher used to determine the position to insert
* either an `int` from a callable or, in the case of `$matcher` being
* a `class-string`, the position before the first pipe of that class
*/
public function insert(callable $pipe, callable $matcher): Pipeline
public function insert(callable $pipe, $matcher): Pipeline
{
if (is_string($matcher)) {
$before = $matcher;
$matcher = function (array $pipes) use ($before) {
foreach ($pipes as $ii => $current) {
if ($current instanceof $before) {
return $ii;
}
}

return null;
};
}

$index = $matcher($this->pipes);
if (null === $index || $index < 0 || $index > count($this->pipes)) {
throw new OpenApiException('Matcher result out of range');
Expand Down
14 changes: 13 additions & 1 deletion tests/PipelineTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public function testRemoveClassString()
$this->assertEquals('c', $pipeline->process(''));
}

public function testInsert()
public function testInsertMatcher()
{
$pipeline = new Pipeline();

Expand All @@ -100,4 +100,16 @@ public function testInsert()
$pipeline->insert($this->pipe('y'), function ($pipes) { return 1; });
$this->assertEquals('xyz', $pipeline->process(''));
}

public function testInsertClassString()
{
$pipeline = new Pipeline();

$pipeline->add($this);
$pipeline->add($this->pipe('y'));
$this->assertEquals('xy', $pipeline->process(''));

$pipeline->insert($this->pipe('a'), __CLASS__);
$this->assertEquals('axy', $pipeline->process(''));
}
}

0 comments on commit f37bfd6

Please sign in to comment.