All Downloads are FREE. Search and download functionalities are using the official Maven repository.

php-slim4-server.SlimRouter.mustache Maven / Gradle / Ivy

There is a newer version: 7.9.0
Show newest version
licenseInfo}}

/**
 * NOTE: This class is auto generated by the openapi generator program.
 * https://github.com/openapitools/openapi-generator
 * Do not edit the class manually.
 */{{#apiInfo}}
namespace {{invokerPackage}};

use Slim\Factory\AppFactory;
use Slim\Interfaces\RouteInterface;
use Slim\Exception\HttpNotImplementedException;
use Psr\Container\ContainerInterface;
use InvalidArgumentException;
use Dyorg\TokenAuthentication;
use Dyorg\TokenAuthentication\TokenSearch;
use Psr\Http\Message\ServerRequestInterface;
use OpenAPIServer\Mock\OpenApiDataMocker;
use OpenAPIServer\Mock\OpenApiDataMockerRouteMiddleware;
{{#isSlimPsr7}}
use Slim\Psr7\Factory\ResponseFactory;
{{/isSlimPsr7}}
{{#isNyholmPsr7}}
use Nyholm\Psr7\Factory\Psr17Factory
{{/isNyholmPsr7}}
{{#isGuzzlePsr7}}
use GuzzleHttp\Psr7\HttpFactory;
{{/isGuzzlePsr7}}
{{#isZendDiactoros}}
use Zend\Diactoros\ResponseFactory;
{{/isZendDiactoros}}
use Exception;

/**
 * SlimRouter Class Doc Comment
 *
 * @package {{invokerPackage}}
 * @author  OpenAPI Generator team
 * @link    https://github.com/openapitools/openapi-generator
 */
class SlimRouter
{

    /** @var App instance */
    private $slimApp;

    /** @var array[] list of all api operations */
    private $operations = [
        {{#apis}}
        {{#operations}}
        {{#operation}}
        [
            'httpMethod' => '{{httpMethod}}',
            'basePathWithoutHost' => '{{{basePathWithoutHost}}}',
            'path' => '{{{path}}}',
            'apiPackage' => '{{apiPackage}}',
            'classname' => '{{classname}}',
            'userClassname' => '{{userClassname}}',
            'operationId' => '{{operationId}}',
            'responses' => [
            {{#responses}}
                '{{#isDefault}}default{{/isDefault}}{{^isDefault}}{{code}}{{/isDefault}}' => [
                    'jsonSchema' => '{{{jsonSchema}}}',
                ],
            {{/responses}}
            ],
            'authMethods' => [
                {{#hasAuthMethods}}
                {{#authMethods}}
                // {{type}} security schema named '{{name}}'
                {{#isBasicBasic}}
                [
                    'type' => '{{type}}',
                    'isBasic' => true,
                    'isBearer' => false,
                    'isApiKey' => false,
                    'isOAuth' => false,
                ],
                {{/isBasicBasic}}
                {{#isBasicBearer}}
                [
                    'type' => '{{type}}',
                    'isBasic' => true,
                    'isBearer' => true,
                    'isApiKey' => false,
                    'isOAuth' => false,
                ],
                {{/isBasicBearer}}
                {{#isApiKey}}
                [
                    'type' => '{{type}}',
                    'isBasic' => false,
                    'isBearer' => false,
                    'isApiKey' => true,
                    'isOAuth' => false,
                    'keyParamName' => '{{keyParamName}}',
                    'isKeyInHeader' => {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}},
                    'isKeyInQuery' => {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}},
                    'isKeyInCookie' => {{#isKeyInCookie}}true{{/isKeyInCookie}}{{^isKeyInCookie}}false{{/isKeyInCookie}},
                ],
                {{/isApiKey}}
                {{#isOAuth}}
                [
                    'type' => '{{type}}',
                    'isBasic' => false,
                    'isBearer' => false,
                    'isApiKey' => false,
                    'isOAuth' => true,
                    'scopes' => [
                    {{#scopes}}
                        '{{scope}}',{{#description}} // {{.}}{{/description}}
                    {{/scopes}}
                    ],
                ],
                {{/isOAuth}}
                {{/authMethods}}
                {{/hasAuthMethods}}
            ],
        ],
        {{/operation}}
        {{/operations}}
        {{/apis}}
    ];

    /**
     * Class constructor
     *
     * @param ContainerInterface|array $settings Either a ContainerInterface or an associative array of app settings
     *
     * @throws HttpNotImplementedException When implementation class doesn't exists
     * @throws Exception when not supported authorization schema type provided
     */
    public function __construct($settings = [])
    {
        if ($settings instanceof ContainerInterface) {
            // Set container to create App with on AppFactory
            AppFactory::setContainer($settings);
        }
        $this->slimApp = AppFactory::create();

        // middlewares requires Psr\Container\ContainerInterface
        $container = $this->slimApp->getContainer();

        {{#hasAuthMethods}}
        $authPackage = '{{authPackage}}';
        $basicAuthenticator = function (ServerRequestInterface &$request, TokenSearch $tokenSearch) use ($authPackage) {
            $message = "How about extending {{abstractNamePrefix}}Authenticator{{abstractNameSuffix}} class by {$authPackage}\BasicAuthenticator?";
            throw new HttpNotImplementedException($request, $message);
        };
        $apiKeyAuthenticator = function (ServerRequestInterface &$request, TokenSearch $tokenSearch) use ($authPackage) {
            $message = "How about extending {{abstractNamePrefix}}Authenticator{{abstractNameSuffix}} class by {$authPackage}\ApiKeyAuthenticator?";
            throw new HttpNotImplementedException($request, $message);
        };
        $oAuthAuthenticator = function (ServerRequestInterface &$request, TokenSearch $tokenSearch) use ($authPackage) {
            $message = "How about extending {{abstractNamePrefix}}Authenticator{{abstractNameSuffix}} class by {$authPackage}\OAuthAuthenticator?";
            throw new HttpNotImplementedException($request, $message);
        };
        {{/hasAuthMethods}}

        $userOptions = $this->getSetting($settings, 'tokenAuthenticationOptions', null);

        // mocker options
        $mockerOptions = $this->getSetting($settings, 'mockerOptions', null);
        $dataMocker = $mockerOptions['dataMocker'] ?? new OpenApiDataMocker();
        {{#isSlimPsr7}}
        $responseFactory = new ResponseFactory();
        {{/isSlimPsr7}}
        {{#isNyholmPsr7}}
        $responseFactory = new Psr17Factory();
        {{/isNyholmPsr7}}
        {{#isGuzzlePsr7}}
        $responseFactory = new HttpFactory();
        {{/isGuzzlePsr7}}
        {{#isZendDiactoros}}
        $responseFactory = new ResponseFactory();
        {{/isZendDiactoros}}
        $getMockStatusCodeCallback = $mockerOptions['getMockStatusCodeCallback'] ?? null;
        $mockAfterCallback = $mockerOptions['afterCallback'] ?? null;

        foreach ($this->operations as $operation) {
            $callback = function ($request, $response, $arguments) use ($operation) {
                $message = "How about extending {$operation['classname']} by {$operation['apiPackage']}\\{$operation['userClassname']} class implementing {$operation['operationId']} as a {$operation['httpMethod']} method?";
                throw new HttpNotImplementedException($request, $message);
            };
            $middlewares = [];

            if (class_exists("\\{$operation['apiPackage']}\\{$operation['userClassname']}")) {
                $callback = "\\{$operation['apiPackage']}\\{$operation['userClassname']}:{$operation['operationId']}";
            }

            {{#hasAuthMethods}}
            foreach ($operation['authMethods'] as $authMethod) {
                switch ($authMethod['type']) {
                    case 'http':
                        $authenticatorClassname = "\\{$authPackage}\\BasicAuthenticator";
                        if (class_exists($authenticatorClassname)) {
                            $basicAuthenticator = new $authenticatorClassname($container);
                        }

                        $middlewares[] = new TokenAuthentication($this->getTokenAuthenticationOptions([
                            'authenticator' => $basicAuthenticator,
                            'regex' => $authMethod['isBearer'] ? '/Bearer\s+(.*)$/i' : '/Basic\s+(.*)$/i',
                            'header' => 'Authorization',
                            'parameter' => null,
                            'cookie' => null,
                            'argument' => null,
                        ], $userOptions));
                        break;
                    case 'apiKey':
                        $authenticatorClassname = "\\{$authPackage}\\ApiKeyAuthenticator";
                        if (class_exists($authenticatorClassname)) {
                            $apiKeyAuthenticator = new $authenticatorClassname($container);
                        }

                        $middlewares[] = new TokenAuthentication($this->getTokenAuthenticationOptions([
                            'authenticator' => $apiKeyAuthenticator,
                            'regex' => '/^(.*)$/i',
                            'header' => $authMethod['isKeyInHeader'] ? $authMethod['keyParamName'] : null,
                            'parameter' => $authMethod['isKeyInQuery'] ? $authMethod['keyParamName'] : null,
                            'cookie' => $authMethod['isKeyInCookie'] ? $authMethod['keyParamName'] : null,
                            'argument' => null,
                        ], $userOptions));
                        break;
                    case 'oauth2':
                        $authenticatorClassname = "\\{$authPackage}\\OAuthAuthenticator";
                        if (class_exists($authenticatorClassname)) {
                            $oAuthAuthenticator = new $authenticatorClassname($container, $authMethod['scopes']);
                        }

                        $middlewares[] = new TokenAuthentication($this->getTokenAuthenticationOptions([
                            'authenticator' => $oAuthAuthenticator,
                            'regex' => '/Bearer\s+(.*)$/i',
                            'header' => 'Authorization',
                            'parameter' => null,
                            'cookie' => null,
                            'argument' => null,
                        ], $userOptions));
                        break;
                    default:
                        throw new Exception('Unknown authorization schema type');
                }
            }
            {{/hasAuthMethods}}

            if (is_callable($getMockStatusCodeCallback)) {
                $mockSchemaResponses = array_map(function ($item) {
                    return json_decode($item['jsonSchema'], true);
                }, $operation['responses']);
                $middlewares[] = new OpenApiDataMockerRouteMiddleware($dataMocker, $mockSchemaResponses, $responseFactory, $getMockStatusCodeCallback, $mockAfterCallback);
            }

            $this->addRoute(
                [$operation['httpMethod']],
                "{$operation['basePathWithoutHost']}{$operation['path']}",
                $callback,
                $middlewares
            )->setName($operation['operationId']);
        }
    }

    /**
     * Merges user defined options with dynamic params
     *
     * @param array $staticOptions Required static options
     * @param array $userOptions   User options
     *
     * @return array Merged array
     */
    private function getTokenAuthenticationOptions(array $staticOptions, array $userOptions = null)
    {
        if (is_array($userOptions) === false) {
            return $staticOptions;
        }

        return array_merge($userOptions, $staticOptions);
    }

    /**
     * Returns app setting by name.
     *
     * @param ContainerInterface|array $settings    Either a ContainerInterface or an associative array of app settings
     * @param string                   $settingName Setting name
     * @param mixed                    $default     Default setting value.
     *
     * @return mixed
     */
    private function getSetting($settings, $settingName, $default = null)
    {
        if ($settings instanceof ContainerInterface && $settings->has($settingName)) {
            return $settings->get($settingName);
        } elseif (is_array($settings) && array_key_exists($settingName, $settings)) {
            return $settings[$settingName];
        }

        return $default;
    }

    /**
     * Add route with multiple methods
     *
     * @param string[]        $methods     Numeric array of HTTP method names
     * @param string          $pattern     The route URI pattern
     * @param callable|string $callable    The route callback routine
     * @param array|null      $middlewares List of middlewares
     *
     * @return RouteInterface
     *
     * @throws InvalidArgumentException If the route pattern isn't a string
     */
    public function addRoute(array $methods, string $pattern, $callable, $middlewares = [])
    {
        $route = $this->slimApp->map($methods, $pattern, $callable);
        foreach ($middlewares as $middleware) {
            $route->add($middleware);
        }
        return $route;
    }

    /**
     * Returns Slim Framework instance
     *
     * @return App
     */
    public function getSlimApp()
    {
        return $this->slimApp;
    }
}
{{/apiInfo}}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy