Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 173 additions & 10 deletions Annotations/AnnotationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@ class AnnotationGenerator
*/
protected $allowLocalRequests;

/**
* @var array<string, mixed>|null
*/
protected $parameterExamples;

public function __construct(
DocumentationGenerator $generator,
?PathResolver $pathResolver = null,
Expand All @@ -110,6 +115,7 @@ public function __construct(
$this->artifactWriter = $artifactWriter ?? new ArtifactWriter();
$this->missingImportantDataWarnings = [];
$this->allowLocalRequests = $allowLocalRequests;
$this->parameterExamples = null;
$this->currentPluginDir = Manager::getInstance()::getPluginDirectory('OpenApiDocs');
}

Expand Down Expand Up @@ -455,7 +461,7 @@ public function buildParameterAnnotationData(string $methodName, string $paramNa
// Sometimes, doc-block can wrap type hinting with parenthesis. Remove them.
$type = trim($type, '()');
// If the signature type is array, but the type hinting provides more, use that instead
if ($type === 'array' && strpos($docType, '[]') !== false && strpos($docType, '|') === false) {
if ($type === 'array' && $this->hasSpecificArrayShape($docType) && strpos($docType, '|') === false) {
$type = $docType;
}
$typesMap = [];
Expand All @@ -468,6 +474,7 @@ public function buildParameterAnnotationData(string $methodName, string $paramNa
$typeHints = array_diff($typeHints, ['bool']);
}

$isRequired = !key_exists('default', $paramMetadata) || $paramMetadata['default'] instanceof NoDefaultValue;
$allTypeHintsAreStringLiterals = $this->areAllTypeHintsStringLiterals($typeHints);
$enumValues = [];
if ($allTypeHintsAreStringLiterals) {
Expand All @@ -478,17 +485,13 @@ public function buildParameterAnnotationData(string $methodName, string $paramNa
} else {
foreach ($typeHints as $typePart) {
$typePart = trim($typePart, ' ()');
$normalisedType = $this->getOpenApiTypeFromPhpType($typePart);
$normalisedType = $this->hasSpecificArrayShape($typePart) ? 'array' : $this->getOpenApiTypeFromPhpType($typePart);
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If it's a complex array type I'm just leaving it for now. When I implement POST this can be changed

// If the type is array, check if there's a subType
$subType = null;
if ($normalisedType === 'array' && $typePart !== 'array' && strpos($typePart, '[]') !== false) {
$subType = substr($typePart, 0, strpos($typePart, '[]'));
}
$subType = $this->getArraySubTypeFromPhpType($typePart, $normalisedType);
$typesMap[$normalisedType] = $subType !== null ? $this->getOpenApiTypeFromPhpType($subType) : $subType;
}
}

$isRequired = !key_exists('default', $paramMetadata) || $paramMetadata['default'] instanceof NoDefaultValue;
$description = $paramDocInfo['description'] ?? '';
if (empty($description)) {
$this->addMissingImportantDataWarning($methodName, $paramName, 'Description is not specified in comment block.');
Expand All @@ -506,11 +509,20 @@ public function buildParameterAnnotationData(string $methodName, string $paramNa
$example = trim($example, '"');
}

if ($isRequired && $example === '') {
$configExample = $this->getParameterExampleFromConfig($paramName, $type, $typesMap);
if ($configExample !== null) {
$example = $configExample;
}
}

// Clean up the descriptions a little more like removing linebreaks and escaping double-quotes
$description = $this->normaliseDescriptionText($description);

$default = $paramMetadata['default'] ?? null;
if (!is_string($default)) {
if ($default === null) {
$default = NoDefaultValue::class;
} elseif (!is_string($default)) {
$default = json_encode($default);
}

Expand Down Expand Up @@ -555,6 +567,138 @@ protected function areAllTypeHintsStringLiterals(array $typeHints): bool
return true;
}

protected function hasSpecificArrayShape(string $type): bool
{
return strpos($type, '[]') !== false || preg_match('/^(array|list)<.+>$/', trim($type)) === 1;
}

protected function getArraySubTypeFromPhpType(string $typePart, string $normalisedType): ?string
{
if ($normalisedType !== 'array' || $typePart === 'array') {
return null;
}

if (strpos($typePart, '[]') !== false) {
return substr($typePart, 0, strpos($typePart, '[]'));
}

if (preg_match('/^(array|list)<(.+)>$/', trim($typePart), $matches) !== 1) {
return null;
}

$genericParts = array_map('trim', explode(',', $matches[2], 2));
if (count($genericParts) === 1) {
return $genericParts[0];
}

return $genericParts[1];
}

/**
* Load and return the configured parameter examples.
*
* @return array<string, mixed>
*/
protected function getParameterExamplesConfig(): array
{
if ($this->parameterExamples !== null) {
return $this->parameterExamples;
}

$configPath = $this->currentPluginDir . '/config/ParameterExamples.php';
if (!is_file($configPath)) {
$this->parameterExamples = [];
return $this->parameterExamples;
}

$config = require $configPath;
$this->parameterExamples = is_array($config) ? $config : [];

return $this->parameterExamples;
}

/**
* Return a config-backed example string if the configured example is intentionally simple enough to support.
*/
protected function getParameterExampleFromConfig(string $paramName, string $type, array $typesMap): ?string
{
$config = $this->getParameterExamplesConfig();
$keysToTry = [
$paramName . ':' . $type,
$paramName . ':' . preg_replace('/\s+/', '', $type),
];

$configValue = null;
$foundConfigValue = false;
foreach (array_unique($keysToTry) as $key) {
if (!array_key_exists($key, $config)) {
continue;
}

$configValue = $config[$key];
$foundConfigValue = true;
break;
}

if (!$foundConfigValue) {
return null;
}

return $this->normaliseConfiguredParameterExample($configValue, $typesMap);
}

/**
* Convert supported scalar/basic-array config values into the string form used by schema generation.
*/
protected function normaliseConfiguredParameterExample($example, array $typesMap = []): ?string
{
if (is_bool($example)) {
return $example ? 'true' : 'false';
}

if (is_int($example) || is_float($example) || is_string($example)) {
return strval($example);
}

if (
!is_array($example)
|| !$this->isBasicExampleArray($example)
|| !$this->supportsBasicArrayExample($typesMap)
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here: will remove this logic when adding POST. At the moment it prevents complex param examples from coming through

) {
return null;
}

$encoded = json_encode(array_values($example));

return is_string($encoded) ? $encoded : null;
}

/**
* Only use array config examples when the emitted schema includes an array shape.
*/
protected function supportsBasicArrayExample(array $typesMap): bool
{
return array_key_exists('array', $typesMap);
}

/**
* Only support flat indexed arrays of scalar values for now.
*/
protected function isBasicExampleArray(array $example): bool
{
if (array_values($example) !== $example) {
return false;
}

foreach ($example as $item) {
if (!is_bool($item) && !is_int($item) && !is_float($item) && !is_string($item)) {
return false;
}
}

return true;
}

/**
* Take description text and normalise it. This includes trimming surrounding whitespace, removing newlines and
* escaping double-quote characters.
Expand Down Expand Up @@ -1863,7 +2007,7 @@ public function buildSchemaObjectArray(string $type, string $subType = '', strin
*/
public function wrapStringWithQuotes(string $string, string $type, string $quoteCharacter = '"'): string
{
if (in_array($type, ['integer', 'boolean', 'array'])) {
if (in_array($type, ['integer', 'number', 'boolean', 'array'])) {
return $string;
}

Expand Down Expand Up @@ -1972,12 +2116,17 @@ public function compileOperationLines(string $path, string $opId, string $plugin
$paramMap[] = 'description="' . $param['description'] . '"';
}
$exampleString = $param['example'];
if (in_array('array', array_keys($param['types']))) {
$useParameterLevelExample = $this->shouldUseParameterLevelExample($param['types'], $exampleString);
if (in_array('array', array_keys($param['types'])) && !$useParameterLevelExample) {
// The annotation expects example objects and not arrays, so replace [] with {}
$exampleString = str_replace(['[', ']'], ['{', '}'], $exampleString);
// Escape quotes differently for the annotation examples
$exampleString = str_replace('\"', '""', $exampleString);
}
if ($useParameterLevelExample) {
$paramMap[] = 'example="' . $this->normaliseDescriptionText($exampleString) . '"';
$exampleString = '';
}
$paramMap[] = $this->buildSchemaObjectArrays(
$param['types'],
strval($param['default']),
Expand Down Expand Up @@ -2019,4 +2168,18 @@ public function compileOperationLines(string $path, string $opId, string $plugin
$this->removeTrailingCommaFromLastLine($lines);
return $lines;
}

/**
* Use a parameter-level string example for scalar/array unions so Swagger UI can show a concrete query value.
*
* @param array<string, string|null> $typesMap
*/
protected function shouldUseParameterLevelExample(array $typesMap, string $example): bool
{
if (count($typesMap) <= 1 || !array_key_exists('array', $typesMap) || $example === '') {
return false;
}

return is_array(json_decode($example, true));
}
}
Loading
Loading