From b1efc1eed5936b59b57007bd4cf0d48ee4f248ec Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Sun, 21 Jun 2026 23:56:03 +0300 Subject: [PATCH 1/5] feat(openapi): add #[ApiResponse] annotation for declarative response descriptions - Create WebFiori\Http\Annotations\ApiResponse repeatable attribute - Modify toPathItemObj() to read #[ApiResponse] from mapped methods - Programmatic addResponse() takes priority over annotations - Methods without #[ApiResponse] fall back to default '200 - Successful operation' Closes #143 --- WebFiori/Http/Annotations/ApiResponse.php | 34 ++++ WebFiori/Http/WebService.php | 50 +++++- .../Tests/Http/ApiResponseAnnotationTest.php | 159 ++++++++++++++++++ .../ApiResponseAnnotatedService.php | 45 +++++ 4 files changed, 286 insertions(+), 2 deletions(-) create mode 100644 WebFiori/Http/Annotations/ApiResponse.php create mode 100644 tests/WebFiori/Tests/Http/ApiResponseAnnotationTest.php create mode 100644 tests/WebFiori/Tests/Http/TestServices/ApiResponseAnnotatedService.php diff --git a/WebFiori/Http/Annotations/ApiResponse.php b/WebFiori/Http/Annotations/ApiResponse.php new file mode 100644 index 0000000..bac1a0c --- /dev/null +++ b/WebFiori/Http/Annotations/ApiResponse.php @@ -0,0 +1,34 @@ +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); @@ -1176,6 +1181,47 @@ private function getAnnotatedRequestParams(): array { return $result; } + /** + * Reads #[ApiResponse] annotations from methods and groups them by HTTP method. + * + * @return array 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. */ diff --git a/tests/WebFiori/Tests/Http/ApiResponseAnnotationTest.php b/tests/WebFiori/Tests/Http/ApiResponseAnnotationTest.php new file mode 100644 index 0000000..e110aea --- /dev/null +++ b/tests/WebFiori/Tests/Http/ApiResponseAnnotationTest.php @@ -0,0 +1,159 @@ +toPathItemObj(); + $json = json_decode($pathItem->toJSON() . '', true); + + $responses = $json['get']['responses']; + $this->assertArrayHasKey('200', $responses); + $this->assertArrayHasKey('404', $responses); + $this->assertEquals('List of products', $responses['200']['description']); + $this->assertEquals('Product not found', $responses['404']['description']); + } + + /** + * Test that #[ApiResponse] annotations on a POST method produce multiple responses. + */ + public function testPostMethodMultipleApiResponses() { + $service = new ApiResponseAnnotatedService(); + $pathItem = $service->toPathItemObj(); + $json = json_decode($pathItem->toJSON() . '', true); + + $responses = $json['post']['responses']; + $this->assertArrayHasKey('201', $responses); + $this->assertArrayHasKey('400', $responses); + $this->assertArrayHasKey('409', $responses); + $this->assertEquals('Product created successfully', $responses['201']['description']); + $this->assertEquals('Invalid input data', $responses['400']['description']); + $this->assertEquals('Product already exists', $responses['409']['description']); + } + + /** + * Test that methods without #[ApiResponse] fall back to default "200 - Successful operation". + */ + public function testMethodWithoutApiResponseUsesDefault() { + $service = new ApiResponseAnnotatedService(); + $pathItem = $service->toPathItemObj(); + $json = json_decode($pathItem->toJSON() . '', true); + + $responses = $json['delete']['responses']; + $this->assertArrayHasKey('200', $responses); + $this->assertEquals('Successful operation', $responses['200']['description']); + $this->assertArrayNotHasKey('404', $responses); + } + + /** + * Test that programmatic addResponse() takes priority over #[ApiResponse] annotations. + */ + public function testProgrammaticResponseTakesPriority() { + $service = new ApiResponseAnnotatedService(); + // Programmatically override GET responses + $service->addResponse(RequestMethod::GET, '200', 'Overridden response'); + $service->addResponse(RequestMethod::GET, '500', 'Server error'); + + $pathItem = $service->toPathItemObj(); + $json = json_decode($pathItem->toJSON() . '', true); + + $responses = $json['get']['responses']; + $this->assertEquals('Overridden response', $responses['200']['description']); + $this->assertEquals('Server error', $responses['500']['description']); + // The annotated 404 should NOT appear since programmatic takes priority + $this->assertArrayNotHasKey('404', $responses); + } + + /** + * Test that #[ApiResponse] annotations are included when service is registered in a manager. + */ + public function testApiResponseInManagerOpenAPI() { + $manager = new WebServicesManager(); + $manager->addService(new ApiResponseAnnotatedService()); + $openapi = $manager->toOpenAPI(); + $json = json_decode($openapi->toJSON() . '', true); + + $path = $json['paths']['/api-response-service']; + $this->assertArrayHasKey('200', $path['get']['responses']); + $this->assertEquals('List of products', $path['get']['responses']['200']['description']); + } + + /** + * Test that a method with a single #[ApiResponse] generates exactly one response entry. + */ + public function testSingleApiResponse() { + $service = new class extends \WebFiori\Http\WebService { + public function __construct() { + parent::__construct('single-response'); + } + + public function isAuthorized(): bool { + return true; + } + + #[\WebFiori\Http\Annotations\GetMapping] + #[\WebFiori\Http\Annotations\ApiResponse(status: '204', description: 'No content')] + public function noContent() { + } + + public function processRequest() { + } + }; + + $pathItem = $service->toPathItemObj(); + $json = json_decode($pathItem->toJSON() . '', true); + + $responses = $json['get']['responses']; + $this->assertCount(1, $responses); + $this->assertArrayHasKey('204', $responses); + $this->assertEquals('No content', $responses['204']['description']); + } + + /** + * Test that #[ApiResponse] works with status code ranges (e.g., "2XX"). + */ + public function testApiResponseWithStatusRange() { + $service = new class extends \WebFiori\Http\WebService { + public function __construct() { + parent::__construct('range-response'); + } + + public function isAuthorized(): bool { + return true; + } + + #[\WebFiori\Http\Annotations\GetMapping] + #[\WebFiori\Http\Annotations\ApiResponse(status: '2XX', description: 'Successful')] + #[\WebFiori\Http\Annotations\ApiResponse(status: '4XX', description: 'Client error')] + public function rangeResponse() { + } + + public function processRequest() { + } + }; + + $pathItem = $service->toPathItemObj(); + $json = json_decode($pathItem->toJSON() . '', true); + + $responses = $json['get']['responses']; + $this->assertArrayHasKey('2XX', $responses); + $this->assertArrayHasKey('4XX', $responses); + $this->assertEquals('Successful', $responses['2XX']['description']); + $this->assertEquals('Client error', $responses['4XX']['description']); + } +} diff --git a/tests/WebFiori/Tests/Http/TestServices/ApiResponseAnnotatedService.php b/tests/WebFiori/Tests/Http/TestServices/ApiResponseAnnotatedService.php new file mode 100644 index 0000000..50a348c --- /dev/null +++ b/tests/WebFiori/Tests/Http/TestServices/ApiResponseAnnotatedService.php @@ -0,0 +1,45 @@ + Date: Mon, 22 Jun 2026 00:03:31 +0300 Subject: [PATCH 2/5] feat(response): serialize JsonI objects directly without metadata in #[ResponseBody] - JsonI/Json return values are now stringified immediately via toJSON() - Non-JSON content type branch now handles JsonI/Json without wrapping in 'data' key - Internal public properties of JsonI objects no longer leak into response Closes #142 --- WebFiori/Http/WebService.php | 29 ++-- .../Tests/Http/JsonISerializationTest.php | 130 ++++++++++++++++++ .../TestServices/JsonIResponseService.php | 48 +++++++ 3 files changed, 193 insertions(+), 14 deletions(-) create mode 100644 tests/WebFiori/Tests/Http/JsonISerializationTest.php create mode 100644 tests/WebFiori/Tests/Http/TestServices/JsonIResponseService.php diff --git a/WebFiori/Http/WebService.php b/WebFiori/Http/WebService.php index 8d73d8c..1e6d517 100644 --- a/WebFiori/Http/WebService.php +++ b/WebFiori/Http/WebService.php @@ -1781,20 +1781,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; } @@ -1821,17 +1825,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 diff --git a/tests/WebFiori/Tests/Http/JsonISerializationTest.php b/tests/WebFiori/Tests/Http/JsonISerializationTest.php new file mode 100644 index 0000000..bc81883 --- /dev/null +++ b/tests/WebFiori/Tests/Http/JsonISerializationTest.php @@ -0,0 +1,130 @@ +get(new JsonIResponseService()); + $body = $response->getBody(); + $decoded = json_decode($body, true); + + $this->assertNotNull($decoded, 'Response should be valid JSON'); + $this->assertEquals('3.1.0', $decoded['openapi']); + $this->assertEquals('Test API', $decoded['info']['title']); + $this->assertEquals('1.0.0', $decoded['info']['version']); + } + + /** + * JsonI response should NOT contain metadata fields. + */ + public function testJsonIResponseHasNoMetadata() { + $response = $this->get(new JsonIResponseService()); + $body = $response->getBody(); + + $this->assertStringNotContainsString('Value', $body); + $this->assertStringNotContainsString('Case', $body); + $this->assertStringNotContainsString('JsonXTagName', $body); + $this->assertStringNotContainsString('Style', $body); + $this->assertStringNotContainsString('Type', $body); + } + + /** + * JsonI response should NOT be wrapped in a "data" key. + */ + public function testJsonIResponseNotWrappedInData() { + $response = $this->get(new JsonIResponseService()); + $body = $response->getBody(); + $decoded = json_decode($body, true); + + $this->assertArrayNotHasKey('data', $decoded); + $this->assertArrayHasKey('openapi', $decoded); + } + + /** + * Internal public properties of the JsonI object should not leak. + */ + public function testInternalPropertiesNotLeaked() { + $response = $this->get(new JsonIResponseService()); + $body = $response->getBody(); + + $this->assertStringNotContainsString('internalState', $body); + $this->assertStringNotContainsString('should-not-leak', $body); + } + + /** + * Returning a Json object directly should also produce clean output. + */ + public function testJsonReturnProducesCleanOutput() { + $service = new class extends WebService { + public function __construct() { + parent::__construct('json-direct'); + } + public function isAuthorized(): bool { return true; } + + #[GetMapping] + #[ResponseBody] + #[AllowAnonymous] + public function getData(): Json { + $j = new Json(); + $j->add('status', 'ok'); + $j->add('count', 42); + return $j; + } + public function processRequest() {} + }; + + $response = $this->get($service); + $decoded = json_decode($response->getBody(), true); + + $this->assertEquals('ok', $decoded['status']); + $this->assertEquals(42, $decoded['count']); + $this->assertArrayNotHasKey('data', $decoded); + } + + /** + * JsonI returned with a custom content type should still serialize cleanly. + */ + public function testJsonIWithCustomContentType() { + $service = new class extends WebService { + public function __construct() { + parent::__construct('custom-ct'); + } + public function isAuthorized(): bool { return true; } + + #[GetMapping] + #[ResponseBody(contentType: 'application/vnd.oai.openapi+json')] + #[AllowAnonymous] + public function getSpec(): JsonI { + return new SampleSpec(); + } + public function processRequest() {} + }; + + $response = $this->get($service); + $body = $response->getBody(); + $decoded = json_decode($body, true); + + $this->assertNotNull($decoded, 'Response should be valid JSON'); + $this->assertEquals('3.1.0', $decoded['openapi']); + $this->assertArrayNotHasKey('data', $decoded); + $this->assertStringNotContainsString('internalState', $body); + } +} diff --git a/tests/WebFiori/Tests/Http/TestServices/JsonIResponseService.php b/tests/WebFiori/Tests/Http/TestServices/JsonIResponseService.php new file mode 100644 index 0000000..1330332 --- /dev/null +++ b/tests/WebFiori/Tests/Http/TestServices/JsonIResponseService.php @@ -0,0 +1,48 @@ +add('openapi', '3.1.0'); + $info = new Json(); + $info->add('title', 'Test API'); + $info->add('version', '1.0.0'); + $j->add('info', $info); + $j->add('paths', new Json()); + return $j; + } +} + +/** + * Test service that returns JsonI objects from #[ResponseBody] methods. + */ +#[RestController('jsoni-service')] +class JsonIResponseService extends WebService { + public function isAuthorized(): bool { + return true; + } + + #[GetMapping] + #[ResponseBody] + #[AllowAnonymous] + public function getSpec(): JsonI { + return new SampleSpec(); + } + + public function processRequest() { + } +} From cdd937a8b8e1e1ece90dc314bc82b9e9dc643bbe Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Mon, 22 Jun 2026 00:08:09 +0300 Subject: [PATCH 3/5] feat(annotations): add path property to #[RestController] attribute - Add optional 'path' parameter to RestController for custom route paths - Add getPath()/setPath() methods to WebService - Update OpenAPIGenerator to use getPath() for spec path generation - Path supports multi-segment URLs (e.g., 'auth/login') - Falls back to service name when no path is set Closes #141 --- WebFiori/Http/Annotations/RestController.php | 3 +- WebFiori/Http/OpenAPI/OpenAPIGenerator.php | 2 +- WebFiori/Http/WebService.php | 35 ++++ .../Tests/Http/RestControllerPathTest.php | 154 ++++++++++++++++++ 4 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 tests/WebFiori/Tests/Http/RestControllerPathTest.php diff --git a/WebFiori/Http/Annotations/RestController.php b/WebFiori/Http/Annotations/RestController.php index 73d1da5..c959aa6 100644 --- a/WebFiori/Http/Annotations/RestController.php +++ b/WebFiori/Http/Annotations/RestController.php @@ -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 = '' ) { } } diff --git a/WebFiori/Http/OpenAPI/OpenAPIGenerator.php b/WebFiori/Http/OpenAPI/OpenAPIGenerator.php index 5bc9e39..62812a4 100644 --- a/WebFiori/Http/OpenAPI/OpenAPIGenerator.php +++ b/WebFiori/Http/OpenAPI/OpenAPIGenerator.php @@ -38,7 +38,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()); } } diff --git a/WebFiori/Http/WebService.php b/WebFiori/Http/WebService.php index 1e6d517..e97aa2d 100644 --- a/WebFiori/Http/WebService.php +++ b/WebFiori/Http/WebService.php @@ -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. * @@ -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. * @@ -1335,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 = ''; diff --git a/tests/WebFiori/Tests/Http/RestControllerPathTest.php b/tests/WebFiori/Tests/Http/RestControllerPathTest.php new file mode 100644 index 0000000..a45526c --- /dev/null +++ b/tests/WebFiori/Tests/Http/RestControllerPathTest.php @@ -0,0 +1,154 @@ +setPath('auth/login'); + + $manager = new WebServicesManager(); + $manager->addService($service); + $json = json_decode($manager->toOpenAPI()->toJSON() . '', true); + + $this->assertArrayHasKey('/auth/login', $json['paths']); + $this->assertArrayNotHasKey('/login', $json['paths']); + } + + /** + * Service without path should fall back to name for OpenAPI spec. + */ + public function testNoPathFallsBackToName() { + $service = new class extends WebService { + public function __construct() { + parent::__construct('users'); + } + public function isAuthorized(): bool { return true; } + public function processRequest() {} + }; + + $manager = new WebServicesManager(); + $manager->addService($service); + $json = json_decode($manager->toOpenAPI()->toJSON() . '', true); + + $this->assertArrayHasKey('/users', $json['paths']); + } + + /** + * #[RestController] with path property should configure the service path. + */ + public function testAnnotationPathProperty() { + $service = new PathAnnotatedService(); + + $this->assertEquals('login', $service->getName()); + $this->assertEquals('auth/login', $service->getPath()); + } + + /** + * #[RestController] with path should generate correct OpenAPI path. + */ + public function testAnnotationPathInOpenAPI() { + $manager = new WebServicesManager(); + $manager->addService(new PathAnnotatedService()); + $json = json_decode($manager->toOpenAPI()->toJSON() . '', true); + + $this->assertArrayHasKey('/auth/login', $json['paths']); + } + + /** + * #[RestController] without path should use name as path. + */ + public function testAnnotationWithoutPath() { + $service = new NoPathAnnotatedService(); + + $this->assertEquals('users', $service->getName()); + $this->assertEquals('users', $service->getPath()); + } + + /** + * #[RestController] with only path (no name) derives name from class. + */ + public function testAnnotationPathOnlyNoName() { + $service = new PathOnlyService(); + + $this->assertEquals('v2/items', $service->getPath()); + } + + /** + * setPath trims leading/trailing slashes. + */ + public function testSetPathTrimsSlashes() { + $service = new class extends WebService { + public function __construct() { + parent::__construct('test'); + } + public function isAuthorized(): bool { return true; } + public function processRequest() {} + }; + + $service->setPath('/api/v2/users/'); + $this->assertEquals('api/v2/users', $service->getPath()); + } + + /** + * Base path in manager combined with service path. + */ + public function testBasePathWithServicePath() { + $service = new PathAnnotatedService(); + + $manager = new WebServicesManager(); + $manager->setBasePath('/api/v1'); + $manager->addService($service); + $json = json_decode($manager->toOpenAPI()->toJSON() . '', true); + + $this->assertArrayHasKey('/api/v1/auth/login', $json['paths']); + } +} + +#[RestController(name: 'login', path: 'auth/login')] +class PathAnnotatedService extends WebService { + public function isAuthorized(): bool { return true; } + + #[GetMapping] + #[ResponseBody] + #[AllowAnonymous] + public function handle(): array { + return ['token' => 'abc']; + } + + public function processRequest() {} +} + +#[RestController(name: 'users')] +class NoPathAnnotatedService extends WebService { + public function isAuthorized(): bool { return true; } + public function processRequest() {} +} + +#[RestController(path: 'v2/items')] +class PathOnlyService extends WebService { + public function isAuthorized(): bool { return true; } + public function processRequest() {} +} From 4e4b2309dd78f02f38a8c9539379bbe497af5873 Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Mon, 22 Jun 2026 00:10:15 +0300 Subject: [PATCH 4/5] feat(openapi): add namespace scanning and built-in OpenAPISpecService - Add OpenAPIGenerator::generateFromNamespace() for auto-discovery - Add OpenAPIGenerator::discoverServices() static helper - Add OpenAPISpecService: ready-to-use service that exposes spec via GET - Namespace scan finds #[RestController] classes, excludes abstract/non-annotated Closes #144 --- WebFiori/Http/OpenAPI/OpenAPIGenerator.php | 60 ++++++++ WebFiori/Http/OpenAPI/OpenAPISpecService.php | 78 +++++++++++ .../Tests/Http/OpenAPINamespaceScanTest.php | 131 ++++++++++++++++++ 3 files changed, 269 insertions(+) create mode 100644 WebFiori/Http/OpenAPI/OpenAPISpecService.php create mode 100644 tests/WebFiori/Tests/Http/OpenAPINamespaceScanTest.php diff --git a/WebFiori/Http/OpenAPI/OpenAPIGenerator.php b/WebFiori/Http/OpenAPI/OpenAPIGenerator.php index 62812a4..1dcfef2 100644 --- a/WebFiori/Http/OpenAPI/OpenAPIGenerator.php +++ b/WebFiori/Http/OpenAPI/OpenAPIGenerator.php @@ -10,6 +10,7 @@ */ namespace WebFiori\Http\OpenAPI; +use WebFiori\Http\Annotations\RestController; use WebFiori\Http\WebService; /** @@ -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; + } } diff --git a/WebFiori/Http/OpenAPI/OpenAPISpecService.php b/WebFiori/Http/OpenAPI/OpenAPISpecService.php new file mode 100644 index 0000000..6139ed6 --- /dev/null +++ b/WebFiori/Http/OpenAPI/OpenAPISpecService.php @@ -0,0 +1,78 @@ +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() { + } +} diff --git a/tests/WebFiori/Tests/Http/OpenAPINamespaceScanTest.php b/tests/WebFiori/Tests/Http/OpenAPINamespaceScanTest.php new file mode 100644 index 0000000..4fd6ddc --- /dev/null +++ b/tests/WebFiori/Tests/Http/OpenAPINamespaceScanTest.php @@ -0,0 +1,131 @@ + $s->getName(), $services); + $this->assertContains('api-response-service', $names); + $this->assertContains('get-post-service', $names); + } + + /** + * discoverServices excludes classes without #[RestController]. + */ + public function testDiscoverServicesExcludesNonAnnotated() { + $services = OpenAPIGenerator::discoverServices('WebFiori\\Tests\\Http\\TestServices'); + + $names = array_map(fn($s) => $s->getName(), $services); + // NonAnnotatedService exists but has no #[RestController] + $this->assertNotContains('non-annotated', $names); + } + + /** + * discoverServices excludes abstract classes. + */ + public function testDiscoverServicesExcludesAbstract() { + $services = OpenAPIGenerator::discoverServices('WebFiori\\Tests\\Http\\TestServices'); + + $classes = array_map(fn($s) => get_class($s), $services); + foreach ($classes as $class) { + $this->assertFalse((new \ReflectionClass($class))->isAbstract()); + } + } + + /** + * discoverServices returns empty for non-existent namespace. + */ + public function testDiscoverServicesEmptyForUnknownNamespace() { + $services = OpenAPIGenerator::discoverServices('NonExistent\\Namespace'); + $this->assertEmpty($services); + } + + /** + * generateFromNamespace produces a valid OpenAPI spec. + */ + public function testGenerateFromNamespace() { + // Ensure classes are loaded + class_exists(OpenAPIGetPostService::class); + + $generator = new OpenAPIGenerator(); + $spec = $generator->generateFromNamespace( + 'WebFiori\\Tests\\Http\\TestServices', + 'Test API', + '2.0.0', + '/api' + ); + + $json = json_decode($spec->toJSON() . '', true); + $this->assertEquals('3.1.0', $json['openapi']); + $this->assertEquals('Test API', $json['info']['title']); + $this->assertEquals('2.0.0', $json['info']['version']); + $this->assertArrayHasKey('/api/get-post-service', $json['paths']); + } + + /** + * OpenAPISpecService returns spec via GET. + */ + public function testOpenAPISpecServiceReturnsSpec() { + // Ensure classes are loaded + class_exists(OpenAPIGetPostService::class); + + $service = new OpenAPISpecService( + 'WebFiori\\Tests\\Http\\TestServices', + '/api', + 'My API', + '3.0.0' + ); + + $response = $this->get($service); + $body = $response->getBody(); + $decoded = json_decode($body, true); + + $this->assertNotNull($decoded, 'Response should be valid JSON'); + $this->assertEquals('3.1.0', $decoded['openapi']); + $this->assertEquals('My API', $decoded['info']['title']); + $this->assertEquals('3.0.0', $decoded['info']['version']); + $this->assertArrayHasKey('paths', $decoded); + } + + /** + * OpenAPISpecService response contains no metadata. + */ + public function testOpenAPISpecServiceCleanOutput() { + class_exists(OpenAPIGetPostService::class); + + $service = new OpenAPISpecService( + 'WebFiori\\Tests\\Http\\TestServices', + '/api', + 'Test', + '1.0.0' + ); + + $response = $this->get($service); + $body = $response->getBody(); + + $this->assertStringNotContainsString('Value', $body); + $this->assertStringNotContainsString('JsonXTagName', $body); + $this->assertStringNotContainsString('"data"', $body); + } +} From 760b969c95716f5f83f0ef87e7f3eae46de4ceb7 Mon Sep 17 00:00:00 2001 From: Ibrahim BinAlshikh Date: Mon, 22 Jun 2026 00:13:28 +0300 Subject: [PATCH 5/5] docs: add example for #[ApiResponse], path, and namespace scanning --- .../ProductService.php | 58 ++++++++++++++++ .../05-openapi-namespace-scan/README.md | 67 +++++++++++++++++++ .../05-openapi-namespace-scan/index.php | 34 ++++++++++ examples/04-advanced/README.md | 9 ++- 4 files changed, 163 insertions(+), 5 deletions(-) create mode 100644 examples/04-advanced/05-openapi-namespace-scan/ProductService.php create mode 100644 examples/04-advanced/05-openapi-namespace-scan/README.md create mode 100644 examples/04-advanced/05-openapi-namespace-scan/index.php diff --git a/examples/04-advanced/05-openapi-namespace-scan/ProductService.php b/examples/04-advanced/05-openapi-namespace-scan/ProductService.php new file mode 100644 index 0000000..38b6c66 --- /dev/null +++ b/examples/04-advanced/05-openapi-namespace-scan/ProductService.php @@ -0,0 +1,58 @@ + $id, 'name' => 'Widget', 'price' => 9.99]; + } + return ['products' => [['id' => 1, 'name' => 'Widget']]]; + } + + #[PostMapping] + #[ResponseBody] + #[AllowAnonymous] + #[ApiResponse(status: '201', description: 'Product created')] + #[ApiResponse(status: '400', description: 'Invalid input')] + #[RequestParam('name', ParamType::STRING)] + #[RequestParam('price', ParamType::DOUBLE)] + public function createProduct(string $name, float $price): array { + return ['id' => 42, 'name' => $name, 'price' => $price]; + } + + #[DeleteMapping] + #[ResponseBody] + #[AllowAnonymous] + #[ApiResponse(status: '204', description: 'Product deleted')] + #[ApiResponse(status: '404', description: 'Product not found')] + #[RequestParam('id', ParamType::INT)] + public function deleteProduct(int $id): array { + return ['deleted' => $id]; + } + + public function isAuthorized(): bool { return true; } + public function processRequest() {} +} diff --git a/examples/04-advanced/05-openapi-namespace-scan/README.md b/examples/04-advanced/05-openapi-namespace-scan/README.md new file mode 100644 index 0000000..6c645d5 --- /dev/null +++ b/examples/04-advanced/05-openapi-namespace-scan/README.md @@ -0,0 +1,67 @@ +# OpenAPI Namespace Scanning & Built-in Spec Service + +Demonstrates the new OpenAPI features: +- `#[ApiResponse]` for declarative response descriptions +- `#[RestController(path: '...')]` for custom route paths +- `OpenAPIGenerator::discoverServices()` for namespace scanning +- `OpenAPISpecService` for a ready-to-use spec endpoint + +## What This Example Demonstrates + +- Declaring API responses directly on methods with `#[ApiResponse]` +- Setting a custom multi-segment path via `#[RestController(path: 'shop/products')]` +- Auto-discovering services in a namespace without manual registration +- Serving the OpenAPI spec as a live endpoint with `OpenAPISpecService` + +## Files + +- [`ProductService.php`](ProductService.php) - Service using `#[ApiResponse]` and custom path +- [`index.php`](index.php) - Generates spec using namespace scanning + +## How to Run + +```bash +php -S localhost:8080 +# Visit http://localhost:8080 to see the generated OpenAPI JSON +``` + +## Key Features + +### #[ApiResponse] — Declarative Response Descriptions + +```php +#[GetMapping] +#[ApiResponse(status: '200', description: 'List of products')] +#[ApiResponse(status: '404', description: 'Product not found')] +public function getProducts(?int $id): array { ... } +``` + +These appear in the OpenAPI spec under `responses` for each operation. + +### #[RestController(path: '...')] — Custom Route Path + +```php +#[RestController(name: 'products', path: 'shop/products')] +``` + +- `name` = service identifier (used for lookups) +- `path` = URL mount point (used in OpenAPI spec and routing) + +### OpenAPISpecService — Built-in Spec Endpoint + +```php +use WebFiori\Http\OpenAPI\OpenAPISpecService; +use WebFiori\Http\RequestProcessor; + +$specService = new OpenAPISpecService( + 'App\\Apis', // Namespace to scan + '/apis', // Base path + 'My API', // Title + '1.0.0' // Version +); + +$processor = new RequestProcessor(); +$processor->process($specService); +``` + +Point Swagger UI at this endpoint to get live, auto-generated documentation. diff --git a/examples/04-advanced/05-openapi-namespace-scan/index.php b/examples/04-advanced/05-openapi-namespace-scan/index.php new file mode 100644 index 0000000..4e31f1a --- /dev/null +++ b/examples/04-advanced/05-openapi-namespace-scan/index.php @@ -0,0 +1,34 @@ +generate( + OpenAPIGenerator::discoverServices(''), // Scans global namespace here + 'Shop API', + '1.0.0', + '/apis' +); + +header('Content-Type: application/json'); +echo $spec->toJSON(); + +// --- Approach 2: Built-in OpenAPISpecService --- +// Uncomment below to serve the spec as a live endpoint: +// +// $specService = new OpenAPISpecService( +// 'App\\Apis', // Namespace to scan +// '/apis', // Base path in spec +// 'Shop API', // Title +// '1.0.0' // Version +// ); +// $processor = new RequestProcessor(); +// $processor->process($specService); diff --git a/examples/04-advanced/README.md b/examples/04-advanced/README.md index 4e46691..6e8de3d 100644 --- a/examples/04-advanced/README.md +++ b/examples/04-advanced/README.md @@ -5,18 +5,17 @@ This folder demonstrates advanced WebFiori HTTP patterns and techniques. ## Examples 1. **[01-object-mapping](01-object-mapping/)** - Request to object mapping with MapEntity attribute -2. **02-custom-filters** - Custom parameter validation -3. **03-exception-handling** - Global exception handling -4. **04-middleware-pattern** - Request/response interceptors -5. **05-streaming-responses** - Large data streaming +2. **[02-openapi-docs](02-openapi-docs/)** - OpenAPI spec generation with standalone generator 3. **[03-manual-openapi](03-manual-openapi/)** - Using OpenAPIObj to serve API documentation +4. **[04-request-processor](04-request-processor/)** - Processing services with RequestProcessor +5. **[05-openapi-namespace-scan](05-openapi-namespace-scan/)** - Namespace scanning, #[ApiResponse], and built-in spec service ## Advanced Concepts - Object-oriented request handling with MapEntity attribute - Custom validation and filtering - Structured exception handling -- Middleware and interceptors +- OpenAPI spec generation and auto-discovery - Performance optimization techniques ## Prerequisites