项目作者: wapmorgan

项目描述 :
PHP Library that generates OpenApi configuration (~ Swagger configuration) directly from actual PHP code (PhpDoc and php type hints)
高级语言: PHP
项目地址: git://github.com/wapmorgan/OpenApiGenerator.git
创建时间: 2020-01-23T17:33:52Z
项目社区:https://github.com/wapmorgan/OpenApiGenerator

开源协议:MIT License

下载


What is it?

It is OpenApi configuration generator that works with origin source code + phpdoc.

Latest Stable Version
Latest Unstable Version
License

Main purpose of this library is to automatize generation of OpenApi-specification for existing JSON-API with a lot of methods. Idea by @maxonrock.

  1. Open Api generator
  2. Extending

OpenApiGenerator

What it does?

It generates OpenApi 3.0 specification files for your REST JSON-based API
written in PHP from source code directly. You do not need to write OpenApi-specification manually.

Laravel Example

  1. Routes:

    1. Route::get('/selector/lists', [\App\Http\Controllers\SelectorController::class, 'lists']);
    2. Route::post('/selector/select', [\App\Http\Controllers\SelectorController::class, 'select']);
    3. Route::get('/selector/goTo', [\App\Http\Controllers\SelectorController::class, 'goTo']);
    4. Route::get('/geo/detect', [\App\Http\Controllers\GeoController::class, 'detect']);
    5. Route::get('/geo/select', [\App\Http\Controllers\GeoController::class, 'select']);
  2. One controller:

    1. /**
    2. * Returns lists of filters
    3. * @param Request $request
    4. * @return ListsResponse
    5. */
    6. public function lists(Request $request) {
    7. return new ListsResponse([
    8. // 'persons' => range(1, 15),
    9. 'persons' => array_keys(Menu::$personsList),
    10. 'tastes' => Menu::$tastes,
    11. 'meat' => Menu::$meat,
    12. 'pizzas' => Menu::$pizzas,
    13. ]);
    14. }
    15. /**
    16. * Makes a selection of pizzas according to criteria
    17. * @param \App\Http\Requests\SelectPizzas $request
    18. * @return PizzaListItem[]
    19. */
    20. public function select(\App\Http\Requests\SelectPizzas $request) {
    21. $validated = $request->validated();
    22. return (new Selector())->select(
    23. $validated['city'], $validated['persons'],
    24. $validated['tastes'] ?? null, $validated['meat'] ?? null,
    25. $validated['vegetarian'] ?? false, $validated['maxPrice'] ?? null);
    26. }
  3. One request and two responses:

    1. class SelectPizzas extends FormRequest {
    2. public function rules()
    3. {
    4. // ...
    5. return array_merge([
    6. 'city' => ['required', 'string'],
    7. 'persons' => ['required', Rule::in(array_keys(Menu::$personsList))],
    8. 'vegetarian' => ['boolean'],
    9. 'maxPrice' => ['numeric'],
    10. 'pizzas' => ['array', Rule::in(array_keys(Menu::$pizzas))],
    11. ], $tastes, $meat);
    12. }
    13. }
    14. class ListsResponse extends BaseResponse {
    15. /** @var string[] */
    16. public $persons;
    17. /** @var string[] */
    18. public $tastes;
    19. /** @var string[] */
    20. public $meat;
    21. /** @var string[] */
    22. public $pizzas;
    23. }
    24. class PizzaListItem extends BaseResponse {
    25. public string $pizzeria;
    26. public string $id;
    27. public int $sizeId;
    28. public string $name;
    29. public float $size;
    30. public array $tastes;
    31. public array $meat;
    32. public float $price;
    33. public float $pizzaArea;
    34. public float $pizzaCmPrice;
    35. public string $thumbnail;
    36. public array $ingredients;
    37. public int $dough;
    38. }
  4. Result of generation from code: two endpoints with description and arguments for select.

    1. ┌─────────┬─────────────────┬──────────────────────────┐
    2. get /selector/lists Returns lists of filters
    3. ├─────────┼─────────────────┼──────────────────────────┤
    4. Result (4)
    5. persons array of string
    6. tastes array of string
    7. meat array of string
    8. pizzas array of string
    9. └─────────┴─────────────────┴──────────────────────────┘
    10. ┌──────────────────┬──────────────────┬───────────────────────────────────────────────────┐
    11. post /selector/select Makes a selection of pizzas according to criteria
    12. ├──────────────────┼──────────────────┼───────────────────────────────────────────────────┤
    13. Parameters (15)
    14. string city
    15. string persons
    16. boolean vegetarian
    17. number maxPrice
    18. array pizzas
    19. boolean tastes.cheese
    20. boolean tastes.sausage
    21. boolean tastes.spicy
    22. boolean tastes.mushroom
    23. boolean tastes.exotic
    24. boolean meat.chicken
    25. boolean meat.pork
    26. boolean meat.beef
    27. boolean meat.fish
    28. boolean meat.sauce_meat
    29. ├──────────────────┼──────────────────┼───────────────────────────────────────────────────┤
    30. Result (14)
    31. array of
    32. [*].pizzeria string
    33. [*].id string
    34. [*].sizeId integer
    35. [*].name string
    36. [*].size integer
    37. [*].tastes array of
    38. [*].meat array of
    39. [*].price integer
    40. [*].pizzaArea integer
    41. [*].pizzaCmPrice integer
    42. [*].thumbnail string
    43. [*].ingredients array of
    44. [*].dough integer
    45. └──────────────────┴──────────────────┴───────────────────────────────────────────────────┘

