<?php
namespace Nelmio\ApiDocBundle\RouteDescriber;
use LogicException;
use Nelmio\ApiDocBundle\OpenApiPhp\Util;
use OpenApi\Annotations as OA;
use OpenApi\Generator;
use Symfony\Component\Routing\Route;
final class RouteMetadataDescriber implements RouteDescriberInterface
{
use RouteDescriberTrait;
public function describe(OA\OpenApi $api, Route $route, \ReflectionMethod $reflectionMethod)
{
foreach ($this->getOperations($api, $route) as $operation) {
$requirements = $route->getRequirements();
$compiledRoute = $route->compile();
$existingParams = $this->getRefParams($api, $operation);
foreach ($compiledRoute->getPathVariables() as $pathVariable) {
if ('_format' === $pathVariable) {
continue;
}
$paramId = $pathVariable.'/path';
$parameter = $existingParams[$paramId] ?? null;
if (null !== $parameter) {
if (!$parameter->required || Generator::UNDEFINED === $parameter->required) {
throw new LogicException(\sprintf('Global parameter "%s" is used as part of route "%s" and must be set as "required"', $pathVariable, $route->getPath()));
}
continue;
}
$parameter = Util::getOperationParameter($operation, $pathVariable, 'path');
$parameter->required = true;
$parameter->schema = Util::getChild($parameter, OA\Schema::class);
if (Generator::UNDEFINED === $parameter->schema->type) {
$parameter->schema->type = 'string';
}
if (isset($requirements[$pathVariable]) && Generator::UNDEFINED === $parameter->schema->pattern) {
$parameter->schema->pattern = $requirements[$pathVariable];
}
}
}
}
private function getRefParams(OA\OpenApi $api, OA\Operation $operation): array
{
$globalParams = Generator::UNDEFINED !== $api->components && Generator::UNDEFINED !== $api->components->parameters ? $api->components->parameters : [];
$globalParams = array_column($globalParams, null, 'parameter');
$existingParams = [];
$operationParameters = Generator::UNDEFINED !== $operation->parameters ? $operation->parameters : [];
foreach ($operationParameters as $id => $parameter) {
$ref = $parameter->ref;
if (Generator::UNDEFINED === $ref) {
continue;
}
$ref = \mb_substr($ref, 24);
if (!isset($globalParams[$ref])) {
continue;
}
$refParameter = $globalParams[$ref];
$existingParams[\sprintf('%s/%s', $refParameter->name, $refParameter->in)] = $refParameter;
}
return $existingParams;
}
}