Coder Social home page Coder Social logo

yiisoft / yii-swagger Goto Github PK

View Code? Open in Web Editor NEW
28.0 18.0 6.0 157 KB

Swagger integration for Yii

Home Page: https://www.yiiframework.com/

License: BSD 3-Clause "New" or "Revised" License

PHP 100.00%
api openapi swagger swagger-ui yii3 hacktoberfest

yii-swagger's Introduction

Yii Swagger


Latest Stable Version Total Downloads Build status Scrutinizer Code Quality Code Coverage Mutation testing badge static analysis type-coverage

OpenAPI Swagger for Yii Framework.

Requirements

  • PHP 8.0 or higher.

Installation

The package could be installed with composer:

composer require yiisoft/yii-swagger

Configuration

1. Add route configuration to config/routes.php

use Yiisoft\DataResponse\Middleware\FormatDataResponseAsHtml;
use Yiisoft\DataResponse\Middleware\FormatDataResponseAsJson;
use Yiisoft\Router\Group;
use Yiisoft\Router\Route;
use Yiisoft\Swagger\Middleware\SwaggerUi;
use Yiisoft\Swagger\Action\SwaggerJson;

// Swagger routes
Group::create('/swagger', [
    Route::get('')
        ->middleware(FormatDataResponseAsHtml::class)
        ->action(fn (SwaggerUi $swaggerUi) => $swaggerUi->withJsonUrl('/swagger/json-url')),
    Route::get('/json-url')
        ->middleware(FormatDataResponseAsJson::class)
        ->action(SwaggerJson::class),
]),

2. Add annotations to default API controller

use OpenApi\Annotations as OA;

/**
 * @OA\Info(title="My first API", version="1.0")
 */
class DefaultController {
    // ...
}

and before actions

/**
 * @OA\Get(
 *     path="/api/endpoint",
 *     @OA\Response(response="200", description="Get default action")
 * )
 */
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
    // ...
}

See Swagger-PHP documentation for details on how to annotate your code.

3. Configure SwaggerJson action

For annotations to be registered you need to configure SwaggerJson.

You can use the parameters in config/params.php to configure SwaggerJson:

//...
'yiisoft/yii-swagger' => [
    'annotation-paths' => [
        '@src/Controller' // Directory where annotations are used
    ],
    'cacheTTL' => 60 // Enables caching and sets TTL, "null" value means infinite cache TTL.
],
//...

4. (Optional) Add config for aliases and asset manager

use Yiisoft\Definitions\Reference;
use Yiisoft\Assets\AssetManager;

return [
    //...
    'yiisoft/aliases' => [
        'aliases' => [
            //...
            '@views' => '@root/views',
            '@assets' => '@public/assets',
            '@assetsUrl' => '@baseUrl/assets',
        ],
    ],
    'yiisoft/view' => [
        'basePath' => '@views',
        'defaultParameters' => [
            'assetManager' => Reference::to(AssetManager::class),
        ]
    ],
    //...
];

5. (Optional) Configure SwaggerUi action

You can use the parameters in config/params.php to configure SwaggerUi.

For example, you can enable persisting authorization by setting the persistAuthorization parameter to true.

//...
'yiisoft/yii-swagger' => [
    'ui-params' => [
        'persistAuthorization' => true,
    ],
],
//...

You can find a complete list of parameters by following the link.

6. (Optional) Configure SwaggerService

You can specify options for generation an OpenApi\Annotations\OpenApi instance in config/params.php to configure SwaggerService:

//...
'yiisoft/yii-swagger' => [
    // Default values are specified.
    'open-api-options' => [
        'aliases' => OpenApi\Generator::DEFAULT_ALIASES,
        'namespaces' => OpenApi\Generator::DEFAULT_NAMESPACES,
        'analyser' => null,
        'analysis' => null,
        'processors' => null,
        'logger' => null,
        'validate' => true,
        'version' => OpenApi\Annotations\OpenApi::DEFAULT_VERSION,
    ],
],
//...

For more information about generation an OpenApi\Annotations\OpenApi instance, see the documentation of the zircote/swagger-php package.

Testing

Unit testing

The package is tested with PHPUnit. To run tests:

./vendor/bin/phpunit

Mutation testing

The package tests are checked with Infection mutation framework with Infection Static Analysis Plugin. To run it:

./vendor/bin/roave-infection-static-analysis-plugin

Static analysis

The code is statically analyzed with Psalm. To run static analysis:

./vendor/bin/psalm

License

The Yii Swagger is free software. It is released under the terms of the BSD License. Please see LICENSE for more information.

Maintained by Yii Software.

Support the project

Open Collective

Follow updates

Official website Twitter Telegram Facebook Slack

yii-swagger's People

Contributors

dependabot[bot] avatar devanych avatar fantom409 avatar iamsaint avatar rustamwin avatar samdark avatar sankaest avatar terabytesoftw avatar thenotsoft avatar viktorprogger avatar vjik avatar xepozz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii-swagger's Issues

Swagger middleware does not respect any global middlewares

Steps to reproduce:

  • Create any route with swagger declaration
  • Add Locale middleware from yii-middleware package
  • Open swagger

What I expect to see:
All routes should contain the path part from Locale middleware: {_language} with an ability to change it on request

What I see:
All routes are exactly as they were declared

Looks like the problem is larger than it is. Having swagger declaration in third-party library developer may have wrong addresses that make our swagger package unusable. Just think of that you're changing /debug route from yii-debug package to /infra/debug and you still have /debug into your swagger panel, do not have /infra/debug and any /debug calls bring errors.

@yiisoft/yii3 do you have any thought about it?

Have a trouble in step 4

What steps will reproduce the problem?

4

What is the expected result?

I don't know if step 4 in wich file paste this code. I supose that the file is /project/config/web.php, but when i put the code fail, the error say "Uncaught Error: Class "Yiisoft\Definitions\Reference"."
Please help me.

Another question is, if i have in config/web.php

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                    '<controller:\w+>/<id:\d+>'=>'<controller>/view',
               '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
               '<controller:\w+>/<action:\w+>'=>'<controller>/<action>'
            ],

where is the route to see swagger ui.
Thanks a lot for the support.

What do you get instead?

Additional info

Q A
Version 1.0.?
PHP version
Operating system

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.