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
34 changes: 34 additions & 0 deletions WebFiori/Http/Annotations/ApiResponse.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php

/**
* This file is licensed under MIT License.
*
* Copyright (c) 2026-present WebFiori Framework
*
* For more information on the license, please visit:
* https://github.com/WebFiori/.github/blob/main/LICENSE
*/
namespace WebFiori\Http\Annotations;

use Attribute;

/**
* Declares a possible response for a service method in the OpenAPI spec.
*
* This attribute is repeatable so multiple responses can be declared per method.
*
* Usage:
* ```php
* #[ApiResponse(status: '200', description: 'List of products')]
* #[ApiResponse(status: '404', description: 'Product not found')]
* public function getProducts(): array { ... }
* ```
*/
#[Attribute(Attribute::TARGET_METHOD | Attribute::IS_REPEATABLE)]
class ApiResponse {
public function __construct(
public readonly string $status = '200',
public readonly string $description = '',
) {
}
}
3 changes: 2 additions & 1 deletion WebFiori/Http/Annotations/RestController.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
class RestController {
public function __construct(
public readonly string $name = '',
public readonly string $description = ''
public readonly string $description = '',
public readonly string $path = ''
) {
}
}
62 changes: 61 additions & 1 deletion WebFiori/Http/OpenAPI/OpenAPIGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/
namespace WebFiori\Http\OpenAPI;

use WebFiori\Http\Annotations\RestController;
use WebFiori\Http\WebService;

/**
Expand Down Expand Up @@ -38,7 +39,7 @@ public function generate(array $services, string $description = '', string $vers

foreach ($services as $service) {
if ($service instanceof WebService) {
$path = $basePath.'/'.$service->getName();
$path = $basePath.'/'.$service->getPath();
$paths->addPath($path, $service->toPathItemObj());
}
}
Expand All @@ -47,4 +48,63 @@ public function generate(array $services, string $description = '', string $vers

return $openapi;
}

/**
* Generates an OpenAPI specification by scanning a namespace for #[RestController] classes.
*
* Classes must already be autoloadable (e.g., via Composer). The method finds all
* declared classes in the given namespace that extend WebService and have the
* #[RestController] attribute.
*
* @param string $namespace The namespace to scan (e.g., 'App\\Apis').
* @param string $description API title/description for the info object.
* @param string $version API version string.
* @param string $basePath Base path prefix for all service routes.
*
* @return OpenAPIObj The generated OpenAPI specification object.
*/
public function generateFromNamespace(string $namespace, string $description = '', string $version = '1.0.0', string $basePath = '') : OpenAPIObj {
$services = self::discoverServices($namespace);

return $this->generate($services, $description, $version, $basePath);
}

/**
* Discovers WebService instances in a given namespace.
*
* Scans all declared classes for those belonging to the namespace,
* extending WebService, having #[RestController], and not being abstract.
*
* @param string $namespace The namespace to scan.
*
* @return WebService[] Array of instantiated service objects.
*/
public static function discoverServices(string $namespace) : array {
$namespace = rtrim($namespace, '\\') . '\\';
$services = [];

foreach (get_declared_classes() as $class) {
if (!str_starts_with($class, $namespace)) {
continue;
}

if (!is_subclass_of($class, WebService::class)) {
continue;
}

$reflection = new \ReflectionClass($class);

if ($reflection->isAbstract()) {
continue;
}

if (empty($reflection->getAttributes(RestController::class))) {
continue;
}

$services[] = new $class();
}

return $services;
}
}
78 changes: 78 additions & 0 deletions WebFiori/Http/OpenAPI/OpenAPISpecService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php

/**
* This file is licensed under MIT License.
*
* Copyright (c) 2026-present WebFiori Framework
*
* For more information on the license, please visit:
* https://github.com/WebFiori/http/blob/master/LICENSE
*/
namespace WebFiori\Http\OpenAPI;

