Search by

OpenAPI specification generator and Swagger UI for PHP 8.1-8.4 projects (standalone and Nette Framework)

Package info

github.com/michalpospiech/swagger

pkg:composer/michalpospiech/swagger

Statistics

Installs: 3

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

2.0.1 2026-12-02 17:16 UTC

This package is auto-updated.

Last update: 2026-12-02 17:17:20 UTC


README

Composer package for OpenAPI specification generation and Swagger UI in PHP projects. Provides a unified interface for generating OpenAPI documentation from annotations/attributes and displaying an interactive Swagger UI.

The package is modular - you can use only the OpenAPI generator, only the Swagger UI, or both together.

Features

  • OpenAPI 3.0 specification generation from PHP doctrine annotations and native PHP attributes
  • JSON and YAML output formats
  • Bundled Swagger UI assets (offline-capable, no CDN dependency)
  • Automatic cache with filemtime-based invalidation
  • PSR-16 (SimpleCache) cache adapter support
  • Standalone plain-PHP handler - no framework required
  • Nette DI extension with NEON configuration
  • Independent access guards for UI and spec routes
  • Fully configurable Swagger UI options

Requirements

  • PHP ^8.1 (8.1-8.4); for PHP 7.2-8.0 use the original esportscz/swagger 1.x
  • zircote/swagger-php 4.1+, 5.x, 6.x or 7.x (6.x and 7.x need PHP 8.2+; Composer picks the newest one your PHP allows)
  • Composer

Optional:

  • symfony/yaml - required for YAML output format
  • nette/di ^3.1 - required for Nette DI extension
  • nette/application ^3.1.4 - required for Nette route wiring

Installation

composer require michalpospiech/swagger

For YAML output support:

composer require symfony/yaml

Nette Integration

Requires nette/di ^3.1 (install it with composer require nette/di).

Minimal Configuration

extensions:
    swagger: MichalPospiech\Swagger\DI\SwaggerExtension

swagger:
    # Directories to scan for OpenAPI annotations / PHP 8 attributes
    # When omitted or empty, PSR-4 auto-discovery from composer.json is used as fallback
    scanPaths:
        - %appDir%/Api

Full NEON Configuration

extensions:
    swagger: MichalPospiech\Swagger\DI\SwaggerExtension

