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
69 changes: 7 additions & 62 deletions generate-spec.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@
use PhpParser\Node\Name;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Enum_;
use PhpParser\Node\Stmt\EnumCase;
use PhpParser\Node\Stmt\Throw_;
use PhpParser\NodeFinder;
use PhpParser\NodeTraverser;
Expand Down Expand Up @@ -144,68 +142,15 @@
$schemas = [];
$tags = [];

$enumsByFqcn = [];
$enumSourceDirs = [$sourceDir];
// Namespace prefixes used to lazily resolve classes referenced as native parameter types, PSR-4 style.
$namespaceRoots = [
$appNamespace => $sourceDir,
Comment thread
CarlSchwan marked this conversation as resolved.
];
if ($appIsCore) {
$enumSourceDirs[] = $sourceDir . '/../lib/private';
}
foreach ($enumSourceDirs as $enumSourceDir) {
if (!is_dir($enumSourceDir)) {
continue;
}
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($enumSourceDir));
foreach ($iterator as $file) {
$path = $file->getPathname();
if (!str_ends_with((string)$path, '.php')) {
continue;
}
$contents = file_get_contents($path);
if (!str_contains($contents, 'enum ')) {
// Cheap pre-filter to avoid parsing every file in the app just to look for enums.
continue;
}
foreach ($nodeFinder->findInstanceOf($nodeTraverser->traverse($astParser->parse($contents)), Enum_::class) as $node) {
$name = $node->name->name;
if ($node->scalarType === null) {
Logger::debug($path, "Enum '" . $name . "' is not backed and can therefore not be used as an OpenAPI type. Use 'enum " . $name . ": string' or 'enum " . $name . ": int' instead.");
continue;
}

$values = [];
foreach ($node->stmts as $stmt) {
if ($stmt instanceof EnumCase && $stmt->expr !== null) {
$values[] = Helpers::exprToValue($path . ': ' . $name . '::' . $stmt->name->name, $stmt->expr);
}
}

$description = null;
$doc = $node->getDocComment()?->getText();
if ($doc != null) {
$descriptionLines = [];
$docNodes = $phpDocParser->parse(new TokenIterator($lexer->tokenize($doc)))->children;
foreach ($docNodes as $docNode) {
if ($docNode instanceof PhpDocTextNode) {
$block = Helpers::cleanDocComment($docNode->text);
if ($block !== '') {
$descriptionLines[] = $block;
}
}
}
if ($descriptionLines !== []) {
$description = implode("\n", $descriptionLines);
}
}

$enumsByFqcn[$node->namespacedName->toString()] = new OpenApiType(
context: $path,
type: $node->scalarType->name === 'int' ? 'integer' : 'string',
format: $node->scalarType->name === 'int' ? 'int64' : null,
description: $description,
enum: $values,
);
}
}
$namespaceRoots['OC'] = $sourceDir . '/../lib/private';
}
$classResolver = new ClassResolver($astParser, $nodeTraverser, $nodeFinder, $namespaceRoots);
$enumResolver = new EnumResolver($classResolver, $phpDocParser, $lexer);

$definitions = [];
$definitionsPath = $sourceDir . '/ResponseDefinitions.php';
Expand Down
91 changes: 91 additions & 0 deletions src/ClassResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<?php

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OpenAPIExtractor;

use PhpParser\Node\Stmt\ClassLike;
use PhpParser\NodeFinder;
use PhpParser\NodeTraverser;
use PhpParser\Parser;

