Git Product home page Git Product logo

openapi-data-mocker-server-middleware's Introduction

Openapi Data Mocker Server Middleware

Build Status

PSR-15 HTTP Server Middleware to create mock responses from OpenAPI Schemas(OAS 3.0). This package was an enhancement of PHP Slim4 server in OpenAPI Generator project, but it easier to maintain it in separated repo.

Requirements

  • PHP ^7.3

Important notice! While PHP 8.0 declared in composer.json this package hasn't been tested against it.

Installation via Composer

Run in terminal:

composer require ybelenko/openapi-data-mocker-server-middleware

Constructor Arguments

  1. $mocker: OpenApiDataMockerInterface
    • is mocker class instance. To create custom data mocker extend OpenAPIServer\Mock\OpenApiDataMockerInterface.
  2. $responses: array
  3. $responseFactory: ResponseFactoryInterface
  4. $getMockStatusCodeCallback: callable|null = null
    • is callback before mock data generation. Below example shows how to enable mock feature for only requests with X-OpenAPIServer-Mock: ping HTTP header. Adjust requests filtering to fit your project requirements. This function must return single response schema from $responses array parameter. Mock feature is disabled when callback returns anything beside existent key from $responses array, eg 'default' or 200.
  5. $afterCallback: callable|null = null
    • is callback executed after mock data generation. Most obvious use case is append specific HTTP headers to distinguish real and fake responses. This function must always return response instance.

Usage Example

require_once __DIR__ . '/vendor/autoload.php';

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;
use OpenAPIServer\Mock\OpenApiDataMockerRouteMiddleware;
use OpenAPIServer\Mock\OpenApiDataMocker;

// initiate Slim app or any other PSR-15 compliant framework
$app = AppFactory::create();

// create new mocker instance
$mocker = new OpenApiDataMocker();

// responses OAS3.0 definition of GET /mock operation
// check examples/get_mock_responses.php file
$responsesForGetMockRoute = require_once(__DIR__ . '/get_mock_responses.php');

// initiate any PSR-17 compliant response factory
$responseFactory = AppFactory::determineResponseFactory();

// optional response schema selector
$getMockStatusCodeCallback = function (ServerRequestInterface $request, $responses) {
    // check if client clearly asks for mocked response
    if (
        $request->hasHeader('X-OpenAPIServer-Mock')
        && $request->getHeader('X-OpenAPIServer-Mock')[0] === 'ping'
    ) {
        $responses = (array) $responses;
        if (array_key_exists('default', $responses)) {
            return 'default';
        }

        // return first response key
        reset($responses);
        return key($responses);
    }
    return false;
};

// optional after middleware callback
$afterCallback = function (ServerRequestInterface $request, ResponseInterface $response) {
    // mark mocked response to distinguish real and fake responses
    return $response->withHeader('X-OpenAPIServer-Mock', 'pong');
};

// create middleware itself
$mw = new OpenApiDataMockerRouteMiddleware(
    $mocker,
    $responsesForGetMockRoute,
    $responseFactory,
    $getMockStatusCodeCallback,
    $afterCallback
);

// this package is route middleware, apply it to route as described in Slim docs:
// https://www.slimframework.com/docs/v4/concepts/middleware.html#route-middleware
$app->get('/mock', function (ServerRequestInterface $request, ResponseInterface $response) {
    $response->getBody()->write('Hello ');

    return $response;
})->add($mw);

$app->run();

// let's assume you started builtin PHP server
// which you MUST NOT use on production:
// $ php -S localhost:8888 examples/slim_example.php

// finally you can check output with curl library
// $ curl http://localhost:8888/mock
// Hello

// $ curl http://localhost:8888/mock -H 'X-OpenAPIServer-Mock: ping'

openapi-data-mocker-server-middleware's People

Stargazers

 avatar

Watchers

 avatar

Forkers

anttikuuskoski

openapi-data-mocker-server-middleware's Issues

PHP warning from OpenApiDataMockerRouteMiddleware.phpL90 due to callback returning false

The code in

if (array_key_exists($mockedStatusCode, $this->responses)) {
results in a PHP warning:

Warning: array_key_exists(): The first argument should be either a string or an integer in ybelenko\openapi-data-mocker-server-middleware\src\Mock\OpenApiDataMockerRouteMiddleware.php on line 90

The empty callback return value comes (for example) from an enabled (uncommented) but unused mock setup in https://github.com/OpenAPITools/openapi-generator/blob/349445ab0102eefb0c086a74f7be4381b1ba9c0f/modules/openapi-generator/src/main/resources/php-slim4-server/config_example.mustache#L75

So the issue might belong to the other repo as well, but as I think the callback handler should be prepared for unexpected return values, I'm placing the issue here. Please do close / move if inappropriate.

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.