Created
August 2, 2017 11:54
-
-
Save gielfeldt/c41640296f59dcd005f0c226ac3eaeba to your computer and use it in GitHub Desktop.
Swagger controller provider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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