How it works

  1. Scraper collects info about API (tags, security schemes and servers, all endpoints) and contains settings for Generator. Scraper is framework-dependent.
  2. Generator fulfills openapi-specification with endpoints information by analyzing source code:
    • summary and description of actions
    • parameters and result of actions
      Generator is common. It just receives information from Scraper and analyzes code by Scraper rules.

More detailed process description is in How it works document.

How to use

Invoke console script to generate openapi for your project (with help of integrations):

For example, for yii2-project:

  1. Run parser on project to analyze files and retrieve info about endpoints
    1. ./vendor/bin/openapi-generator scrape --scraper yii2 ./
    2. # And more deeper scan
    3. ./vendor/bin/openapi-generator generate --scraper yii2 --inspect ./
  2. Generate specification(s) into yaml-files in api_docs folder by specification_name.yml
    1. ./vendor/bin/openapi-generator generate --scraper yii2 ./ ./api_docs/
    2. # Or with your own scraper (child of one of basic scrapers)
    3. ./vendor/bin/openapi-generator generate --scraper components/api/OpenApiScraper.php ./ ./api_docs/
  3. Deploy swagger with specification (e.g. api_docs/main.yml on port 8091)
    1. docker run -p 8091:8080 --rm -e URL=./apis/main.yaml -v $(pwd):/usr/share/nginx/html/apis/ swaggerapi/swagger-ui:v4.15.2

More detailed description is in How to use document.

Integrations

There’s few integrations: Yii2, Laravel, Slim. Details is in Integrations document.
You can write your own integration for framework or your project.

Extending

New scraper

You use (or extend) a predefined scraper (see Integrations) or create your own scraper from scratch (extend DefaultScraper), which should return a result with list of your API endpoints. Also, your scraper should provide tags, security schemes and so on.

Scraper should return list of specifications (for example, list of api versions) with:

  • meta - version/description/externalDocs - of specification.
  • servers - list of servers (base urls).
  • tags - list of tags with description and other properties (categories for endpoints).
  • securitySchemes - list of security schemes (authorization types).
  • endpoints - list of API endpoints (separate callbacks).

Detailed information about Scraper result: in another document.

Settings

DefaultGenerator provides list of settings to tune generator.

Parameter type default description
CHANGE_GET_TO_POST_FOR_COMPLEX_PARAMETERS bool false if callback has arguments with object , array , stdclass , mixed type or class-typed, method of argument will be changed to POST and these arguments will be placed as body data in json-format
TREAT_COMPLEX_ARGUMENTS_AS_BODY bool false move complex arguments to request body
PARSE_PARAMETERS_FROM_ENDPOINT bool false if callback id has macroses (users/{id}), these arguments will be parsed as normal callback arguments
PARSE_PARAMETERS_FORMAT_FORMAT_DESCRIPTION bool false if php-doc for callback argument in first word after argument variable has one of predefined sub-types (@param string $arg SUBTYPE Full parameter description), this will change sub-type in resulting specification. For example, for string format there are subtypes: date, date-time, password, byte, binary, for integer there are: float, double, int32, int64. Also, you can defined custom format with DefaultGenerator::setCustomFormat($format, $formatConfig)

Usage:

  1. $generator->changeSetting(DefaultGenerator::CHANGE_GET_TO_POST_FOR_COMPLEX_PARAMETERS, true);

By default, they all are disabled.

Limitations

  • Only query parameters supported (url?param1=...¶m2=...) or body json parameters ({data: 123).
  • Only one response type supported - HTTP 200 response.
  • No support for parameters’ / fields’ / properties’ format, example and other validators.

ToDo

  • Support for few operations on one endpoint (GET/POST/PUT/DELETE/…).
  • Support for body parameters (when parameters are complex objects) - partially.
  • Support for few responses (with different HTTP codes).
  • Extracting class types into separate components (into openapi components).
  • Support for other request/response types besides JSON
  • Add @paramFormat for specifying parameter format - partially.
  • Support for dynamic action arguments in dynamic model
  • Switch 3.0/3.1 (https://www.openapis.org/blog/2021/02/16/migrating-from-openapi-3-0-to-3-1-0)