From 009c74f1ef1609dbfc036bac98f75bec236b885f Mon Sep 17 00:00:00 2001 From: Martin Rademacher Date: Thu, 27 Jun 2024 18:25:50 +1200 Subject: [PATCH] Simplify the collector implementation (#1611) --- src/Processors/Concerns/CollectorTrait.php | 59 ++++++++-------------- 1 file changed, 20 insertions(+), 39 deletions(-) diff --git a/src/Processors/Concerns/CollectorTrait.php b/src/Processors/Concerns/CollectorTrait.php index 2473a460..8e2ef8c1 100644 --- a/src/Processors/Concerns/CollectorTrait.php +++ b/src/Processors/Concerns/CollectorTrait.php @@ -11,57 +11,38 @@ trait CollectorTrait { /** - * Collects a complete list of all nested/referenced annotations. + * Collects a (complete) list of all nested/referenced annotations starting from the given root. */ - public function collect(iterable $annotations): \SplObjectStorage + public function collect(iterable $root): \SplObjectStorage { $storage = new \SplObjectStorage(); - foreach ($annotations as $annotation) { - if ($annotation instanceof OA\AbstractAnnotation) { - $storage->addAll($this->traverse($annotation)); - } - } - - return $storage; - } - - public function traverse(OA\AbstractAnnotation $annotation): \SplObjectStorage - { - $storage = new \SplObjectStorage(); - - if ($storage->contains($annotation)) { - return $storage; - } - - $storage->attach($annotation); - - foreach (array_merge($annotation::$_nested, ['allOf', 'anyOf', 'oneOf', 'callbacks']) as $properties) { - foreach ((array) $properties as $property) { - if (isset($annotation->{$property})) { - $storage->addAll($this->traverseNested($annotation->{$property})); - } - } - } + $this->traverse($root, function (OA\AbstractAnnotation $annotation) use (&$storage) { + $storage->attach($annotation); + }); return $storage; } /** - * @param string|array|OA\AbstractAnnotation $nested + * @param string|array|OA\AbstractAnnotation $root */ - protected function traverseNested($nested): \SplObjectStorage + public function traverse($root, callable $callable): void { - $storage = new \SplObjectStorage(); - - if (is_array($nested)) { - foreach ($nested as $value) { - $storage->addAll($this->traverseNested($value)); + if (is_iterable($root)) { + foreach ($root as $value) { + $this->traverse($value, $callable); + } + } elseif ($root instanceof OA\AbstractAnnotation) { + $callable($root); + + foreach (array_merge($root::$_nested, ['allOf', 'anyOf', 'oneOf', 'callbacks']) as $properties) { + foreach ((array) $properties as $property) { + if (isset($root->{$property})) { + $this->traverse($root->{$property}, $callable); + } + } } - } elseif ($nested instanceof OA\AbstractAnnotation) { - $storage->addAll($this->traverse($nested)); } - - return $storage; } }