-
Notifications
You must be signed in to change notification settings - Fork 0
Add examples for try it out, #PG-5178 #38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5cad729
Added basic parameter examples, not currently showing complex types, …
lachiebol a2cdabe
generated more meaningful examples + removed not required
lachiebol 834255b
phpcs
lachiebol ab120dd
Fix tests
lachiebol bca8e0e
Added missing required examples and fixed default logic
lachiebol 6c51fe8
Merge branch '5.x-dev' into PG-5178-try-it-out-examples
lachiebol File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -99,6 +99,11 @@ class AnnotationGenerator | |
| */ | ||
| protected $allowLocalRequests; | ||
|
|
||
| /** | ||
| * @var array<string, mixed>|null | ||
| */ | ||
| protected $parameterExamples; | ||
|
|
||
| public function __construct( | ||
| DocumentationGenerator $generator, | ||
| ?PathResolver $pathResolver = null, | ||
|
|
@@ -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'); | ||
| } | ||
|
|
||
|
|
@@ -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 = []; | ||
|
|
@@ -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) { | ||
|
|
@@ -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); | ||
| // 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.'); | ||
|
|
@@ -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); | ||
| } | ||
|
|
||
|
|
@@ -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) | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. | ||
|
|
@@ -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; | ||
| } | ||
|
|
||
|
|
@@ -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']), | ||
|
|
@@ -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)); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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