diff --git a/src/Processors/AugmentTags.php b/src/Processors/AugmentTags.php index 171b6387..25290081 100644 --- a/src/Processors/AugmentTags.php +++ b/src/Processors/AugmentTags.php @@ -15,6 +15,25 @@ */ class AugmentTags implements ProcessorInterface { + + /** @var array */ + protected $whitelist; + + public function __construct(array $whitelist = []) + { + $this->whitelist = $whitelist; + } + + /** + * Whitelist tags to keep even if not used. * may be used to keep all unused. + */ + public function setWhitelist(array $whitelist): AugmentTags + { + $this->whitelist = $whitelist; + + return $this; + } + public function __invoke(Analysis $analysis) { /** @var OA\Operation[] $operations */ @@ -39,6 +58,7 @@ public function __invoke(Analysis $analysis) $analysis->openapi->tags = array_values($declaredTags); } + // Add a tag for each tag that is used in operations but not declared in the global tags if ($usedTagNames) { $declatedTagNames = array_keys($declaredTags); foreach ($usedTagNames as $tagName) { @@ -48,8 +68,18 @@ public function __invoke(Analysis $analysis) } } + $this->removeUnusedTags($usedTagNames, $declaredTags, $analysis); + } + + private function removeUnusedTags(array $usedTagNames, array $declaredTags, Analysis $analysis) + { + if (in_array('*', $this->whitelist)) { + return; + } + + $tagsToKeep = array_merge($usedTagNames, $this->whitelist); foreach ($declaredTags as $tag) { - if (!in_array($tag->name, $usedTagNames)) { + if (!in_array($tag->name, $tagsToKeep)) { if (false !== $index = array_search($tag, $analysis->openapi->tags, true)) { $analysis->annotations->detach($tag); unset($analysis->openapi->tags[$index]); diff --git a/tests/Fixtures/UnusedTags.php b/tests/Fixtures/UnusedTags.php new file mode 100644 index 00000000..1a35293c --- /dev/null +++ b/tests/Fixtures/UnusedTags.php @@ -0,0 +1,32 @@ +assertCount(3, $analysis->openapi->tags, 'Expecting 3 unique tags'); } + + /** + * @requires PHP 8.1 + */ + public function testAllowUnusedTags(): void + { + $this->skipLegacy(); + + $analysis = $this->analysisFromFixtures( + ['UnusedTags.php'], + static::processors(), + null, + [ + 'augmentTags' => ['whitelist' => ['fancy']], + ] + ); + + $this->assertCount(2, $analysis->openapi->tags, 'Expecting fancy tag to be preserved'); + } + + /** + * @requires PHP 8.1 + */ + public function testAllowUnusedTagsWildcard(): void + { + $this->skipLegacy(); + + $analysis = $this->analysisFromFixtures( + ['UnusedTags.php'], + static::processors(), + null, + [ + 'augmentTags' => ['whitelist' => ['*']], + ] + ); + + $this->assertCount(3, $analysis->openapi->tags, 'Expecting all tags to be preserved'); + } }