BuildPaths.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php declare(strict_types=1);
  2. /**
  3. * @license Apache 2.0
  4. */
  5. namespace OpenApi\Processors;
  6. use OpenApi\Annotations\PathItem;
  7. use OpenApi\Annotations\Operation;
  8. use OpenApi\Logger;
  9. use OpenApi\Context;
  10. use OpenApi\Analysis;
  11. /**
  12. * Build the openapi->paths using the detected @OA\PathItem and @OA\Operations (like @OA\Get, @OA\Post, etc)
  13. */
  14. class BuildPaths
  15. {
  16. public function __invoke(Analysis $analysis)
  17. {
  18. $paths = [];
  19. // Merge @OA\PathItems with the same path.
  20. if ($analysis->openapi->paths !== UNDEFINED) {
  21. foreach ($analysis->openapi->paths as $annotation) {
  22. if (empty($annotation->path)) {
  23. Logger::notice($annotation->identity() . ' is missing required property "path" in ' . $annotation->_context);
  24. } elseif (isset($paths[$annotation->path])) {
  25. $paths[$annotation->path]->mergeProperties($annotation);
  26. $analysis->annotations->detach($annotation);
  27. } else {
  28. $paths[$annotation->path] = $annotation;
  29. }
  30. }
  31. }
  32. // Merge @OA\Operations into existing @OA\PathItems or create a new one.
  33. $operations = $analysis->unmerged()->getAnnotationsOfType(Operation::class);
  34. foreach ($operations as $operation) {
  35. if ($operation->path) {
  36. if (empty($paths[$operation->path])) {
  37. $paths[$operation->path] = new PathItem(
  38. [
  39. 'path' => $operation->path,
  40. '_context' => new Context(['generated' => true], $operation->_context)
  41. ]
  42. );
  43. $analysis->annotations->attach($paths[$operation->path]);
  44. }
  45. if ($paths[$operation->path]->merge([$operation])) {
  46. Logger::notice('Unable to merge '.$operation->identity() .' in '.$operation->_context);
  47. }
  48. }
  49. }
  50. if (count($paths)) {
  51. $analysis->openapi->paths = array_values($paths);
  52. }
  53. }
  54. }