/**
* Lazily resolves a class, interface, trait or enum by its fully qualified name,
* by mapping namespace prefixes to source directories, PSR-4 style.
*/
class ClassResolver {
/** @var array<string, ClassLike|false> */
private array $cache = [];

/** @var array<string, string> Namespace prefix => source directory */
private readonly array $namespaceRoots;

/** @param array<string, string> $namespaceRoots Namespace prefix => source directory */
public function __construct(
private readonly Parser $astParser,
private readonly NodeTraverser $nodeTraverser,
private readonly NodeFinder $nodeFinder,
array $namespaceRoots,
) {
$this->namespaceRoots = array_combine(
array_map(static fn (string $prefix): string => trim($prefix, '\\'), array_keys($namespaceRoots)),
array_values($namespaceRoots),
);
}

/** Returns null if the class can not be found, e.g. because it is outside of the known namespace roots. */
public function resolve(string $fqcn): ?ClassLike {
$fqcn = ltrim($fqcn, '\\');
if (!array_key_exists($fqcn, $this->cache)) {
$this->cache[$fqcn] = $this->load($fqcn) ?? false;
}

$node = $this->cache[$fqcn];
return $node !== false ? $node : null;
}

private function load(string $fqcn): ?ClassLike {
$path = $this->findFile($fqcn);
if ($path === null || !is_file($path)) {
return null;
}

$contents = file_get_contents($path);
if ($contents === false) {
return null;
}

/** @var ClassLike $node */
foreach ($this->nodeFinder->findInstanceOf($this->nodeTraverser->traverse($this->astParser->parse($contents)), ClassLike::class) as $node) {
if ($node->namespacedName?->toString() === $fqcn) {
$node->setAttribute('sourceFile', $path);
return $node;
}
}

return null;
}

/** Maps the class name to a file path via its longest matching namespace prefix. */
private function findFile(string $fqcn): ?string {
$bestPrefix = null;
foreach (array_keys($this->namespaceRoots) as $prefix) {
if (!str_starts_with($fqcn . '\\', $prefix . '\\')) {
continue;
}
if ($bestPrefix === null || strlen($prefix) > strlen($bestPrefix)) {
$bestPrefix = $prefix;
}
}

if ($bestPrefix === null) {
return null;
}

$relativeName = substr($fqcn, strlen($bestPrefix) + 1);
return $this->namespaceRoots[$bestPrefix] . '/' . str_replace('\\', '/', $relativeName) . '.php';
}
}
85 changes: 85 additions & 0 deletions src/EnumResolver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
<?php

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OpenAPIExtractor;

use PhpParser\Node\Stmt\Enum_;
use PhpParser\Node\Stmt\EnumCase;
use PHPStan\PhpDocParser\Ast\PhpDoc\PhpDocTextNode;
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\Parser\PhpDocParser;
use PHPStan\PhpDocParser\Parser\TokenIterator;

/** Resolves a backed enum's fully qualified class name into its OpenAPI representation. */
class EnumResolver {
/** @var array<string, OpenApiType|false> */
private array $cache = [];

public function __construct(
private readonly ClassResolver $classResolver,
private readonly PhpDocParser $phpDocParser,
private readonly Lexer $lexer,
) {
}

public function resolve(string $fqcn): ?OpenApiType {
$fqcn = ltrim($fqcn, '\\');
if (!array_key_exists($fqcn, $this->cache)) {
$this->cache[$fqcn] = $this->load($fqcn) ?? false;
}

$enum = $this->cache[$fqcn];
return $enum !== false ? $enum : null;
}

private function load(string $fqcn): ?OpenApiType {
$node = $this->classResolver->resolve($fqcn);
if (!$node instanceof Enum_) {
return null;
}

$path = $node->getAttribute('sourceFile', $fqcn);

if ($node->scalarType === null) {
Logger::debug($path, "Enum '" . $fqcn . "' is not backed and can therefore not be used as an OpenAPI type. Use 'enum " . $node->name->name . ": string' or 'enum " . $node->name->name . ": int' instead.");
return null;
}

$values = [];
foreach ($node->stmts as $stmt) {
if ($stmt instanceof EnumCase && $stmt->expr !== null) {
$values[] = Helpers::exprToValue($path . ': ' . $fqcn . '::' . $stmt->name->name, $stmt->expr);
}
}

$description = null;
$doc = $node->getDocComment()?->getText();
if ($doc != null) {
$descriptionLines = [];
$docNodes = $this->phpDocParser->parse(new TokenIterator($this->lexer->tokenize($doc)))->children;
foreach ($docNodes as $docNode) {
if ($docNode instanceof PhpDocTextNode) {
$block = Helpers::cleanDocComment($docNode->text);
if ($block !== '') {
$descriptionLines[] = $block;
}
}
}
if ($descriptionLines !== []) {
$description = implode("\n", $descriptionLines);
}
}

return new OpenApiType(
context: $path,
type: $node->scalarType->name === 'int' || $node->scalarType->name === 'integer' ? 'integer' : 'string',
format: $node->scalarType->name === 'int' || $node->scalarType->name === 'integer' ? 'int64' : null,
description: $description,
enum: $values,
);
}
}
7 changes: 3 additions & 4 deletions src/OpenApiType.php
Original file line number Diff line number Diff line change
Expand Up @@ -422,13 +422,12 @@ public static function resolveNativeEnum(string $context, ?Node $node): ?OpenApi
return null;
}

