diff --git a/src/FixerGenerator.php b/src/FixerGenerator.php index 4ef50fa..20625bd 100644 --- a/src/FixerGenerator.php +++ b/src/FixerGenerator.php @@ -24,7 +24,15 @@ */ final class FixerGenerator implements \IteratorAggregate { - private function __construct(private string $path, private string $vendor) {} + /** + * @var list<\IteratorAggregate> + */ + private array $fixerIterators = []; + + private function __construct( + private string $path, + private string $vendor, + ) {} /** * @throws \RuntimeException @@ -50,6 +58,18 @@ public static function create(string $path, string $vendor): self return new self($path, $vendor); } + /** + * Merge other iterators that yield `FixerInterface` custom fixers. + * + * @param \IteratorAggregate ...$fixerIterators + */ + public function mergeWith(\IteratorAggregate ...$fixerIterators): self + { + $this->fixerIterators = array_values($fixerIterators); + + return $this; + } + /** * @return \Traversable */ @@ -63,7 +83,16 @@ public function getIterator(): \Traversable ->sortByName() ; - $fixers = array_filter(array_map( + $otherFixers = []; + + foreach ($this->fixerIterators as $fixerIterator) { + $otherFixers = array_merge( + $otherFixers, + iterator_to_array($fixerIterator->getIterator(), false), + ); + } + + $fixers = array_values(array_filter(array_map( function (SplFileInfo $file): object { $fixer = \sprintf( '%s\\%s%s%s', @@ -76,8 +105,8 @@ function (SplFileInfo $file): object { return new $fixer(); }, iterator_to_array($finder, false), - ), static fn(object $fixer): bool => $fixer instanceof FixerInterface); + ), static fn(object $fixer): bool => $fixer instanceof FixerInterface)); - yield from $fixers; + yield from array_merge($fixers, $otherFixers); } } diff --git a/tests/FixerGeneratorTest.php b/tests/FixerGeneratorTest.php index 72ce57a..0cff7df 100644 --- a/tests/FixerGeneratorTest.php +++ b/tests/FixerGeneratorTest.php @@ -14,6 +14,7 @@ namespace Nexus\CsConfig\Tests; use Nexus\CsConfig\FixerGenerator; +use PhpCsFixer\Fixer\FixerInterface; use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -53,4 +54,15 @@ public function testTraversableReturnedAreInstancesOfFixerInterface(): void $generator = FixerGenerator::create('vendor/friendsofphp/php-cs-fixer/src/Fixer', 'PhpCsFixer\\Fixer'); self::assertNotEmpty(iterator_to_array($generator)); } + + public function testMergeWithJoinsIteratorsTogether(): void + { + $generator1 = FixerGenerator::create('src/Fixer', 'Nexus\\CsConfig\\Fixer'); + $generator2 = FixerGenerator::create('vendor/friendsofphp/php-cs-fixer/src/Fixer', 'PhpCsFixer\\Fixer'); + + /** @var list $joinedGenerators */ + $joinedGenerators = iterator_to_array($generator1->mergeWith($generator2)->getIterator(), false); + self::assertStringStartsWith('Nexus\\CsConfig\\Fixer', $joinedGenerators[0]::class); + self::assertStringStartsWith('PhpCsFixer\\Fixer', $joinedGenerators[\count($joinedGenerators) - 1]::class); + } }