PHP code example of k-kinzal / oas-fake-php

1. Go to this page and download the library: Download k-kinzal/oas-fake-php 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/ */

    

k-kinzal / oas-fake-php example snippets


use OasFake\OasFake;
use OasFake\Server;

final class PetStoreServer extends Server
{
    protected static string $SCHEMA = __DIR__ . '/openapi.yaml';
}

// Start intercepting HTTP requests
$server = OasFake::start(PetStoreServer::class);

// All HTTP requests now return responses generated from the schema
$client = new GuzzleHttp\Client(['base_uri' => 'https://petstore.example.com']);
$response = $client->get('/pets/1');

// Stop intercepting
OasFake::stop();

use OasFake\OasFake;
use OasFake\Handler;

$server = OasFake::start(PetStoreServer::class, fn ($s) => $s
    ->withResponse('listPets', 200, [['id' => 1, 'name' => 'Buddy']])
    ->withCallback('createPet', function ($request, $response) {
        $body = json_decode((string) $request->getBody(), true);
        return new \GuzzleHttp\Psr7\Response(201, [], json_encode([
            'id' => 42,
            'name' => $body['name'],
        ]));
    })
    ->withHandler('deletePet', Handler::status(204))
);

use OasFake\Server;
use GuzzleHttp\Psr7\Response;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final class PetStoreServer extends Server
{
    protected static string $SCHEMA = __DIR__ . '/openapi.yaml';

    public function listPets(ServerRequestInterface $request, ?ResponseInterface $response): ResponseInterface
    {
        return new Response(200, ['Content-Type' => 'application/json'], json_encode([
            ['id' => 1, 'name' => 'Buddy'],
        ]));
    }

    #[\OasFake\Route(method: 'DELETE', path: '/pets/{petId}')]
    public function removePet(ServerRequestInterface $request, ?ResponseInterface $response): ResponseInterface
    {
        return new Response(204);
    }
}

use OasFake\OasFake;
use OasFake\Mode;

$server = OasFake::start(PetStoreServer::class, fn ($s) => $s
    ->withMode(Mode::RECORD)  // or ->withMode('record')
    ->withCassettePath('./fixtures/cassettes')
    ->withRequestValidation(false)
    ->withResponseValidation(false)
    ->withFakerOptions(['alwaysFakeOptionals' => true, 'minItems' => 2, 'maxItems' => 5])
    ->withMiddleware(new MyMiddleware())
);