Giter Club home page Giter Club logo

swagger-resolver-bundle's Introduction

Swagger Resolver Bundle На Русском

PHPUnit Coverage Status Latest Stable Version Total Downloads

Feel free to connect with me by email or in Telegram.

Usage example on GitHub Gist

Introduction

Bundle provides possibility for validate data according to the Swagger 2 documentation. You describe your API documentation by Swagger and provides verification of data for compliance with the described requirements. When documentation has been updated then verification will be updated too, all in one place!

Documentation is cached through the standard Symfony Warmers mechanism. In debug mode, the cache automatically warms up if you change the file containing the description of the documentation.

Note: as result bundle returns SwaggerResolver object - extension for the OptionsResolver. In this way you get full control over created resolver.

Attention: remember, when you change generated SwaggerResolver object you risk getting divergence with actual documentation.

Integrations

Bundle provides integration with NelmioApiDocBundle, supports configuration loading by swagger-php and also supports loading directly from the json or yaml(yml) configuration file. When used default bundle configuration then swagger documentation will be load in most optimal available way. Loaders priority:

  1. NelmioApiDocBundle - do not require any additional configuration.
  2. swagger-php - scan src/ directory by default. Uses swagger_php.scan and swagger_php.exclude parameters.
  3. json - looking for web/swagger.json by default. Uses configuration_file parameter.

Installation

Step 1: Download the Bundle

Open a command console, enter your project directory and execute the following command to download the latest stable version of this bundle:

    composer require adrenalinkin/swagger-resolver-bundle

is command requires you to have Composer install globally.

Step 2: Enable the Bundle

Then, enable the bundle by updating your app/AppKernel.php file to enable the bundle:

<?php declare(strict_types=1);
// app/AppKernel.php

class AppKernel extends Kernel
{
    // ...

    public function registerBundles()
    {
        $bundles = [
            // ...

            new Linkin\Bundle\SwaggerResolverBundle\LinkinSwaggerResolverBundle(),
        ];

        return $bundles;
    }

    // ...
}

Configuration

To start using bundle you don't need to define some additional configuration. All parameters have values by default:

# app/config.yml
linkin_swagger_resolver:
    # default parameter locations which can apply normalization
    enable_normalization:
        - 'query'
        - 'path'
        - 'header'
    # strategy for merge all request parameters.
    path_merge_strategy:            Linkin\Bundle\SwaggerResolverBundle\Merger\Strategy\StrictMergeStrategy
    configuration_loader_service:   ~   # the name of the configuration loader service
    configuration_file:             ~   # full path to the configuration file
    swagger_php:                        # settings for the swagger-php
        scan:       ~                   # array of the full paths for the annotations scan
        exclude:    ~                   # array of the full paths which should be excluded

Usage

Step 1: Swagger documentation preparation

Swagger documentation preparation differ according to used tools of your project.

NelmioApiDocBundle

If your project has NelmioApiDocBundle connected, then no additional configuration is required.

swagger-php

In the absence of NelmioApiDocBundle, the bundle will degrade to the configuration loading by swagger-php annotations. In this case, by default, will be used src/ directory to scan. To optimize scanning process you can describe directories in the configuration:

# app/config.yml
linkin_swagger_resolver:
    swagger_php:
        scan:
            - '%kernel.project_dir%/src/Acme/ApiBundle'
        exclude:
            - '%kernel.project_dir%/src/Acme/ApiBundle/Resources'
            - '%kernel.project_dir%/src/Acme/ApiBundle/Repository'

JSON

In the absence of NelmioApiDocBundle and swagger-php, the bundle will degrade to the configuration loading by json file. In this case, by default, will be used web/swagger.json file. Also, you can set custom path to the json configuration:

# app/config.yml
linkin_swagger_resolver:
    configuration_file: '%kernel.project_dir%/web/swagger.json' # json extension is required

YAML or (yml)

In the absence of NelmioApiDocBundle and swagger-php, but available configuration file in the yaml or yml format you need to define path to that file:

# app/config.yml
linkin_swagger_resolver:
    configuration_file: '%kernel.project_dir%/web/swagger.yaml' # yaml or yml extension is required

Custom

If you need to use custom configuration loader you should implement custom loading process in the class, which implements SwaggerConfigurationLoaderInterface interface. After that you need to define name of that service in the configuration:

# app/config.yml
linkin_swagger_resolver:
    configuration_loader_service: acme_app.custom_configuration_loader

Step 2: Data validation

Validation for model

<?php declare(strict_types=1);

/** @var \Linkin\Bundle\SwaggerResolverBundle\Factory\SwaggerResolverFactory $factory */
$factory = $container->get('linkin_swagger_resolver.factory');
// loading by fully qualified class name
$swaggerResolver = $factory->createForDefinition(AcmeApiModel::class);
// loading by class name
$swaggerResolver = $factory->createForDefinition('AcmeApiModel');

/** @var \Symfony\Component\HttpFoundation\Request $request */
$data = $swaggerResolver->resolve(json_decode($request->getContent(), true));

Validation for request

<?php declare(strict_types=1);

