NelmioApiDocBundle/Describer/SwaggerPhpDescriber.php

83 lines
2.5 KiB
PHP
Raw Normal View History

2016-07-28 10:20:59 +02:00
<?php
/*
2016-12-29 12:09:26 +01:00
* This file is part of the NelmioApiDocBundle package.
2016-07-28 10:20:59 +02:00
*
2016-12-29 12:09:26 +01:00
* (c) Nelmio
2016-07-28 10:20:59 +02:00
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
2016-12-29 12:09:26 +01:00
namespace Nelmio\ApiDocBundle\Describer;
2016-07-28 10:20:59 +02:00
2017-01-14 17:36:56 +01:00
use Nelmio\ApiDocBundle\SwaggerPhp\AddDefaults;
use Nelmio\ApiDocBundle\SwaggerPhp\ModelRegister;
use Nelmio\ApiDocBundle\SwaggerPhp\OperationResolver;
2017-01-23 19:46:38 +01:00
use Nelmio\ApiDocBundle\Util\ControllerReflector;
2017-01-14 17:36:56 +01:00
use Swagger\Analyser;
use Swagger\Analysis;
2017-01-23 19:46:38 +01:00
use Symfony\Component\Finder\Finder;
use Symfony\Component\Routing\RouteCollection;
2017-01-14 17:36:56 +01:00
final class SwaggerPhpDescriber extends ExternalDocDescriber implements ModelRegistryAwareInterface
2016-07-28 10:20:59 +02:00
{
2017-01-14 17:36:56 +01:00
use ModelRegistryAwareTrait;
2017-01-23 19:46:38 +01:00
private $routeCollection;
private $controllerReflector;
2017-01-23 19:46:38 +01:00
public function __construct(RouteCollection $routeCollection, ControllerReflector $controllerReflector, bool $overwrite = false)
2016-07-28 10:20:59 +02:00
{
2017-01-23 19:46:38 +01:00
$this->routeCollection = $routeCollection;
$this->controllerReflector = $controllerReflector;
2017-01-14 17:36:56 +01:00
2017-01-23 19:46:38 +01:00
parent::__construct(function () {
$whitelist = Analyser::$whitelist;
Analyser::$whitelist = false;
try {
$options = ['processors' => $this->getProcessors()];
$annotation = \Swagger\scan($this->getFinder(), $options);
2017-01-14 17:36:56 +01:00
2017-01-23 19:46:38 +01:00
return json_decode(json_encode($annotation));
} finally {
Analyser::$whitelist = $whitelist;
}
2016-07-29 10:22:40 +02:00
}, $overwrite);
2016-07-28 10:20:59 +02:00
}
2017-01-23 19:46:38 +01:00
private function getFinder()
{
2017-01-23 19:46:38 +01:00
$files = [];
foreach ($this->routeCollection->all() as $route) {
if (!$route->hasDefault('_controller')) {
continue;
}
// if able to resolve the controller
$controller = $route->getDefault('_controller');
if ($callable = $this->controllerReflector->getReflectionClassAndMethod($controller)) {
list($class, $method) = $callable;
$files[$class->getFileName()] = true;
}
}
$finder = new Finder();
$finder->append(array_keys($files));
return $finder;
}
2017-01-14 17:36:56 +01:00
private function getProcessors(): array
{
$processors = [
new AddDefaults(),
new ModelRegister($this->modelRegistry),
2017-01-23 19:46:38 +01:00
new OperationResolver($this->routeCollection, $this->controllerReflector),
2017-01-14 17:36:56 +01:00
];
return array_merge($processors, Analysis::processors());
}
2016-07-28 10:20:59 +02:00
}