global $enumsByFqcn;
$fqcn = ltrim($node->toString(), '\\');
if (!array_key_exists($fqcn, $enumsByFqcn)) {
global $enumResolver;
$enum = $enumResolver->resolve($node->toString());
if ($enum === null) {
return null;
}

$enum = $enumsByFqcn[$fqcn];
return new OpenApiType(
context: $context,
type: $enum->type,
Expand Down
1 change: 1 addition & 0 deletions tests/appinfo/routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@
['name' => 'Settings#custom401', 'url' => '/api/{apiVersion}/custom/401', 'verb' => 'POST', 'requirements' => ['apiVersion' => '(v2)']],
['name' => 'Settings#custom403', 'url' => '/api/{apiVersion}/custom/403', 'verb' => 'POST', 'requirements' => ['apiVersion' => '(v2)']],
['name' => 'Settings#stringBackedEnumParameter', 'url' => '/api/{apiVersion}/enums/string-backed', 'verb' => 'POST', 'requirements' => ['apiVersion' => '(v2)']],
['name' => 'Settings#intBackedEnumParameter', 'url' => '/api/{apiVersion}/enums/int-backed', 'verb' => 'POST', 'requirements' => ['apiVersion' => '(v2)']],
['name' => 'Settings#sortDirectionParameter', 'url' => '/api/{apiVersion}/enums/sort-direction', 'verb' => 'POST', 'requirements' => ['apiVersion' => '(v2)']],
['name' => 'Settings#injectedServiceParameter', 'url' => '/api/{apiVersion}/injected-service', 'verb' => 'POST', 'requirements' => ['apiVersion' => '(v2)']],
['name' => 'V1\SubDir#subDirRoute', 'url' => '/sub-dir', 'verb' => 'GET'],
Expand Down
13 changes: 13 additions & 0 deletions tests/lib/Controller/SettingsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

namespace OCA\Notifications\Controller;

use OCA\Notifications\Notification\NotificationPriority;
use OCA\Notifications\NotificationLevel;
use OCA\Notifications\ResponseDefinitions;
use OCP\AppFramework\Http;
Expand Down Expand Up @@ -865,6 +866,18 @@ public function stringBackedEnumParameter(NotificationLevel $level): DataRespons
return new DataResponse();
}

/**
* A route with a backed enum declared in a sub-namespace as a native parameter type
*
* @param NotificationPriority $priority Priority
* @return DataResponse<Http::STATUS_OK, array{}, array{}>
*
* 200: OK
*/
public function intBackedEnumParameter(NotificationPriority $priority): DataResponse {
return new DataResponse();
}

/**
* A route using the built-in SortDirection enum as a native parameter type
*
Expand Down
22 changes: 22 additions & 0 deletions tests/lib/Notification/NotificationPriority.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Notifications\Notification;

/**
* The priority of a notification
*
* Declared in a sub-namespace/sub-directory to confirm that enums are resolved
* by mapping their namespace to a file path instead of relying on a directory scan.
*/
enum NotificationPriority: integer {
case Low = 0;
case Normal = 1;
case High = 2;
}
Loading