PHP code example of cschindl / php-openapi-mock-middleware

1. Go to this page and download the library: Download cschindl/php-openapi-mock-middleware library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

cschindl / php-openapi-mock-middleware example snippets


use Cschindl\OpenApiMockMiddleware\OpenApiMockMiddlewareConfig;
use Cschindl\OpenApiMockMiddleware\OpenApiMockMiddlewareFactory;
use Psr\Cache\CacheItemPoolInterface;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;

/** @var ContainerInterface $container */
$container = hToOpenApiFile = _DIR__ . '/data/openapi.yaml';
$config = new OpenApiMockMiddlewareConfig();

$openApiMockMiddleware = OpenApiMockMiddlewareFactory::createFromYamlFile(
    $pathToOpenApiFile,
    $config,
    $responseFactory,
    $streamFactory,
    $cache
);

use Cschindl\OpenApiMockMiddleware\OpenApiMockMiddleware;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

$app = new MiddlewareRunner();
$app->add($openApiMockMiddleware);

// To enable the middleware, add this header to your requests
// If this header is not present in the request, the middleware will skip to the next handler
$prepareOpenApiMiddleware = function (
    ServerRequestInterface $request,
    RequestHandlerInterface $handler
) {
    return $handler->handle(
        $request->withAddedHeader(
            OpenApiMockMiddleware::HEADER_OPENAPI_MOCK_ACTIVE,
            'true'
        )
    );
);
// Make sure that this middleware is called before $openApiMockMiddleware
$app->add($prepareOpenApiMiddleware);

$app->run($request, $response);

$settings = [
    'validateRequest' => true,
    'validateResponse' => true,
    'faker' => [
        'minItems' => 1,
        'maxItems' => 10,
        'alwaysFakeOptionals' => false,
        'strategy' => Options::STRATEGY_STATIC,
    ],
];

// @see https://github.com/canvural/php-openapi-faker#options
$fakerOptions = (new Options())
    ->setMinItems($settings['faker']['minItems'])
    ->setMaxItems($settings['faker']['maxItems'])
    ->setAlwaysFakeOptionals($settings['faker']['alwaysFakeOptionals'])
    ->setStrategy($settings['faker']['strategy']);

$config = new OpenApiMockMiddlewareConfig(
    $settings['validateRequest'],
    $settings['validateResponse'],
    $fakerOptions
);