swagger:
    # Directories to scan for OpenAPI annotations / PHP 8 attributes
    # When omitted or empty, PSR-4 auto-discovery from composer.json is used as fallback
    scanPaths:
        - %appDir%/Api
        - %appDir%/Controllers

    # Directories to exclude from scanning (default: [])
    excludePaths:
        - %appDir%/Api/Internal

    # Page title shown in Swagger UI header and browser tab (default: 'API Documentation')
    title: My Application API

    # OpenAPI specification version: '3.0' or '3.1' (default: '3.0')
    # OpenAPI 3.1 requires swagger-php 4.2+
    version: '3.0'

    # Output format for the spec endpoint: 'json' or 'yaml' (default: 'json')
    # YAML requires: composer require symfony/yaml
    outputFormat: json

    # Directory for the file-based spec cache (default: %tempDir%/swagger)
    cachePath: %tempDir%/swagger

    # Enable or disable caching (default: true)
    # When a PSR-16 CacheInterface service is registered in the container,
    # FileCacheAdapter is automatically replaced with Psr16CacheAdapter
    cacheEnabled: true

    # Persist Swagger UI auth tokens across page reloads (default: true)
    persistAuthorization: true

    # Enable the "Try it out" button in Swagger UI by default (default: true)
    tryItOut: true

    # Initial expansion state of operations and tags: 'none' | 'list' | 'full' (default: 'list')
    docExpansion: list

    # Custom CSS injected as inline <style> block in the Swagger UI page (default: null)
    customCss: |
        .swagger-ui .markdown li {
            margin-bottom: 0.5em;
        }

    # Custom JS injected as inline <script> block in <head> (default: null)
    # ⚠️ Raw JS — see "Security note: raw JS in config" below.
    # customJs: |
    #     window.MyHelper = function() { /* ... */ };

    # Swagger UI plugins appended to plugins:[...] as raw JS identifiers (default: [])
    # Each entry is a JS expression that must evaluate to a Swagger UI plugin
    # (already defined in window/global scope via customJs or external <script>).
    # uiPlugins:
    #     - window.MyHelper

    # SwaggerUIBundle request/response/onComplete hooks as raw JS function literals
    # (default: null). Injected into the third Object.assign(...) argument so they
    # override any value coming from the JSON config.
    # requestInterceptor: |
    #     function(req) { return req; }
    # responseInterceptor: |
    #     function(res) { return res; }
    # onComplete: |
    #     function() { console.log('Swagger UI ready'); }

    # Built-in Idempotency-Key plugin (default: false). When true, the package
    # serves assets/idempotency-key-plugin.js and activates it automatically —
    # adds silent auto-gen + topbar "Regenerate Idempotency-Key" button.
    # Accepts either a bool (shorthand for enabled: <bool> with defaults), or
    # a structure customising which parameter / header names to target.
    idempotencyKeyPlugin: false
    # idempotencyKeyPlugin:
    #     enabled: true
    #     paramNames:
    #         - 'Idempotency-Key'
    #         - 'X-Idempotency-Key'
    #     caseInsensitive: true

    # Arbitrary SwaggerUIBundle options as key-value pairs (default: {})
    # Merged on top of the typed options above - uiOptions win on conflict
    uiOptions:
        filter: true
        deepLinking: true

    # Route prefix for Nette router wiring (default: '/swagger')
    # Registers: {prefix}, {prefix}/spec.json, {prefix}/spec.yaml, {prefix}/assets/<file>
    routePrefix: /swagger

    # OpenAPI generation module
    openapi:
        # Enable OpenAPI spec generation - registers SpecGenerator + cache (default: true)
        enabled: true

    # Swagger UI module
    ui:
        # Enable Swagger UI - registers UiRenderer, AssetLocator and routes (default: true)
        enabled: true

        # External spec URL - overrides the default /spec.json path (default: null)
        # Required when openapi.enabled is false and ui.enabled is true
        # Mutually exclusive with specUrls
        specUrl: null

        # Multiple spec URLs - shows a dropdown to switch between specs (default: null)
        # Each entry requires 'url' and 'name' keys
        # Mutually exclusive with specUrl
        # specUrls:
        #     - url: 'https://api-v1.example.com/openapi.json'
        #       name: 'API v1'
        #     - url: 'https://api-v2.example.com/openapi.json'
        #       name: 'API v2'

        # Default spec shown in the dropdown when specUrls is used (default: null)
        # specUrlsPrimaryName: 'API v1'

NEON Configuration Reference

Key Type Default Description
scanPaths string[] [] Directories to scan (empty = PSR-4 auto-discovery)
excludePaths string[] [] Directories to exclude
title string 'API Documentation' Page title
version string '3.0' OpenAPI version
outputFormat json|yaml json Output format
cachePath string|null null Cache directory path
cacheEnabled bool true Enable/disable caching
persistAuthorization bool true Persist auth tokens
tryItOut bool true Enable Try It Out
docExpansion none|list|full list Initial expansion state
customCss string|null null Custom CSS injected as inline <style> block
customJs string|null null Custom JS injected as inline <script> block in <head> (raw JS)
uiPlugins string[] [] Raw JS identifiers appended to SwaggerUIBundle plugins:[...]
requestInterceptor string|null null Raw JS function literal — SwaggerUIBundle requestInterceptor hook
responseInterceptor string|null null Raw JS function literal — SwaggerUIBundle responseInterceptor hook
onComplete string|null null Raw JS function literal — SwaggerUIBundle onComplete hook
idempotencyKeyPlugin bool|structure false Bundled Idempotency-Key plugin — bool shorthand or {enabled, paramNames, caseInsensitive}
uiOptions array [] Extra SwaggerUIBundle options
routePrefix string '/swagger' Route prefix for Nette router
openapi.enabled bool true Enable OpenAPI spec generation (SpecGenerator + cache)
ui.enabled bool true Enable Swagger UI (UiRenderer + AssetLocator + routes)
ui.specUrl string|null null External spec URL for UI (overrides /spec.json)
ui.specUrls array|null null Multiple spec URLs - shows dropdown (each entry: {url, name})
ui.specUrlsPrimaryName string|null null Default spec name in dropdown when specUrls is used