use WebFiori\Http\Annotations\AllowAnonymous;
use WebFiori\Http\Annotations\GetMapping;
use WebFiori\Http\Annotations\ResponseBody;
use WebFiori\Http\Annotations\RestController;
use WebFiori\Http\WebService;
use WebFiori\Json\JsonI;

/**
* Built-in service that exposes an OpenAPI specification via GET.
*
* The service scans a configured namespace for #[RestController] classes
* and returns the generated OpenAPI JSON spec.
*
* Usage:
* ```php
* $spec = new OpenAPISpecService('App\\Apis', '/apis', 'My API', '1.0.0');
* $processor = new RequestProcessor();
* $processor->process($spec);
* ```
*
* @author Ibrahim
*/
#[RestController(name: 'openapi', description: 'OpenAPI specification endpoint')]
class OpenAPISpecService extends WebService {
private string $namespace;
private string $apiBasePath;
private string $apiTitle;
private string $apiVersion;

/**
* Creates a new OpenAPI spec service.
*
* @param string $namespace The namespace to scan for #[RestController] services.
* @param string $basePath The base path prefix for API routes in the spec.
* @param string $title The API title for the info object.
* @param string $version The API version string.
*/
public function __construct(string $namespace, string $basePath = '', string $title = '', string $version = '1.0.0') {
parent::__construct('openapi');
$this->namespace = $namespace;
$this->apiBasePath = $basePath;
$this->apiTitle = $title;
$this->apiVersion = $version;
}

public function isAuthorized(): bool {
return true;
}

#[GetMapping]
#[ResponseBody]
#[AllowAnonymous]
public function getSpec(): JsonI {
$generator = new OpenAPIGenerator();

return $generator->generateFromNamespace(
$this->namespace,
$this->apiTitle,
$this->apiVersion,
$this->apiBasePath
);
}

public function processRequest() {
}
}
114 changes: 98 additions & 16 deletions WebFiori/Http/WebService.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,12 @@ class WebService implements JsonI {
*
*/
private $sinceVersion;
/**
* Custom route path for this service.
*
* @var string
*/
private string $servicePath = '';
/**
* Creates new instance of the class.
*
Expand Down Expand Up @@ -460,6 +466,31 @@ public function getManager() {
public final function getName() : string {
return $this->name;
}
/**
* Returns the custom route path for this service.
*
* If a path is set, it will be used for URL routing and OpenAPI spec
* generation instead of the service name. If not set, falls back to
* the service name.
*
* @return string The custom path, or the service name if no path is set.
*/
public final function getPath() : string {
return $this->servicePath !== '' ? $this->servicePath : $this->name;
}
/**
* Sets a custom route path for this service.
*
* The path may contain slashes for multi-segment URLs (e.g., 'auth/login').
*
* @param string $path The route path.
*
* @return self
*/
public function setPath(string $path) : self {
$this->servicePath = trim($path, '/');
return $this;
}
/**
* Map service parameter to specific instance of a class.
*
Expand Down Expand Up @@ -1086,13 +1117,18 @@ public function toJSON() : Json {
public function toPathItemObj(): OpenAPI\PathItemObj {
$pathItem = new OpenAPI\PathItemObj();
$annotatedParams = $this->getAnnotatedRequestParams();
$annotatedResponses = $this->getAnnotatedApiResponses();

foreach ($this->getRequestMethods() as $method) {
$responses = $this->getResponsesForMethod($method);

if ($responses === null) {
$responses = new OpenAPI\ResponsesObj();
$responses->addResponse('200', 'Successful operation');
if (isset($annotatedResponses[$method])) {
$responses = $annotatedResponses[$method];
} else {
$responses = new OpenAPI\ResponsesObj();
$responses->addResponse('200', 'Successful operation');
}
}

$operation = new OpenAPI\OperationObj($responses);
Expand Down Expand Up @@ -1176,6 +1212,47 @@ private function getAnnotatedRequestParams(): array {
return $result;
}

/**
* Reads #[ApiResponse] annotations from methods and groups them by HTTP method.
*
* @return array<string, OpenAPI\ResponsesObj> Map of HTTP method to ResponsesObj.
*/
private function getAnnotatedApiResponses(): array {
$reflection = new \ReflectionClass($this);
$result = [];

$mappings = [
Annotations\GetMapping::class => RequestMethod::GET,
Annotations\PostMapping::class => RequestMethod::POST,
Annotations\PutMapping::class => RequestMethod::PUT,
Annotations\DeleteMapping::class => RequestMethod::DELETE,
Annotations\PatchMapping::class => RequestMethod::PATCH,
];

foreach ($reflection->getMethods() as $method) {
$responseAttrs = $method->getAttributes(Annotations\ApiResponse::class);

if (empty($responseAttrs)) {
continue;
}

foreach ($mappings as $annotationClass => $httpMethod) {
if (!empty($method->getAttributes($annotationClass))) {
if (!isset($result[$httpMethod])) {
$result[$httpMethod] = new OpenAPI\ResponsesObj();
}

foreach ($responseAttrs as $attr) {
$instance = $attr->newInstance();
$result[$httpMethod]->addResponse($instance->status, $instance->description);
}
}
}
}

return $result;
}

/**
* Builds an OpenAPI ParameterObj (query param) from a RequestParam annotation.
*/
Expand Down Expand Up @@ -1289,6 +1366,10 @@ private function configureFromAnnotations(string $fallbackName): void {
$restController = $attributes[0]->newInstance();
$serviceName = $restController->name ?: $fallbackName;
$description = $restController->description;

if ($restController->path !== '') {
$this->setPath($restController->path);
}
} else {
$serviceName = $fallbackName;
$description = '';
Expand Down Expand Up @@ -1735,20 +1816,24 @@ protected function handleMethodResponse(mixed $result, string $methodName): void
// Handle custom content types
if ($contentType !== 'application/json') {
// For non-JSON content types, send raw result
if (is_array($result)) {
if ($result instanceof Json) {
$this->send($contentType, $result . '', $responseBody->status);
} else if ($result instanceof JsonI) {
$this->send($contentType, $result->toJSON() . '', $responseBody->status);
} else if (is_array($result)) {
$content = new Json();
$content->addArray('data', $result, !array_is_list($result));
$contentType = 'application/json';
$this->send($contentType, $content, $responseBody->status);
} else if (is_object($result)) {
$content = new Json();
$content->addObject('data', $result);
$contentType = 'application/json';
$this->send($contentType, $content, $responseBody->status);
} else {
$content = (string)$result;
$this->send($contentType, (string)$result, $responseBody->status);
}

$this->send($contentType, $content, $responseBody->status);

return;
}

Expand All @@ -1775,17 +1860,14 @@ protected function handleMethodResponse(mixed $result, string $methodName): void
if ($result === null) {
// Null return = empty response with configured status
$this->sendResponse('', $responseBody->status, $responseBody->type);
} else if ($result instanceof Json) {
$this->send($responseBody->contentType, $result . '', $responseBody->status);
} else if ($result instanceof JsonI) {
$this->send($responseBody->contentType, $result->toJSON() . '', $responseBody->status);
} else if (is_array($result) || is_object($result)) {
// Array/object = JSON response
if ($result instanceof Json) {
$json = $result;
} else if ($result instanceof JsonI) {
$json = $result->toJSON();
} else {
$json = new Json();
$asObj = is_array($result) && !array_is_list($result);
$json->add('data', $result, $asObj);
}
$json = new Json();
$asObj = is_array($result) && !array_is_list($result);
$json->add('data', $result, $asObj);
$this->send($responseBody->contentType, $json, $responseBody->status);
} else {
// String/scalar = plain response
Expand Down
Loading
Loading