# swagger-php swagger-php is a PHP library that generates interactive OpenAPI documentation for RESTful APIs using PHP 8+ attributes (preferred) or doctrine annotations. It scans your PHP codebase, extracts API metadata from attributes/annotations attached to classes, methods, and properties, then produces an OpenAPI 3.0, 3.1, or 3.2 specification document in YAML or JSON format. The library supports automatic type resolution from PHP type hints and PHPDoc comments, making schema definition simpler. The library provides both a command-line interface for generating static documentation files and a programmatic PHP API through the `Generator` class for dynamic, on-the-fly documentation generation. It includes a comprehensive set of attributes that map directly to OpenAPI specification elements, along with built-in processors that augment, merge, and validate annotations during the generation process. ## Generator Class - Basic Usage The `Generator` class is the main entry point for programmatically generating OpenAPI specifications. It scans source files, processes annotations, and outputs the complete specification. ```php generate(['/path/to/your/api']); // Output as YAML header('Content-Type: application/x-yaml'); echo $openapi->toYaml(); // Or output as JSON header('Content-Type: application/json'); echo $openapi->toJson(); ``` ## Generator Class - Advanced Configuration The Generator supports extensive customization including custom processors, version selection, file filtering, and custom analyzers for complex projects. ```php files() ->name('*.php') ->in(__DIR__); $context = new \OpenApi\Context(); $openapi = (new \OpenApi\Generator($logger)) ->setProcessorPipeline(new \OpenApi\Pipeline([/* custom processors */])) ->setAnalyser(new \OpenApi\Analysers\ReflectionAnalyser([ new \OpenApi\Analysers\DocBlockAnnotationFactory(), new \OpenApi\Analysers\AttributeAnnotationFactory() ])) ->setVersion(\OpenApi\Annotations\OpenApi::VERSION_3_1_0) ->generate(['/path/to/project', $finder], new \OpenApi\Analysis([], $context), $validate); // Using SourceFinder with exclude patterns $exclude = ['tests', 'vendor']; $pattern = '*.php'; $openapi = (new \OpenApi\Generator()) ->generate(new \OpenApi\SourceFinder(__DIR__, $exclude, $pattern)); ``` ## Command Line Interface The `openapi` CLI tool generates OpenAPI documentation to static YAML or JSON files. It supports various options for customization including exclusions, bootstrap files, and processor configuration. ```bash # Basic usage - scan 'app' directory, output to openapi.yaml ./vendor/bin/openapi app -o openapi.yaml # Output as JSON (format detected from extension) ./vendor/bin/openapi app -o openapi.json # Force specific format ./vendor/bin/openapi app -o api-spec --format yaml # Exclude directories ./vendor/bin/openapi app -o openapi.yaml --exclude vendor,tests # Use specific OpenAPI version ./vendor/bin/openapi app -o openapi.yaml --version 3.1.0 # Configure processors via command line ./vendor/bin/openapi app -o openapi.yaml -c operationId.hash=false # Bootstrap file for constants/autoloading ./vendor/bin/openapi -b config/constants.php app -o openapi.yaml # Filter by file pattern ./vendor/bin/openapi app --pattern "*.php" -o openapi.yaml # Show all options ./vendor/bin/openapi --help ``` ## Info Attribute - API Metadata The `#[OA\Info]` attribute defines top-level API metadata including title, version, description, contact information, and license. This is required for a valid OpenAPI specification. ```php 1, 'name' => 'Admin', 'role' => 'admin'] ), new OA\Examples( example: 'regular', summary: 'Regular user', value: ['id' => 2, 'name' => 'John', 'role' => 'user'] ) ] ) )] public function getUser(int $id) { } } #[OA\Schema] class User { #[OA\Property] public int $id; #[OA\Property] public string $name; #[OA\Property] public string $role; } ``` ## SecurityScheme Attribute - Authentication Configuration Security schemes define authentication methods including API keys, OAuth2, HTTP bearer tokens, and OpenID Connect. ```php 'Read user information', 'write:users' => 'Modify user information', 'admin' => 'Full administrative access' ] ) ] )] class SecuritySpec { } // Apply security to operations class SecureController { // Single security scheme #[OA\Get( path: '/secure/data', security: [['bearerAuth' => []]], tags: ['secure'] )] #[OA\Response(response: 200, description: 'Secured data')] public function getSecureData() { } // OAuth2 with specific scopes #[OA\Post( path: '/users', security: [['oauth2' => ['write:users']]], tags: ['users'] )] #[OA\Response(response: 201, description: 'User created')] public function createUser() { } // Multiple security options (OR logic) #[OA\Get( path: '/flexible', security: [ ['bearerAuth' => []], ['api_key' => []] ], tags: ['secure'] )] #[OA\Response(response: 200, description: 'Success')] public function flexibleAuth() { } } // Global default security for all endpoints #[OA\OpenApi( openapi: OA\OpenApi::VERSION_3_1_0, security: [['bearerAuth' => []]] )] #[OA\Info(version: '1.0.0', title: 'Secure API')] class GlobalSecuritySpec { } ``` ## Enum Support - PHP 8.1+ Native Enums swagger-php supports PHP 8.1+ native enums, automatically generating enum schemas with proper values. ```php Cat::class, 'dog' => Dog::class ] ) )] class Pet { } // Response with union types class PetController { #[OA\Get(path: '/pets/{id}', tags: ['pets'])] #[OA\Response( response: 200, description: 'Pet details', content: new OA\JsonContent( oneOf: [ new OA\Schema(ref: Cat::class), new OA\Schema(ref: Dog::class) ] ) )] public function getPet(int $id) { } } ``` ## File Upload - Multipart Form Data swagger-php supports file upload endpoints with multipart/form-data encoding and binary content types. ```php ['url' => 'https://example.com/logo.png'], 'tagGroups' => [ ['name' => 'User Management', 'tags' => ['users', 'auth']], ['name' => 'Content', 'tags' => ['posts', 'comments']] ] ] )] class ExtendedSpec { } class ExtendedController { #[OA\Get( path: '/internal/status', tags: ['internal'], x: [ 'internal' => true, 'rateLimit' => ['requests' => 100, 'period' => '1m'], 'codeSamples' => [ ['lang' => 'curl', 'source' => 'curl -X GET https://api.example.com/internal/status'] ] ] )] #[OA\Response(response: 200, description: 'Status')] public function status() { } } #[OA\Schema( x: [ 'examples' => [ 'basic' => ['id' => 1, 'name' => 'Example'] ] ] )] class ExtendedModel { #[OA\Property(x: ['deprecated-reason' => 'Use newField instead'])] public string $oldField; } ``` ## Processor Configuration - Customizing Generation Processors can be configured to modify how the OpenAPI specification is generated, including operation ID formatting, path filtering, and cleanup options. ```php setConfig([ // Use hashed operation IDs instead of clear text 'operationId.hash' => true, // Filter paths by tags (regex patterns) 'pathFilter.tags' => ['/pets/', '/users/'], // Filter by path patterns 'pathFilter.paths' => ['/api\/v1\/.*/'], // Clean unused components 'cleanUnusedComponents.enabled' => true, // Preserve all tags even if unused 'augmentTags.whitelist' => ['*'], // Allow multiple @OA\Components to be merged 'mergeIntoOpenApi.mergeComponents' => true, // Augment operation parameters from docblocks 'augmentParameters.augmentOperationParameters' => true, ]) ->generate(['/path/to/api']); echo $openapi->toYaml(); ``` ## Custom Response Classes - Reusable Responses Create custom response classes to reduce boilerplate and ensure consistency across your API. ```php