Modular Configuration

Disable modules you don't need:

# Generator only - no UI services or routes
swagger:
    scanPaths:
        - %appDir%/Api
    ui:
        enabled: false
# UI only - point at an external spec, no local generator
swagger:
    scanPaths: []
    openapi:
        enabled: false
    ui:
        specUrl: 'https://api.example.com/openapi.json'
# UI only - multiple external specs with dropdown selector
swagger:
    scanPaths: []
    openapi:
        enabled: false
    ui:
        specUrls:
            - url: 'https://api-v1.example.com/openapi.json'
              name: 'API v1'
            - url: 'https://api-v2.example.com/openapi.json'
              name: 'API v2'
        specUrlsPrimaryName: 'API v2'

Note: When openapi.enabled: false and ui.enabled: true, either ui.specUrl or ui.specUrls is required - the extension throws InvalidStateException if neither is set. The two options are mutually exclusive.

PSR-16 Cache Auto-Discovery

When a Psr\SimpleCache\CacheInterface service exists in the DI container (registered by your application), SwaggerExtension automatically replaces the default FileCacheAdapter with Psr16CacheAdapter wrapping your PSR-16 instance.

No configuration is needed - the swap happens transparently in beforeCompile().

Presenter

When nette/application is installed, the extension automatically:

  1. Registers DefaultPresenter as a DI service (handles all Swagger routes)
  2. Sets up module mapping Swagger -> MichalPospiech\Swagger\Presenter\*Presenter in PresenterFactory

No manual presenter creation is needed. After registering the extension and configuring scanPaths, Swagger UI is available at routePrefix (default: /swagger).

The presenter handles 4 actions:

Action Route Description
ui {routePrefix} Renders Swagger UI HTML page
specJson {routePrefix}/spec.json Returns OpenAPI spec as JSON
specYaml {routePrefix}/spec.yaml Returns OpenAPI spec as YAML
asset {routePrefix}/assets/<file> Serves bundled Swagger UI static assets

When openapi.enabled: false (UI-only mode with ui.specUrl), the spec actions redirect to the configured external URL.

Route Wiring

When Nette\Routing\Router is found in the DI container, the extension automatically registers routes under routePrefix. If no Router service is found, route wiring is silently skipped.

Standalone Usage

Drop a swagger.php file into your project's public directory:

<?php
require __DIR__ . '/../vendor/autoload.php';

use MichalPospiech\Swagger\SwaggerConfig;
use MichalPospiech\Swagger\Spec\SpecGenerator;
use MichalPospiech\Swagger\Ui\AssetLocator;
use MichalPospiech\Swagger\Ui\UiRenderer;
use MichalPospiech\Swagger\Handler\StandaloneHandler;

$config = (new SwaggerConfig())
    ->setScanPaths([__DIR__ . '/../src/Api'])
    ->setTitle('My API')
    ->setCachePath(__DIR__ . '/../temp/swagger');

$generator  = new SpecGenerator($config);
$locator    = new AssetLocator();
$renderer   = new UiRenderer($locator);
$handler    = new StandaloneHandler($config, $generator, $renderer, $locator);
$handler->handle();

Routing

StandaloneHandler::handle() reads $_SERVER['REQUEST_URI'] and dispatches to the appropriate response:

