Skip to content

Instantly share code, notes, and snippets.

@gielfeldt
Created August 2, 2017 11:54
Show Gist options
  • Save gielfeldt/c41640296f59dcd005f0c226ac3eaeba to your computer and use it in GitHub Desktop.
Save gielfeldt/c41640296f59dcd005f0c226ac3eaeba to your computer and use it in GitHub Desktop.
Swagger controller provider
<?php
namespace SimpleSwagger;
use Silex\Application;
use Silex\Api\ControllerProviderInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class SwaggerControllerProvider implements ControllerProviderInterface
{
protected $className;
public function __construct($className)
{
$this->className = $className;
$reflection = new \ReflectionClass($this->className);
$this->basePath = $reflection->getFileName();
}
public function connect(Application $app)
{
$this->config = new \Basster\Silex\Provider\Swagger\SwaggerConfig($this->basePath);
$this->service = new \Basster\Silex\Provider\Swagger\SwaggerService($this->config);
$controllers = $app['controllers_factory'];
$controllers->get(
'/swagger.json',
[$this, 'getSwaggerResponse']
);
$swagger = json_decode((string) $this->service->getSwagger());
foreach ($swagger->paths as $path => $pathInfo) {
foreach ($pathInfo as $method => $methodInfo) {
$controllers->match(
$path,
$this->className . '::' . $methodInfo->operationId
)->method(strtoupper($method));
}
}
return $controllers;
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request
*
* @return \Symfony\Component\HttpFoundation\Response
* @throws \InvalidArgumentException
*/
public function getSwaggerResponse(Request $request, $_route, Application $app)
{
$url = $_SERVER['REQUEST_URI'];
$part = '/swagger.json';
if (substr($url, -strlen($part)) != $part) {
return $app->abort(500);
}
$basePath = substr($url, 0, -strlen($part));
$swagger = json_decode((string) $this->service->getSwagger());
$swagger->host = $_SERVER['HTTP_HOST'];
$swagger->basePath = $basePath;
$output = json_encode($swagger);
$response = Response::create(
$output,
Response::HTTP_OK,
['Content-Type' => 'application/json']
);
#$response->setCache($this->cacheConfig);
$response->setEtag(md5($output));
$response->isNotModified($request);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment