SkillAgentSearch skills...

PHPSwaggerGen

PHP library to generate Swagger/OpenAPI REST API documentation files from comments in PHP source code.

Install / Use

/learn @vanderlee/PHPSwaggerGen

README

SwaggerGen

Version 2.3.22

License Build Status Quality

Copyright © 2014-2024 Martijn van der Lee Toyls.com.

MIT Open Source license applies.

Introduction

SwaggerGen is a PHP library for generating Swagger REST API documentation from PHP source code.

It reads comments starting with @rest\, containing commands describing the API as you go. Working with SwaggerGen is intended to be a natural extension to normal PHP-documentor style documentation. You can describe a REST API call similar to how you would describe method.

Using just a few simple commands like @rest\endpoint /users and @rest\method GET Get a list of all users gets you a definition of an API. By adding a @rest\response 200 array(object(name:string, age:int[0,>, gender:enum(male,female))) statement, you've just defined exactly what it'll return. You could have also just defined a User and do the same with a @rest\response 200 array(User) statement or even just @rest\response ok [User].

SwaggerGen makes it quick and intuitive to write high quality documentation.

Use Swagger-UI to read and test your API, as in this example generated real-time with SwaggerGen: Example (only available when running on a PHP server).

SwaggerGen is compatible with the latest Swagger 2.0 specification, which forms the basis of the Open API Initiative.

Installation

Requires PHP 5.4 or greater. PHP 5.3 is supported as long as no more recent features are absolutely necessary. There is no guarantee SwaggerGen will continue to work on PHP 5.3 in the future.

To install using Composer:

composer require vanderlee/swaggergen

Make sure you use version 2.x.x or up.

SwaggerGen aims to be PSR-4 compatible, so you should be able to use it in any package manager.

Using SwaggerGen

The easiest part of generating Swagger documentation with SwaggerGen is setting it up.

  1. Set up your (PSR-0, PSR-4 or custom) autoloader to use the SwaggerGen directory.

    You can take a look at the autoloader in the example folder if you don't already have an autoloader.

  2. Create an instance of the /SwaggerGen/SwaggerGen class.

    You can (and are advised to) specify the domainname of your server and the path to the API in the constructor.

  3. Call the array SwaggerGen->getSwagger(string[] $filenames) method to generate the documentation.

    Just provide the files which contain the operation definitions of your API. If your API uses other files, just specify an array of directories in the SwaggerGen constructor and these files will be automatically parsed when needed.

  4. You're done. Your documentation is generated. All that's left to do is output it. Store it in a file or return it real-time.

If you want to use the preprocessor, you'll probably want to call the SwaggerGen->define(string $name, string $value) method of your SwaggerGen instance after step 2 to define preprocessor variable names.

The following is a typical example:

// Assuming you don't already have an autoloader
spl_autoload_register(function ($classname) {
	include_once __DIR__ . $classname . '.php';
});

$SwaggerGen = new \SwaggerGen\SwaggerGen(
	$_SERVER['HTTP_HOST'],
	dirname($_SERVER['REQUEST_URI']),
	[__DIR__ . '/api']
);
$SwaggerGen->define('admin');				// admin = 1
$SwaggerGen->define('date', date('Y-m-d'));	// date = "2015-12-31"
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
	$SwaggerGen->define('windows');	// windows = 1 (only if on Windows OS)
}
$swagger = $SwaggerGen->getSwagger(['Example.php']);

header('Content-type: application/json');
echo json_encode($swagger);

SwaggerGen class

The only class you need to know about is the SwaggerGen class in the similarly names SwaggerGen namespace.

__construct($host = '', $basePath = '', $dirs = array())

Create a new SwaggerGen object with the given host and basePath and provide a set of dirs to use for scanning for classes that may be referenced from the sourcecode files you're about to scan.

  • $host should be the domain name, i.e. www.example.com.
  • $basePath should be the URL path to the root of the API, i.e. /api/v1.

mixed getSwagger($files, $dirs = array(), $format = self::FORMAT_ARRAY)

Generate Swagger/OpenAPI documentation by scanning the provided list of files. Optionally you can specify additional dirs to scan for class files and provide a format to specify how you want to output the documentation.