Path Response
/ or /index Swagger UI HTML page
/spec.json OpenAPI spec (JSON)
/spec.yaml OpenAPI spec (YAML)
/assets/* Bundled Swagger UI static assets (JS, CSS, PNG)
Any other path 404 plain text

Access Guards

Protect the UI or the spec endpoint independently:

$handler = new StandaloneHandler($config, $generator, $renderer, $locator);

// Protect UI with HTTP Basic Auth
$handler->setUiGuard(function () {
    $user = $_SERVER['PHP_AUTH_USER'] ?? '';
    $pass = $_SERVER['PHP_AUTH_PW'] ?? '';
    return $user === 'admin' && $pass === 'secret';
});

// Keep spec endpoint public (e.g. for API clients)
// $handler->setSpecGuard(function () { return isApiClient(); });

$handler->handle();

Both guards default to null, which means public access by default. A guard returning false triggers a 403 Forbidden response.

Configuration Reference

All configuration is done via SwaggerConfig, a fluent builder:

$config = (new SwaggerConfig())
    ->setScanPaths([...])
    ->setTitle('My API');

setScanPaths(array $paths): self

Directories to scan for OpenAPI annotations/attributes.

  • Default: []
  • Note: When empty, auto-discovery reads PSR-4 namespaces from composer.json. When explicit paths are set, PSR-4 auto-discovery is skipped entirely.
$config->setScanPaths([
    __DIR__ . '/src/Api',
    __DIR__ . '/src/Controller',
]);

setExcludePaths(array $paths): self

Directories to exclude from scanning (applied after path resolution).

  • Default: []
$config->setExcludePaths([
    __DIR__ . '/src/Api/Internal',
]);

setTitle(string $title): self

Page title shown in the browser tab and Swagger UI header.

  • Default: 'API Documentation'
$config->setTitle('My Application API');

setVersion(string $version): self

OpenAPI specification version to generate.

  • Default: '3.0'
  • Accepted values: '3.0' or '3.1' (3.1 requires swagger-php 4.2+)
$config->setVersion('3.1');

setOutputFormat(string $format): self

Serialisation format for the generated spec.

  • Default: 'json'
  • Accepted values: 'json' or 'yaml'
  • Note: 'yaml' requires symfony/yaml installed.
$config->setOutputFormat('yaml');

setCachePath(string $path): self

Directory where generated specs are stored by FileCacheAdapter.

  • Default: null (falls back to sys_get_temp_dir() . '/swagger-cache')
$config->setCachePath(__DIR__ . '/temp/swagger');

disableCache(): self

Disable caching entirely. The spec is regenerated on every request.

  • Default cache state: enabled
$config->disableCache();

setPersistAuthorization(bool $value): self

When true, Swagger UI persists authorization tokens across page reloads.

  • Default: true
$config->setPersistAuthorization(false);

setTryItOut(bool $value): self

When true, the "Try it out" button is enabled in Swagger UI by default.

  • Default: true
$config->setTryItOut(false);

setDocExpansion(string $value): self

Controls the initial expansion state of operations and tags.

  • Default: 'list'
  • Accepted values: 'none' | 'list' | 'full'
$config->setDocExpansion('none'); // collapse everything on load

setCustomCss(?string $css): self

Inject custom CSS as an inline <style> block in the Swagger UI page head. Useful for tweaking Swagger UI styling without creating a separate CSS file.

  • Default: null (no custom CSS)
$config->setCustomCss('.swagger-ui .markdown li { margin-bottom: 0.5em; }');

setCustomJs(?string $js): self

Inject custom JavaScript as an inline <script> block in the Swagger UI page <head>, executed before the SwaggerUIBundle init script. Useful for defining global plugins, helpers, or globals that the SwaggerUIBundle config later references (see setUiPlugins()).

  • Default: null (no inline script)
  • ⚠️ Raw JS — see "Security note: raw JS in config" below.
$config->setCustomJs('window.MyHelper = function() { /* ... */ };');

setUiPlugins(array $plugins): self

List of raw JS identifiers appended to SwaggerUIBundle's plugins:[...] array, after the default SwaggerUIBundle.plugins.DownloadUrl. Each entry must be a JS expression that evaluates to a Swagger UI plugin at runtime — typically a global declared via setCustomJs() or an external script.

  • Default: []
  • ⚠️ Raw JS — values are emitted verbatim (no escaping).
$config->setUiPlugins([
    'window.MyHelperPlugin',
    'SomeNamespace.AnotherPlugin',
]);

setRequestInterceptor(?string $js): self

Raw JS function literal for SwaggerUIBundle's requestInterceptor hook. Called before every outgoing Try-it-out request — receives the request object, returns it (optionally mutated).

  • Default: null
  • ⚠️ Raw JS — emitted as-is into the SwaggerUIBundle constructor.
$config->setRequestInterceptor(<<<'JS'
function(req) {
    req.headers['X-Trace-Id'] = crypto.randomUUID();
    return req;
}
JS);

setResponseInterceptor(?string $js): self

Raw JS function literal for SwaggerUIBundle's responseInterceptor hook. Called for every response — receives the response object, returns it (optionally mutated).

  • Default: null
  • ⚠️ Raw JS
$config->setResponseInterceptor('function(res) { console.log(res.status); return res; }');

setOnComplete(?string $js): self

Raw JS function literal for SwaggerUIBundle's onComplete hook. Called once Swagger UI has finished loading the spec.

  • Default: null
  • ⚠️ Raw JS
$config->setOnComplete('function() { console.log("Swagger UI ready"); }');

setIdempotencyKeyPluginEnabled(bool $value): self

Enable the built-in Idempotency-Key plugin bundled with this package (assets/idempotency-key-plugin.js). When enabled:

  1. The plugin file is served at {routePrefix}/assets/idempotency-key-plugin.js (transparent — same asset route as Swagger UI vendor files).
  2. An inline <script>window.SwaggerIdempotencyKeyPluginOptions = {...};</script> block is emitted with the plugin options (paramNames, caseInsensitive).
  3. A <script src="…"> tag is injected into the page <head> so the global window.SwaggerIdempotencyKeyPlugin is loaded before SwaggerUIBundle starts.
  4. The plugin is automatically appended to plugins:[...].

Features:

  • Silent auto-gen: every outgoing request whose targeted header is present but blank gets a fresh UUID via crypto.randomUUID() in the preFetch hook.
  • Topbar refresh button ("🔑 Regenerate Idempotency-Key", slides in from the right on hover) — writes a new UUID into every Try-it-out parameter whose name matches paramNames via the Swagger UI Redux store, so values survive component re-renders.

Use setIdempotencyKeyPluginParamNames() and setIdempotencyKeyPluginCaseInsensitive() to customise which parameter / header names the plugin targets (default: exact match against 'Idempotency-Key').

  • Default: false
$config->setIdempotencyKeyPluginEnabled(true);

In NEON the same can be done via the bool shorthand or the full structure:

# Shorthand — enables with defaults (paramNames: ['Idempotency-Key'], case-sensitive)
swagger:
    idempotencyKeyPlugin: true

# Structured — full customisation
swagger:
    idempotencyKeyPlugin:
        enabled: true
        paramNames:
            - 'Idempotency-Key'
            - 'X-Idempotency-Key'
        caseInsensitive: true

setIdempotencyKeyPluginParamNames(array $names): self

List of parameter / header names the bundled Idempotency-Key plugin targets. Each entry is matched against:

  • request header keys inside the preFetch hook (silent auto-gen when blank),

  • Try-it-out parameter name values when the topbar refresh button is clicked.

  • Default: ['Idempotency-Key']

  • Match: exact by default; case-insensitive when setIdempotencyKeyPluginCaseInsensitive(true) is set.

$config->setIdempotencyKeyPluginParamNames([
    'Idempotency-Key',
    'X-Idempotency-Key',
    'Request-Id',
]);

setIdempotencyKeyPluginCaseInsensitive(bool $value): self

When true, the bundled Idempotency-Key plugin compares parameter / header names case-insensitively. Useful when client code emits headers in lowercase (idempotency-key) and the spec declares the parameter in canonical case.

  • Default: false
$config->setIdempotencyKeyPluginCaseInsensitive(true);

Security note: raw JS in config

The keys customJs, uiPlugins, requestInterceptor, responseInterceptor, and onComplete accept raw JavaScript that is emitted verbatim into the rendered Swagger UI HTML — no escaping, no sanitisation.

This is intentional: they are developer-controlled configuration (PHP / NEON), not user input. The threat model is "the app operator writes the config".

Never pass user-supplied data (request parameters, database values, etc.) into these keys. Doing so trivially yields stored XSS on the Swagger UI page.

setUiOptions(array $options): self

Pass arbitrary SwaggerUIBundle options as a key-value array. These are merged on top of the typed setters, so uiOptions values take precedence.

  • Default: []
$config->setUiOptions([
    'filter'      => true,
    'deepLinking' => true,
    'maxDisplayedTags' => 5,
]);

setSpecUrl(?string $url): self

Set a custom spec URL for Swagger UI. When set, the UI loads the OpenAPI specification from this URL instead of the default /spec.json. Required for UI-only mode (openapi.enabled: false) unless setSpecUrls() is used. Mutually exclusive with setSpecUrls().

  • Default: null (uses /spec.json)
$config->setSpecUrl('https://api.example.com/openapi.json');

setSpecUrls(array $urls): self

Set multiple spec URLs for Swagger UI. When set, the UI displays a dropdown selector allowing users to switch between different OpenAPI specifications. Each entry must be an associative array with url and name keys. Mutually exclusive with setSpecUrl().

  • Default: null
$config->setSpecUrls([
    ['url' => 'https://api-v1.example.com/openapi.json', 'name' => 'API v1'],
    ['url' => 'https://api-v2.example.com/openapi.json', 'name' => 'API v2'],
]);

setSpecUrlsPrimaryName(?string $name): self

Select which spec is shown first in the dropdown when setSpecUrls() is used. The name must match one of the name values in the specUrls array.

  • Default: null (first spec in the array)
$config->setSpecUrlsPrimaryName('API v2');

setOpenApiEnabled(bool $value): self

Enable or disable the OpenAPI generation module. When disabled, SpecGenerator and the cache service are not registered in Nette DI.

  • Default: true
$config->setOpenApiEnabled(false); // UI-only mode

setUiEnabled(bool $value): self

Enable or disable the Swagger UI module. When disabled, UiRenderer and AssetLocator are not registered in Nette DI and route wiring is skipped.

  • Default: true
$config->setUiEnabled(false); // generator-only mode

Recipes

Idempotency-Key auto-generation

Use case: APIs that accept an Idempotency-Key request header want Try-it-out to send a fresh UUID per request without forcing the user to type one.

Easy mode — flip on the bundled plugin (silent auto-gen + a topbar "🔑 Regenerate Idempotency-Key" button that writes a fresh UUID into every visible Try-it-out field):

swagger:
    idempotencyKeyPlugin: true

Custom header name — point the plugin at a non-default header name, or match multiple names case-insensitively:

swagger:
    idempotencyKeyPlugin:
        enabled: true
        paramNames:
            - 'Idempotency-Key'
            - 'X-Idempotency-Key'
        caseInsensitive: true

Silent-only mode — no UI button, just fill in blank values before the request leaves the browser:

swagger:
    requestInterceptor: |
        function(req) {
            if (req.headers && 'Idempotency-Key' in req.headers) {
                var v = req.headers['Idempotency-Key'];
                if (!v || ('' + v).trim() === '') {
                    req.headers['Idempotency-Key'] = crypto.randomUUID();
                }
            }
            return req;
        }

Custom plugin — ship your own Swagger UI plugin via customJs and register it through uiPlugins:

swagger:
    customJs: |
        window.MyOrgIdempotencyKeyPlugin = function() {
            return {
                fn: {
                    preFetch: function(req) {
                        // your custom logic
                        return req;
                    }
                }
            };
        };
    uiPlugins:
        - window.MyOrgIdempotencyKeyPlugin

OpenAPI Annotations

Doctrine Annotations

Docblock annotations are deprecated since swagger-php 6.11 and will be removed in swagger-php 8. They still work with 7.x (a silenced E_USER_DEPRECATED is triggered); prefer native attributes in new code.

<?php

use OpenApi\Annotations as OA;

/**
 * @OA\Get(
 *   path="/users",
 *   summary="List all users",
 *   @OA\Response(response=200, description="Success")
 * )
 */
class UserController
{
    // ...
}

Native Attributes

<?php

use OpenApi\Attributes as OA;

class UserController
{
    #[OA\Get(path: '/users', summary: 'List all users')]
    #[OA\Response(response: 200, description: 'Success')]
    public function index(): void
    {
        // ...
    }
}

Full annotation reference: zircote/swagger-php documentation

Cache

Default File Cache

When cacheEnabled is true (default) and setCachePath() is configured, specs are stored as files in the specified directory:

$config = (new SwaggerConfig())
    ->setScanPaths([__DIR__ . '/src/Api'])
    ->setCachePath(__DIR__ . '/temp/swagger');

If setCachePath() is not called, files are stored in sys_get_temp_dir() . '/swagger-cache'.