/** @var \Linkin\Bundle\SwaggerResolverBundle\Factory\SwaggerResolverFactory $factory */
$factory = $container->get('linkin_swagger_resolver.factory');
$request = $container->get('request_stack')->getCurrentRequest();
// Loading by request
$swaggerResolver = $factory->createForRequest($request);

$data = $swaggerResolver->resolve(json_decode($request->getContent(), true));

Advanced

Custom validator

Bundle validates the data through the validator system. List of all validators, you can find out by going to the Validator folder. All validators registered as tagging services. To create your own validator it is enough to create class, which implements SwaggerValidatorInterface and then register it under the tag linkin_swagger_resolver.validator.

Custom normalizer

Bundle validates the data through the normalizer system. List of all normalizers, you can find out by going to the Normalizer folder. All normalizers registered as tagging services. To create your own normalizer it is enough to create class, which implements SwaggerNormalizerInterface and then register it under the tag linkin_swagger_resolver.normalizer.

Running the tests and static analysis tools

Download the project:

git clone [email protected]:adrenalinkin/swagger-resolver-bundle.git
cd swagger-resolver-bundle

Follow this instruction for set up simple docker container.

Install composer dependencies:

composer update

For run the test suite:

bin/simple-phpunit

For run the PHP-CS-Fixer:

php-cs-fixer fix --diff

For run the composer-normalize:

composer-normalize --dry-run

License

license

swagger-resolver-bundle's People

Contributors

adrenalinkin avatar mario-fehr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

swagger-resolver-bundle's Issues

PHP 8.1

Hello,

Since PHP 7.4 is already EOL, I wanted to update my application to PHP 8.1. Unfortunately, it does not work because the compsoer "php" defaults to "^7.1".

Problem 1
- Root composer.json requires adrenalinkin/swagger-resolver-bundle ^0.4.6 -> satisfiable by adrenalinkin/swagger-resolver-bundle[v0.4.6].
- adrenalinkin/swagger-resolver-bundle v0.4.6 requires php ~7.1 -> your php version (8.1.13) does not satisfy that requirement.

Is an update planned here, or do I have to look for something new?

Swagger operation for path "api/v2/market/{name}" with "get" was not found

Hi, I faced an issue during the composer installation of your bundle.

It throws an exception with message:

Swagger operation for path "api/v1/market/{name}" with "get" was not found

By stepping through your code I noticed that the problem occurs when the mapping is generated.
private function initMapPathToRouteName(): void { foreach ($this->router->getRouteCollection() as $routeName => $route) { foreach ($route->getMethods() as $method) { $this->mapPathToRouteName[$route->getPath()][$method] = $routeName; } } }

$method will be passed as uppercase variant, e.g. "GET" - but the comparision if the mapping has been set will only check the lowercase variant, e.g. "get".

I could solve the problem by adding the method always in the lowercase variant to the mapping.

See:
private function initMapPathToRouteName(): void { foreach ($this->router->getRouteCollection() as $routeName => $route) { foreach ($route->getMethods() as $method) { $this->mapPathToRouteName[$route->getPath()][strtolower($method)] = $routeName; } } }

I'm using FOS Rest and Nelmio, I've defined my routes with:

@rest\Get("api/v1/market/{name}/")

I don't know if its matters.

Best regards;
Florian

Allow to get all errors across validation

Currently we can receive only first incorrect value with validation - this is "Fail fast" style.
Would be better if we will can receive all incorrect value which was not pass validation.

Normalizers should not throw an errors

Normalizers should not throw an errors - we already have Validators for this purpose. Better return value as is in that case when normalizer can't perform normalization.
Also we should not analyse is this property required or not.
According to this information contract will be pretty simple

public function supports(Schema $propertySchema, string $propertyName): bool;
public function getNormalizer(): Closure;

Add symfony 5 support

ATM the composer.json is constraint to 3.4 or 4. Probably we can just update. Have you considered it?

Add API documentation caching

At the present time implementation of the API (like swagger-php and NelmioApiDoc) generates data at every requests.
Also, for provide validation according to API documentation we don't need whole documentation.
Best solution - provide cache in prepared format.

Cover all SwaggerConfigurationLoader's with unit Tests

  • AbstractAnnotationConfigurationLoader
  • AbstractFileConfigurationLoader
  • AbstractSwaggerConfigurationLoader
  • JsonConfigurationLoader
  • NelmioApiDocConfigurationLoader
  • SwaggerPhpConfigurationLoader
  • YamlConfigurationLoader

Add array normalizer

Currently after resolving we was not normalize specific string array representation (csv, tsv, etc.) into PHP array.
Would be better to have PHP array exactly after resolving

Add integration with option resolver normalizer

According to symfony option resolver component we can use Normalizers.
This feature useful when we work with not strict data types but want to be sure about final type.

When data received from body as JSON all types can be right out of the box.
But when we work with query or path parameters we will receive string always.

So we need to have possibility process this situations by data normalization.

New Minor Version possible?

Hi,

is it possible that you publish a new minor version?
I use the symfony 5 framework and want to use this package but the last version did not contain your last changes :)

Thx a lot!

Change SwaggerValidatorInterface::validate by adding return bool

Currently we have SwaggerValidatorInterface::validate which throws exception when validation was not pass and void return when validation has been passed.
Wold be better to change this interface according to add bool return type.

This will BREAK COMPATIBILITY

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.