By default, the documentation is output as an array, ready for encoding as JSON, YAML or for manual post-processing. The following formats are available as constants of the SwaggerGen class.

  • FORMAT_ARRAY output the raw array.
  • FORMAT_JSON JSON-encoded output (mimetype application/json).
  • FORMAT_JSON_PRETTY JSON-encoded output with a human-friendly layout (mimetype application/json).
  • FORMAT_YAML YAML (UTF-8 character encoding) output (mimetype application/x-yaml (most common) or text/yaml).

define($name, $value = 1)

Define a value to be used by the preprocessor commands. By default, it's value will be set to 1.

undefine($name)

Undefine a value, so it is no longer recognized by the preprocessor commands.

Creating documentation

SwaggerGen takes a number of of source files and scans the comments for commands it understands. The following is a short example of the type of comments SwaggerGen understands:

/*
 * @rest\description SwaggerGen 2 Example API
 * @rest\title Example API
 * @rest\contact http://example.com Arthur D. Author
 * @rest\license MIT
 * @rest\security api_key apikey X-Api-Authentication header Authenticate using this fancy header
 * @rest\require api_key
 */

Comments

All comments are parsed, this includes both doc-comments (/** ... */) and normal comments, both single line (// ...) and multi-line (/* ... */).

Comments that are attached to functions, methods and classes. Any doc-comment immediately preceeding a function, method or class will be attached to that function, method or class. Other comments will be attached to the function, method or class containing them. For instance, SwaggerGen comments within a function will be attached to that function.

Commands

All commands must be prefixed with @rest\ to distinguish between SwaggerGen statements and normal comment statements and statements from other tools such as PHP-Documentor.

All commands are multi-line by default; any line(s) after the command that do not start with an at-sign (@) are automatically appended to the command on the previous line.

You can reference SwaggerGen documentation for other functions, methods or classes by using the uses command. This command lets you specify an other function, method or class whose documentation to include.

Commands are processed in the order in which they appear. This includes any documentation referenced with the uses command.

Contexts

SwaggerGen uses a stack of contexts. Each context represents a certain part of the Swagger documentation that will be generated. Each context supports a few commands which hold meaning within that context.

You initially start at the Swagger context.

You can switch contexts using some of the commands available within the current context. In this manual, whenever a command switches the context, it is marked using '⇒ Context name' at the end of the command syntax description.

If a command is not recognized in the current context, the context is removed from the top of the stack and the previous context tries to handle the command. If no context is able to handle the command, SwaggerGen will report this as an error.

Preprocessor commands

SwaggerGen has a limited set of preprocessor statements to remove or change parts of the generated documentation at run-time.

The preprocessor statements are loosely based on the C/C++ preprocessors.

The work by defining values for variable names and checking whether or not a variable name is defined or checking if a variables name has a specific value.

SwaggerGen currently has no predefined variables, but you can define variables yourself by assigning them to the SwaggerGen parser before scanning starts.

Preprocessor statments may be nested and are available for PHP and text.

define name [value]

Define a variable name and optionally assign a value to it.

undef name

Remove the definition a variable name.

if name [value]

If the variable name is defined and, if provided, it's value is equal to the specified value, then process all following SwaggerGen commands upto the next preprocessor command. Otherwise, do not process those commands.

ifdef name

If the variable name is defined, then process all following SwaggerGen commands upto the next preprocessor command. Otherwise, do not process those commands.

ifndef name

If the variable name is not defined, then process all following SwaggerGen commands upto the next preprocessor command. Otherwise, do not process those commands.

else

If the previous if... or elif preprocessor command did not match, then process all following SwaggerGen commands upto the next preprocessor command. Otherwise, do not process those commands.

elif name [value]

If the previous if... or elif preprocessor command did not match and if the variable name is defined and, if provided, it's value is equal to the specified value, then process all following SwaggerGen commands upto the next preprocessor

Related Skills

View on GitHub
GitHub Stars42
CategoryProduct
Updated5mo ago
Forks16

Languages

JavaScript

Security Score

92/100

Audited on Oct 19, 2025

No findings