Cache Invalidation

Cache keys are derived from:

  • File modification times (filemtime) of all scanned source files
  • Configuration hash (version, output format, exclude paths)

The cache is automatically invalidated when any source file changes or config changes.

PSR-16 Adapter

Inject any PSR-16 compatible cache (Redis, Memcached, APCu, etc.):

use MichalPospiech\Swagger\Cache\Psr16CacheAdapter;

$psr16Cache = new YourApp\RedisCache(); // implements Psr\SimpleCache\CacheInterface
$cacheAdapter = new Psr16CacheAdapter($psr16Cache);

$generator = new SpecGenerator($config, null, $cacheAdapter);

Disabling Cache

$config = (new SwaggerConfig())
    ->setScanPaths([__DIR__ . '/src/Api'])
    ->disableCache();

Module Independence

The package is split into three independent modules that can be used separately:

MOD-01: OpenAPI Generator Only (no UI)

Use SpecGenerator without any UI components:

use MichalPospiech\Swagger\SwaggerConfig;
use MichalPospiech\Swagger\Spec\SpecGenerator;

$config = (new SwaggerConfig())
    ->setScanPaths([__DIR__ . '/src/Api'])
    ->setOutputFormat('json');

$generator = new SpecGenerator($config);
$json = $generator->generate();

header('Content-Type: application/json');
echo $json;

Use case: Expose the spec for external tooling (Postman, code generation) without hosting a UI.

MOD-02: Swagger UI Only (external spec URL)

Use UiRenderer with an external spec URL - no local generator needed:

use MichalPospiech\Swagger\Ui\AssetLocator;
use MichalPospiech\Swagger\Ui\UiRenderer;
use MichalPospiech\Swagger\SwaggerConfig;

$config = (new SwaggerConfig())->setTitle('External API Docs');
$locator = new AssetLocator();
$renderer = new UiRenderer($locator);

$html = $renderer->render(
    $config,
    'https://api.example.com/spec.json', // external spec URL
    '/assets/swagger-ui.css',
    '/assets/swagger-ui-bundle.js',
    '/assets/swagger-ui-standalone-preset.js'
);

header('Content-Type: text/html; charset=UTF-8');
echo $html;

Use case: Host a UI pointing at a spec generated elsewhere.

MOD-03: Generator + UI Without Handler

Wire SpecGenerator and UiRenderer without StandaloneHandler (e.g. in a framework controller):

use MichalPospiech\Swagger\SwaggerConfig;
use MichalPospiech\Swagger\Spec\SpecGenerator;
use MichalPospiech\Swagger\Ui\AssetLocator;
use MichalPospiech\Swagger\Ui\UiRenderer;

$config    = (new SwaggerConfig())->setScanPaths([__DIR__ . '/src/Api']);
$generator = new SpecGenerator($config);
$locator   = new AssetLocator();
$renderer  = new UiRenderer($locator);

// In your router/controller:
if ($request->getPath() === '/api/spec.json') {
    return new JsonResponse($generator->generate());
}

if ($request->getPath() === '/api/docs') {
    $html = $renderer->render($config, '/api/spec.json', ...);
    return new HtmlResponse($html);
}

Examples

See the examples/ directory for ready-to-use example files:

File Description
examples/standalone.php Minimal standalone setup
examples/standalone-with-guards.php Standalone with UI access guard
examples/nette-config.neon Minimal Nette NEON configuration
examples/nette-config-full.neon Full Nette NEON configuration with all options
examples/generator-only.php OpenAPI generation without UI (MOD-01)
examples/custom-cache.php PSR-16 cache adapter injection

Development

Docker setup

docker-compose up -d
docker-compose exec server bash

Running tests

composer check:tests

Running static analysis

composer check:phpstan

Running coding standard

composer check:phpcs

To auto-fix coding standard violations:

composer check:phpcbf

All checks

composer check

License and origin

Released under the MIT License.

This package is a fork of esportscz/swagger (versions up to 1.3.0), originally developed by Michal Pospiech at eSports.cz, s.r.o. and released under the MIT License. The original copyright notice is retained in LICENSE as the license requires. Development continues here from version 2.0.0.