PHP code example of mlambley / swagception

1. Go to this page and download the library: Download mlambley/swagception 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/ */

    

mlambley / swagception example snippets


namespace My\API\PathHandlers

/**
 * @path /api/entity/{entityID}/other/
 * @path /api/entity/{entityID}/other/{otherID}
 */
class MyPathHandler implements \Swagception\PathHandler\HandlesPath
{
    public function convertPath($path)
    {
        //Replace {entityID} with a real id
        if (strpos($path, '{entityID}') !== false) {
            $path = str_replace('{entityID}', $this->getEntityID(), $path);
        }

        //Replace {otherID} with a real id
        if (strpos($path, '{otherID}') !== false) {
            $path = str_replace('{otherID}', $this->getOtherID(), $path);
        }

        return $path;
    }

    protected function getEntityID()
    {
        //$ids = 100 valid entity ids. Pulled from either the database or the api.
        return $ids[mt_rand(0, 99)];
    }

    protected function getOtherID()
    {
        //$ids = 100 valid other ids. Pulled from either the database or the api.
        return $ids[mt_rand(0, 99)];
    }
}

class MyCest
{
    use \Swagception\ContainerTrait;

    public function __construct()
    {
        //Configure the swagger schema object.
        $this->swaggerContainer = new \Swagception\Container\Container();

        $this->swaggerContainer->getSchema()
            //Path to your existing Swagger specification
            ->withSchemaURI('/path/to/swagger.json')
        ;

        //Configure the path handler loader.
        $this->swaggerContainer->getPathHandlerLoader()
            //Set this if you are using your own path handlers, and not relying upon enum and x-example.
            ->withNamespace('My\\API\\PathHandlers')

            //Set this if your path handler classes have not been loaded into the system yet.
            ->withFilePath('/path/to/pathhandlers/')
        ;
    }

    /**
     * @dataProvider _pathProvider
     */
    public function path(MyTester $I, \Codeception\Scenario $S, \Codeception\Example $data)
    {
        $path = $data[0];
        $this->swaggerContainer->getSchema()->testPath($path);
    }

    protected function _pathProvider()
    {
        //Will return an array of arrays.
        return array_map(function($val) {
            return [$val];
        }, $this->swaggerContainer->getSchema()->getPaths());
    }
}

public function paths(MyTester $I, \Codeception\Scenario $S)
{
    $schema = $this->swaggerContainer->getSchema(); 
    foreach ($schema->getPaths() as $path) {
        $schema->testPath($path);
    }
}

(new \Swagception\Validator\Validator())
    ->validate($schema, $json);