Fix code by php-cs-fixer

This commit is contained in:
Ilyas Salikhov 2024-10-01 15:54:04 +03:00
parent cb69478c78
commit e06fb926f5
92 changed files with 9252 additions and 10667 deletions

View File

@ -18,85 +18,85 @@ use Symfony\Component\Routing\Route;
*/
class ApiDoc
{
const DEFAULT_VIEW = 'default';
public const DEFAULT_VIEW = 'default';
/**
* Requirements are mandatory parameters in a route.
*
* @var array
*/
private $requirements = array();
private $requirements = [];
/**
* Which views is this route used. Defaults to "Default"
*
* @var array
*/
private $views = array();
private $views = [];
/**
* Filters are optional parameters in the query string.
*
* @var array
*/
private $filters = array();
private $filters = [];
/**
* Parameters are data a client can send.
*
* @var array
*/
private $parameters = array();
private $parameters = [];
/**
* Headers that client can send.
*
* @var array
*/
private $headers = array();
private $headers = [];
/**
* @var string
*/
private $input = null;
private $input;
/**
* @var string
*/
private $inputs = null;
private $inputs;
/**
* @var string
*/
private $output = null;
private $output;
/**
* @var string
*/
private $link = null;
private $link;
/**
* Most of the time, a single line of text describing the action.
*
* @var string
*/
private $description = null;
private $description;
/**
* Section to group actions together.
*
* @var string
*/
private $section = null;
private $section;
/**
* Extended documentation.
*
* @var string
*/
private $documentation = null;
private $documentation;
/**
* @var Boolean
* @var bool
*/
private $resource = false;
@ -118,7 +118,7 @@ class ApiDoc
/**
* @var array
*/
private $response = array();
private $response = [];
/**
* @var Route
@ -126,19 +126,19 @@ class ApiDoc
private $route;
/**
* @var boolean
* @var bool
*/
private $https = false;
/**
* @var boolean
* @var bool
*/
private $authentication = false;
/**
* @var array
*/
private $authenticationRoles = array();
private $authenticationRoles = [];
/**
* @var int
@ -146,34 +146,34 @@ class ApiDoc
private $cache;
/**
* @var boolean
* @var bool
*/
private $deprecated = false;
/**
* @var array
*/
private $statusCodes = array();
private $statusCodes = [];
/**
* @var string|null
*/
private $resourceDescription = null;
private $resourceDescription;
/**
* @var array
*/
private $responseMap = array();
private $responseMap = [];
/**
* @var array
*/
private $parsedResponseMap = array();
private $parsedResponseMap = [];
/**
* @var array
*/
private $tags = array();
private $tags = [];
public function __construct(array $data)
{
@ -219,7 +219,7 @@ class ApiDoc
if (isset($data['views'])) {
if (!is_array($data['views'])) {
$data['views'] = array($data['views']);
$data['views'] = [$data['views']];
}
foreach ($data['views'] as $view) {
@ -324,44 +324,38 @@ class ApiDoc
/**
* @param string $name
* @param array $filter
*/
public function addFilter($name, array $filter)
public function addFilter($name, array $filter): void
{
$this->filters[$name] = $filter;
}
/**
* @param string $statusCode
* @param mixed $description
*/
public function addStatusCode($statusCode, $description)
public function addStatusCode($statusCode, $description): void
{
$this->statusCodes[$statusCode] = !is_array($description) ? array($description) : $description;
$this->statusCodes[$statusCode] = !is_array($description) ? [$description] : $description;
}
/**
* @param string $tag
* @param string $colorCode
*/
public function addTag($tag, $colorCode = '#d9534f')
public function addTag($tag, $colorCode = '#d9534f'): void
{
$this->tags[$tag] = $colorCode;
}
/**
* @param string $name
* @param array $requirement
*/
public function addRequirement($name, array $requirement)
public function addRequirement($name, array $requirement): void
{
$this->requirements[$name] = $requirement;
}
/**
* @param array $requirements
*/
public function setRequirements(array $requirements)
public function setRequirements(array $requirements): void
{
$this->requirements = array_merge($this->requirements, $requirements);
}
@ -401,7 +395,7 @@ class ApiDoc
/**
* @param string $description
*/
public function setDescription($description)
public function setDescription($description): void
{
$this->description = $description;
}
@ -409,7 +403,7 @@ class ApiDoc
/**
* @param string $link
*/
public function setLink($link)
public function setLink($link): void
{
$this->link = $link;
}
@ -417,7 +411,7 @@ class ApiDoc
/**
* @param string $section
*/
public function setSection($section)
public function setSection($section): void
{
$this->section = $section;
}
@ -449,7 +443,7 @@ class ApiDoc
/**
* @param string $documentation
*/
public function setDocumentation($documentation)
public function setDocumentation($documentation): void
{
$this->documentation = $documentation;
}
@ -463,16 +457,13 @@ class ApiDoc
}
/**
* @return Boolean
* @return bool
*/
public function isResource()
{
return (bool) $this->resource;
}
/**
* @return mixed
*/
public function getResource()
{
return $this->resource && is_string($this->resource) ? $this->resource : false;
@ -480,44 +471,31 @@ class ApiDoc
/**
* @param string $name
* @param array $parameter
*/
public function addParameter($name, array $parameter)
public function addParameter($name, array $parameter): void
{
$this->parameters[$name] = $parameter;
}
/**
* @param array $parameters
*/
public function setParameters(array $parameters)
public function setParameters(array $parameters): void
{
$this->parameters = $parameters;
}
/**
* @param $name
* @param array $header
*/
public function addHeader($name, array $header)
public function addHeader($name, array $header): void
{
$this->headers[$name] = $header;
}
/**
* Sets the response data as processed by the parsers - same format as parameters
*
* @param array $response
*/
public function setResponse(array $response)
public function setResponse(array $response): void
{
$this->response = $response;
}
/**
* @param Route $route
*/
public function setRoute(Route $route)
public function setRoute(Route $route): void
{
$this->route = $route;
@ -557,13 +535,13 @@ class ApiDoc
/**
* @param string $host
*/
public function setHost($host)
public function setHost($host): void
{
$this->host = $host;
}
/**
* @return boolean
* @return bool
*/
public function getHttps()
{
@ -571,15 +549,15 @@ class ApiDoc
}
/**
* @param boolean $https
* @param bool $https
*/
public function setHttps($https)
public function setHttps($https): void
{
$this->https = $https;
}
/**
* @return boolean
* @return bool
*/
public function getAuthentication()
{
@ -587,9 +565,9 @@ class ApiDoc
}
/**
* @param boolean $authentication
* @param bool $authentication
*/
public function setAuthentication($authentication)
public function setAuthentication($authentication): void
{
$this->authentication = $authentication;
}
@ -605,7 +583,7 @@ class ApiDoc
/**
* @param array $authenticationRoles
*/
public function setAuthenticationRoles($authenticationRoles)
public function setAuthenticationRoles($authenticationRoles): void
{
$this->authenticationRoles = $authenticationRoles;
}
@ -621,13 +599,13 @@ class ApiDoc
/**
* @param int $cache
*/
public function setCache($cache)
public function setCache($cache): void
{
$this->cache = (int) $cache;
}
/**
* @return boolean
* @return bool
*/
public function getDeprecated()
{
@ -667,7 +645,8 @@ class ApiDoc
}
/**
* @param boolean $deprecated
* @param bool $deprecated
*
* @return $this
*/
public function setDeprecated($deprecated)
@ -690,10 +669,10 @@ class ApiDoc
*/
public function toArray()
{
$data = array(
$data = [
'method' => $this->method,
'uri' => $this->uri,
);
];
if ($host = $this->host) {
$data['host'] = $host;
@ -768,7 +747,7 @@ class ApiDoc
}
/**
* @return null|string
* @return string|null
*/
public function getResourceDescription()
{
@ -796,14 +775,12 @@ class ApiDoc
}
/**
* @param $model
* @param $type
* @param int $statusCode
*/
public function setResponseForStatusCode($model, $type, $statusCode = 200)
public function setResponseForStatusCode($model, $type, $statusCode = 200): void
{
$this->parsedResponseMap[$statusCode] = array('type' => $type, 'model' => $model);
if ($statusCode == 200 && $this->response !== $model) {
$this->parsedResponseMap[$statusCode] = ['type' => $type, 'model' => $model];
if (200 == $statusCode && $this->response !== $model) {
$this->response = $model;
}
}

View File

@ -40,7 +40,7 @@ class DumpCommand extends Command
private readonly MarkdownFormatter $markdownFormatter,
private readonly HtmlFormatter $htmlFormatter,
private readonly ApiDocExtractor $apiDocExtractor,
private readonly TranslatorInterface $translator
private readonly TranslatorInterface $translator,
) {
parent::__construct();
}

View File

@ -37,7 +37,7 @@ class SwaggerDumpCommand extends Command
public function __construct(
private readonly ApiDocExtractor $extractor,
private readonly SwaggerFormatter $formatter
private readonly SwaggerFormatter $formatter,
) {
parent::__construct();
}
@ -71,7 +71,7 @@ class SwaggerDumpCommand extends Command
if (false !== ($resource = $input->getOption('resource'))) {
$data = $this->getApiDeclaration($apiDocs, $resource);
if (count($data['apis']) === 0) {
if (0 === count($data['apis'])) {
throw new \InvalidArgumentException(sprintf('Resource "%s" does not exist.', $resource));
}
$this->dump($data, $resource, $input, $output);
@ -92,7 +92,6 @@ class SwaggerDumpCommand extends Command
$this->dump($data, null, $input, $output, false);
foreach ($data['apis'] as $api) {
$resource = substr($api['path'], 1);
if (!$input->getArgument('destination')) {
$output->writeln('');
@ -117,14 +116,13 @@ class SwaggerDumpCommand extends Command
return;
}
if ($treatAsFile === false) {
if (false === $treatAsFile) {
if (!$this->filesystem->exists($destination)) {
$this->filesystem->mkdir($destination);
}
}
if (!$resource) {
if (!$treatAsFile) {
$destination = sprintf('%s/api-docs.json', rtrim($destination, '\\/'));
}
@ -134,13 +132,12 @@ class SwaggerDumpCommand extends Command
return;
}
if ($treatAsFile === false) {
if (false === $treatAsFile) {
$destination = sprintf('%s/%s.json', rtrim($destination, '\\/'), $resource);
}
$message = sprintf('<comment>Dump API declaration to %s: </comment>', $destination);
$this->writeToFile($content, $destination, $output, $message);
}
protected function writeToFile($content, $file, OutputInterface $output, $message): void

View File

@ -11,22 +11,22 @@
namespace Nelmio\ApiDocBundle\Controller;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Nelmio\ApiDocBundle\Extractor\ApiDocExtractor;
use Nelmio\ApiDocBundle\Formatter\HtmlFormatter;
use Nelmio\ApiDocBundle\Formatter\RequestAwareSwaggerFormatter;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Nelmio\ApiDocBundle\Formatter\SwaggerFormatter;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class ApiDocController extends AbstractController
{
public function __construct(
private readonly ApiDocExtractor $extractor,
private readonly HtmlFormatter $htmlFormatter,
private readonly SwaggerFormatter $swaggerFormatter
private readonly SwaggerFormatter $swaggerFormatter,
) {
}
@ -42,18 +42,17 @@ class ApiDocController extends AbstractController
}
$htmlContent = $this->htmlFormatter->format($extractedDoc);
return new Response($htmlContent, 200, array('Content-Type' => 'text/html'));
return new Response($htmlContent, 200, ['Content-Type' => 'text/html']);
}
public function swagger(Request $request, $resource = null)
{
$docs = $this->extractor->all();
$formatter = new RequestAwareSwaggerFormatter($request, $this->swaggerFormatter);
$spec = $formatter->format($docs, $resource ? '/' . $resource : null);
if ($resource !== null && count($spec['apis']) === 0) {
if (null !== $resource && 0 === count($spec['apis'])) {
throw $this->createNotFoundException(sprintf('Cannot find resource "%s"', $resource));
}

View File

@ -18,37 +18,38 @@ namespace Nelmio\ApiDocBundle;
*/
class DataTypes
{
const INTEGER = 'integer';
public const INTEGER = 'integer';
const FLOAT = 'float';
public const FLOAT = 'float';
const STRING = 'string';
public const STRING = 'string';
const BOOLEAN = 'boolean';
public const BOOLEAN = 'boolean';
const FILE = 'file';
public const FILE = 'file';
const ENUM = 'choice';
public const ENUM = 'choice';
const COLLECTION = 'collection';
public const COLLECTION = 'collection';
const MODEL = 'model';
public const MODEL = 'model';
const DATE = 'date';
public const DATE = 'date';
const DATETIME = 'datetime';
public const DATETIME = 'datetime';
const TIME = 'time';
public const TIME = 'time';
/**
* Returns true if the supplied `actualType` value is considered a primitive type. Returns false, otherwise.
*
* @param string $type
*
* @return bool
*/
public static function isPrimitive($type)
{
return in_array(strtolower($type), array(
return in_array(strtolower($type), [
static::INTEGER,
static::FLOAT,
static::STRING,
@ -58,6 +59,6 @@ class DataTypes
static::DATETIME,
static::TIME,
static::ENUM,
));
]);
}
}

View File

@ -22,12 +22,9 @@ use Symfony\Component\DependencyInjection\Reference;
*/
class AnnotationsProviderCompilerPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
$annotationsProviders = array();
$annotationsProviders = [];
foreach ($container->findTaggedServiceIds('nelmio_api_doc.extractor.annotations_provider') as $id => $attributes) {
$annotationsProviders[] = new Reference($id);
}

View File

@ -44,7 +44,7 @@ class Configuration implements ConfigurationInterface
->arrayNode('request_listener')
->beforeNormalization()
->ifTrue(function ($a) { return is_bool($a); })
->then(function ($a) { return array('enabled' => $a); })
->then(function ($a) { return ['enabled' => $a]; })
->end()
->addDefaultsIfNotSet()
->children()
@ -62,15 +62,15 @@ class Configuration implements ConfigurationInterface
->addDefaultsIfNotSet()
->beforeNormalization()
->ifString()
->then(function ($v) { return array('default_format' => $v); })
->then(function ($v) { return ['default_format' => $v]; })
->end()
->children()
->arrayNode('formats')
->defaultValue(array('form', 'json'))
->defaultValue(['form', 'json'])
->prototype('scalar')->end()
->end()
->enumNode('default_format')
->values(array('form', 'json'))
->values(['form', 'json'])
->defaultValue('form')
->end()
->end()
@ -79,14 +79,14 @@ class Configuration implements ConfigurationInterface
->addDefaultsIfNotSet()
->children()
->arrayNode('formats')
->defaultValue(array(
->defaultValue([
'json' => 'application/json',
'xml' => 'application/xml'
))
'xml' => 'application/xml',
])
->prototype('scalar')->end()
->end()
->enumNode('method')
->values(array('format_param', 'accept_header'))
->values(['format_param', 'accept_header'])
->defaultValue('format_param')
->end()
->scalarNode('default_format')->defaultValue('json')->end()
@ -97,14 +97,14 @@ class Configuration implements ConfigurationInterface
->scalarNode('delivery')
->isRequired()
->validate()
->ifNotInArray(array('query', 'http', 'header'))
->ifNotInArray(['query', 'http', 'header'])
->thenInvalid("Unknown authentication delivery type '%s'.")
->end()
->end()
->scalarNode('name')->isRequired()->end()
->enumNode('type')
->info('Required if http delivery is selected.')
->values(array('basic', 'bearer'))
->values(['basic', 'bearer'])
->end()
->booleanNode('custom_endpoint')->defaultFalse()->end()
->end()
@ -114,7 +114,7 @@ class Configuration implements ConfigurationInterface
})
->thenInvalid('"type" is required when using http delivery.')
->end()
# http_basic BC
// http_basic BC
->beforeNormalization()
->ifTrue(function ($v) {
return 'http_basic' === $v['delivery'];
@ -169,7 +169,8 @@ class Configuration implements ConfigurationInterface
->scalarNode('file')->defaultValue('%kernel.cache_dir%/api-doc.cache')->end()
->end()
->end()
->end();
->end()
;
return $treeBuilder;
}

View File

@ -11,24 +11,22 @@
namespace Nelmio\ApiDocBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class ExtractorHandlerCompilerPass implements CompilerPassInterface
{
/**
* {@inheritDoc}
*/
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
$handlers = array();
$handlers = [];
foreach ($container->findTaggedServiceIds('nelmio_api_doc.extractor.handler') as $id => $attributes) {
$handlers[] = new Reference($id);
}
$container
->getDefinition('nelmio_api_doc.extractor.api_doc_extractor')
->replaceArgument(3, $handlers);
->replaceArgument(3, $handlers)
;
}
}

View File

@ -8,9 +8,9 @@ use Symfony\Component\DependencyInjection\Reference;
class FormInfoParserCompilerPass implements CompilerPassInterface
{
const TAG_NAME = 'nelmio_api_doc.extractor.form_info_parser';
public const TAG_NAME = 'nelmio_api_doc.extractor.form_info_parser';
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
if (!$container->has('nelmio_api_doc.parser.form_type_parser')) {
return;

View File

@ -2,10 +2,10 @@
namespace Nelmio\ApiDocBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
/**
* Loads parsers to extract information from different libraries.
@ -14,7 +14,7 @@ use Symfony\Component\Config\FileLocator;
*/
class LoadExtractorParsersPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));

View File

@ -12,20 +12,17 @@
namespace Nelmio\ApiDocBundle\DependencyInjection;
use Nelmio\ApiDocBundle\Parser\FormInfoParser;
use Symfony\Component\Config\Definition\Processor;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\Definition\Processor;
class NelmioApiDocExtension extends Extension
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container)
public function load(array $configs, ContainerBuilder $container): void
{
$processor = new Processor();
$configuration = new Configuration();
@ -47,7 +44,8 @@ class NelmioApiDocExtension extends Extension
if (method_exists($container, 'registerForAutoconfiguration')) {
$container->registerForAutoconfiguration(FormInfoParser::class)
->addTag(FormInfoParserCompilerPass::TAG_NAME);
->addTag(FormInfoParserCompilerPass::TAG_NAME)
;
}
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
@ -74,7 +72,7 @@ class NelmioApiDocExtension extends Extension
$container->setParameter('nelmio_api_doc.swagger.info', $config['swagger']['info']);
$container->setParameter('nelmio_api_doc.swagger.model_naming_strategy', $config['swagger']['model_naming_strategy']);
if ($config['cache']['enabled'] === true) {
if (true === $config['cache']['enabled']) {
$arguments = $container->getDefinition('nelmio_api_doc.extractor.api_doc_extractor')->getArguments();
$caching = new Definition('Nelmio\ApiDocBundle\Extractor\CachingApiDocExtractor');
$arguments[] = $config['cache']['file'];
@ -86,7 +84,6 @@ class NelmioApiDocExtension extends Extension
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('autowired.yaml');
}
/**

View File

@ -2,13 +2,13 @@
namespace Nelmio\ApiDocBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
class RegisterExtractorParsersPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
if (false === $container->hasDefinition('nelmio_api_doc.extractor.api_doc_extractor')) {
return;
@ -17,10 +17,10 @@ class RegisterExtractorParsersPass implements CompilerPassInterface
$definition = $container->getDefinition('nelmio_api_doc.extractor.api_doc_extractor');
// find registered parsers and sort by priority
$sortedParsers = array();
$sortedParsers = [];
foreach ($container->findTaggedServiceIds('nelmio_api_doc.extractor.parser') as $id => $tagAttributes) {
foreach ($tagAttributes as $attributes) {
$priority = isset($attributes['priority']) ? $attributes['priority'] : 0;
$priority = $attributes['priority'] ?? 0;
$sortedParsers[$priority][] = $id;
}
}
@ -32,7 +32,7 @@ class RegisterExtractorParsersPass implements CompilerPassInterface
// add method call for each registered parsers
foreach ($sortedParsers as $id) {
$definition->addMethodCall('addParser', array(new Reference($id)));
$definition->addMethodCall('addParser', [new Reference($id)]);
}
}
}

View File

@ -21,31 +21,28 @@ use Symfony\Component\DependencyInjection\ContainerBuilder;
*/
class SwaggerConfigCompilerPass implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* @param ContainerBuilder $container
*
* @api
*/
public function process(ContainerBuilder $container)
public function process(ContainerBuilder $container): void
{
$formatter = $container->getDefinition('nelmio_api_doc.formatter.swagger_formatter');
$formatter->addMethodCall('setBasePath', array($container->getParameter('nelmio_api_doc.swagger.base_path')));
$formatter->addMethodCall('setApiVersion', array($container->getParameter('nelmio_api_doc.swagger.api_version')));
$formatter->addMethodCall('setSwaggerVersion', array($container->getParameter('nelmio_api_doc.swagger.swagger_version')));
$formatter->addMethodCall('setInfo', array($container->getParameter('nelmio_api_doc.swagger.info')));
$formatter->addMethodCall('setBasePath', [$container->getParameter('nelmio_api_doc.swagger.base_path')]);
$formatter->addMethodCall('setApiVersion', [$container->getParameter('nelmio_api_doc.swagger.api_version')]);
$formatter->addMethodCall('setSwaggerVersion', [$container->getParameter('nelmio_api_doc.swagger.swagger_version')]);
$formatter->addMethodCall('setInfo', [$container->getParameter('nelmio_api_doc.swagger.info')]);
$authentication = $container->getParameter('nelmio_api_doc.sandbox.authentication');
$formatter->setArguments(array(
$formatter->setArguments([
$container->getParameter('nelmio_api_doc.swagger.model_naming_strategy'),
));
]);
if ($authentication !== null) {
$formatter->addMethodCall('setAuthenticationConfig', array($authentication));
if (null !== $authentication) {
$formatter->addMethodCall('setAuthenticationConfig', [$authentication]);
}
}
}

View File

@ -14,18 +14,18 @@ namespace Nelmio\ApiDocBundle\EventListener;
use Nelmio\ApiDocBundle\Extractor\ApiDocExtractor;
use Nelmio\ApiDocBundle\Formatter\FormatterInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class RequestListener
{
/**
* @var \Nelmio\ApiDocBundle\Extractor\ApiDocExtractor
* @var ApiDocExtractor
*/
protected $extractor;
/**
* @var \Nelmio\ApiDocBundle\Formatter\FormatterInterface
* @var FormatterInterface
*/
protected $formatter;
@ -41,10 +41,7 @@ class RequestListener
$this->parameter = $parameter;
}
/**
* {@inheritdoc}
*/
public function onKernelRequest(RequestEvent $event)
public function onKernelRequest(RequestEvent $event): void
{
if (HttpKernelInterface::MAIN_REQUEST !== $event->getRequestType()) {
return;
@ -62,9 +59,9 @@ class RequestListener
if (null !== $annotation = $this->extractor->get($controller, $route)) {
$result = $this->formatter->formatOne($annotation);
$event->setResponse(new Response($result, 200, array(
'Content-Type' => 'text/html'
)));
$event->setResponse(new Response($result, 200, [
'Content-Type' => 'text/html',
]));
}
}
}

View File

@ -44,23 +44,20 @@ class DunglasApiProvider implements AnnotationsProviderInterface
public function __construct(
ResourceCollectionInterface $resourceCollection,
ApiDocumentationBuilderInterface $apiDocumentationBuilder,
ClassMetadataFactoryInterface $classMetadataFactory
ClassMetadataFactoryInterface $classMetadataFactory,
) {
$this->resourceCollection = $resourceCollection;
$this->apiDocumentationBuilder = $apiDocumentationBuilder;
$this->classMetadataFactory = $classMetadataFactory;
}
/**
* {@inheritdoc}
*/
public function getAnnotations()
{
$annotations = [];
$hydraDoc = $this->apiDocumentationBuilder->getApiDocumentation();
$entrypointHydraDoc = $this->getResourceHydraDoc($hydraDoc, '#Entrypoint');
/**
/*
* @var ResourceInterface
*/
foreach ($this->resourceCollection as $resource) {
@ -86,10 +83,6 @@ class DunglasApiProvider implements AnnotationsProviderInterface
* Builds ApiDoc annotation from DunglasApiBundle data.
*
* @param bool $collection
* @param ResourceInterface $resource
* @param OperationInterface $operation
* @param array $resourceHydraDoc
* @param array $entrypointHydraDoc
*
* @return ApiDoc
*/
@ -98,7 +91,7 @@ class DunglasApiProvider implements AnnotationsProviderInterface
ResourceInterface $resource,
OperationInterface $operation,
array $resourceHydraDoc,
array $entrypointHydraDoc = []
array $entrypointHydraDoc = [],
) {
$method = $operation->getRoute()->getMethods()[0];
@ -145,7 +138,6 @@ class DunglasApiProvider implements AnnotationsProviderInterface
/**
* Gets Hydra documentation for the given resource.
*
* @param array $hydraApiDoc
* @param string $prefixedShortName
*
* @return array|null
@ -163,7 +155,6 @@ class DunglasApiProvider implements AnnotationsProviderInterface
* Gets the Hydra documentation of a given operation.
*
* @param string $method
* @param array $hydraDoc
*
* @return array|null
*/
@ -181,7 +172,6 @@ class DunglasApiProvider implements AnnotationsProviderInterface
*
* @param string $shortName
* @param string $method
* @param array $hydraEntrypointDoc
*
* @return array|null
*/

View File

@ -40,7 +40,7 @@ class ApiDocExtractor
protected DocCommentExtractor $commentExtractor,
protected array $handlers,
protected array $annotationsProviders,
protected array $excludeSections
protected array $excludeSections,
) {
}
@ -80,12 +80,13 @@ class ApiDocExtractor
foreach ($data as $k => $a) {
// ignore other api version's routes
if (
$a['annotation']->getRoute()->getDefault('_version') &&
!version_compare($apiVersion ?? '', $a['annotation']->getRoute()->getDefault('_version'), '=')
$a['annotation']->getRoute()->getDefault('_version')
&& !version_compare($apiVersion ?? '', $a['annotation']->getRoute()->getDefault('_version'), '=')
) {
unset($data[$k]);
}
}
return $data;
}
@ -100,8 +101,8 @@ class ApiDocExtractor
*/
public function extractAnnotations(array $routes, $view = ApiDoc::DEFAULT_VIEW)
{
$array = array();
$resources = array();
$array = [];
$resources = [];
foreach ($routes as $route) {
if (!$route instanceof Route) {
@ -111,8 +112,8 @@ class ApiDocExtractor
if ($method = $this->getReflectionMethod($route->getDefault('_controller'))) {
$annotation = $this->reader->getMethodAnnotation($method, static::ANNOTATION_CLASS);
if (
$annotation && !in_array($annotation->getSection(), $this->excludeSections) &&
(in_array($view, $annotation->getViews()) || (0 === count($annotation->getViews()) && $view === ApiDoc::DEFAULT_VIEW))
$annotation && !in_array($annotation->getSection(), $this->excludeSections)
&& (in_array($view, $annotation->getViews()) || (0 === count($annotation->getViews()) && ApiDoc::DEFAULT_VIEW === $view))
) {
if ($annotation->isResource()) {
if ($resource = $annotation->getResource()) {
@ -123,7 +124,7 @@ class ApiDocExtractor
}
}
$array[] = array('annotation' => $this->extractData($annotation, $route, $method));
$array[] = ['annotation' => $this->extractData($annotation, $route, $method)];
}
}
}
@ -131,7 +132,7 @@ class ApiDocExtractor
foreach ($this->annotationsProviders as $annotationProvider) {
foreach ($annotationProvider->getAnnotations() as $annotation) {
$route = $annotation->getRoute();
$array[] = array('annotation' => $this->extractData($annotation, $route, $this->getReflectionMethod($route->getDefault('_controller'))));
$array[] = ['annotation' => $this->extractData($annotation, $route, $this->getReflectionMethod($route->getDefault('_controller')))];
}
}
@ -141,7 +142,7 @@ class ApiDocExtractor
$path = $element['annotation']->getRoute()->getPath() ?: '';
foreach ($resources as $resource) {
if (0 === strpos($path, $resource) || $resource === $element['annotation']->getResource()) {
if (str_starts_with($path, $resource) || $resource === $element['annotation']->getResource()) {
$array[$index]['resource'] = $resource;
$hasResource = true;
@ -154,7 +155,7 @@ class ApiDocExtractor
}
}
$methodOrder = array('GET', 'POST', 'PUT', 'DELETE');
$methodOrder = ['GET', 'POST', 'PUT', 'DELETE'];
usort($array, function ($a, $b) use ($methodOrder) {
if ($a['resource'] === $b['resource']) {
if ($a['annotation']->getRoute()->getPath() === $b['annotation']->getRoute()->getPath()) {
@ -187,7 +188,8 @@ class ApiDocExtractor
* Returns the ReflectionMethod for the given controller string.
*
* @param string $controller
* @return \ReflectionMethod|null
*
* @return \ReflectionMethod|null
*/
public function getReflectionMethod($controller)
{
@ -215,7 +217,8 @@ class ApiDocExtractor
*
* @param string $controller
* @param string $route
* @return ApiDoc|null
*
* @return ApiDoc|null
*/
public function get($controller, $route)
{
@ -232,10 +235,8 @@ class ApiDocExtractor
/**
* Registers a class parser to use for parsing input class metadata
*
* @param ParserInterface $parser
*/
public function addParser(ParserInterface $parser)
public function addParser(ParserInterface $parser): void
{
$this->parsers[] = $parser;
}
@ -243,9 +244,6 @@ class ApiDocExtractor
/**
* Returns a new ApiDoc instance with more data.
*
* @param ApiDoc $annotation
* @param Route $route
* @param \ReflectionMethod $method
* @return ApiDoc
*/
protected function extractData(ApiDoc $annotation, Route $route, \ReflectionMethod $method)
@ -262,7 +260,7 @@ class ApiDocExtractor
// route
$annotation->setRoute($route);
$inputs = array();
$inputs = [];
if (null !== $annotation->getInputs()) {
$inputs = $annotation->getInputs();
} elseif (null !== $annotation->getInput()) {
@ -270,11 +268,11 @@ class ApiDocExtractor
}
// input (populates 'parameters' for the formatters)
if (sizeof($inputs)) {
$parameters = array();
if (count($inputs)) {
$parameters = [];
foreach ($inputs as $input) {
$normalizedInput = $this->normalizeClassParameter($input);
$supportedParsers = array();
$supportedParsers = [];
foreach ($this->getParsers($normalizedInput) as $parser) {
if ($parser->supports($normalizedInput)) {
$supportedParsers[] = $parser;
@ -310,8 +308,8 @@ class ApiDocExtractor
// output (populates 'response' for the formatters)
if (null !== $output = $annotation->getOutput()) {
$response = array();
$supportedParsers = array();
$response = [];
$supportedParsers = [];
$normalizedOutput = $this->normalizeClassParameter($output);
@ -337,9 +335,7 @@ class ApiDocExtractor
}
if (count($annotation->getResponseMap()) > 0) {
foreach ($annotation->getResponseMap() as $code => $modelName) {
if ('200' === (string) $code && isset($modelName['type']) && isset($modelName['model'])) {
/*
* Model was already parsed as the default `output` for this ApiDoc.
@ -349,8 +345,8 @@ class ApiDocExtractor
$normalizedModel = $this->normalizeClassParameter($modelName);
$parameters = array();
$supportedParsers = array();
$parameters = [];
$supportedParsers = [];
foreach ($this->getParsers($normalizedModel) as $parser) {
if ($parser->supports($normalizedModel)) {
$supportedParsers[] = $parser;
@ -370,9 +366,7 @@ class ApiDocExtractor
$parameters = $this->generateHumanReadableTypes($parameters);
$annotation->setResponseForStatusCode($parameters, $normalizedModel, $code);
}
}
return $annotation;
@ -380,18 +374,18 @@ class ApiDocExtractor
protected function normalizeClassParameter($input)
{
$defaults = array(
$defaults = [
'class' => '',
'groups' => array(),
'options' => array(),
);
'groups' => [],
'options' => [],
];
// normalize strings
if (is_string($input)) {
$input = array('class' => $input);
$input = ['class' => $input];
}
$collectionData = array();
$collectionData = [];
/*
* Match array<Fully\Qualified\ClassName> as alias; "as alias" optional.
@ -431,6 +425,7 @@ class ApiDocExtractor
*
* @param array $p1 The pre-existing parameters array.
* @param array $p2 The newly-returned parameters array.
*
* @return array The resulting, merged array.
*/
protected function mergeParameters($p1, $p2)
@ -438,8 +433,7 @@ class ApiDocExtractor
$params = $p1;
foreach ($p2 as $propname => $propvalue) {
if ($propvalue === null) {
if (null === $propvalue) {
unset($params[$propname]);
continue;
}
@ -456,20 +450,20 @@ class ApiDocExtractor
} else {
$v1[$name] = $value;
}
} elseif (!is_null($value)) {
if (in_array($name, array('required', 'readonly'))) {
} elseif (null !== $value) {
if (in_array($name, ['required', 'readonly'])) {
$v1[$name] = $v1[$name] || $value;
} elseif (in_array($name, array('requirement'))) {
} elseif (in_array($name, ['requirement'])) {
if (isset($v1[$name])) {
$v1[$name] .= ', ' . $value;
} else {
$v1[$name] = $value;
}
} elseif ($name == 'default') {
} elseif ('default' == $name) {
if (isset($v1[$name])) {
$v1[$name] = isset($value) ? $value : $v1[$name];
$v1[$name] = $value ?? $v1[$name];
} else {
$v1[$name] = isset($value) ? $value : null;
$v1[$name] = $value ?? null;
}
} else {
$v1[$name] = $value;
@ -488,11 +482,9 @@ class ApiDocExtractor
* Parses annotations for a given method, and adds new information to the given ApiDoc
* annotation. Useful to extract information from the FOSRestBundle annotations.
*
* @param ApiDoc $annotation
* @param Route $route
* @param ReflectionMethod $method
*/
protected function parseAnnotations(ApiDoc $annotation, Route $route, \ReflectionMethod $method)
protected function parseAnnotations(ApiDoc $annotation, Route $route, \ReflectionMethod $method): void
{
$annots = $this->reader->getMethodAnnotations($method);
foreach ($this->handlers as $handler) {
@ -504,6 +496,7 @@ class ApiDocExtractor
* Set parent class to children
*
* @param array $array The source array.
*
* @return array The updated array.
*/
protected function setParentClasses($array)
@ -521,6 +514,7 @@ class ApiDocExtractor
}
}
}
return $array;
}
@ -528,6 +522,7 @@ class ApiDocExtractor
* Clears the temporary 'class' parameter from the parameters array before it is returned.
*
* @param array $array The source array.
*
* @return array The cleared array.
*/
protected function clearClasses($array)
@ -545,13 +540,11 @@ class ApiDocExtractor
/**
* Populates the `dataType` properties in the parameter array if empty. Recurses through children when necessary.
*
* @param array $array
* @return array
*/
protected function generateHumanReadableTypes(array $array)
{
foreach ($array as $name => $info) {
if (empty($info['dataType']) && array_key_exists('subType', $info)) {
$array[$name]['dataType'] = $this->generateHumanReadableType($info['actualType'], $info['subType']);
}
@ -569,12 +562,12 @@ class ApiDocExtractor
*
* @param string $actualType
* @param string $subType
*
* @return string
*/
protected function generateHumanReadableType($actualType, $subType)
{
if ($actualType == DataTypes::MODEL) {
if (DataTypes::MODEL == $actualType) {
if ($subType && class_exists($subType)) {
$parts = explode('\\', $subType);
@ -584,8 +577,7 @@ class ApiDocExtractor
return sprintf('object (%s)', $subType);
}
if ($actualType == DataTypes::COLLECTION) {
if (DataTypes::COLLECTION == $actualType) {
if (DataTypes::isPrimitive($subType)) {
return sprintf('array of %ss', $subType);
}
@ -605,9 +597,9 @@ class ApiDocExtractor
private function getParsers(array $parameters)
{
if (isset($parameters['parsers'])) {
$parsers = array();
$parsers = [];
foreach ($this->parsers as $parser) {
if (in_array(get_class($parser), $parameters['parsers'])) {
if (in_array($parser::class, $parameters['parsers'])) {
$parsers[] = $parser;
}
}

View File

@ -12,8 +12,8 @@
namespace Nelmio\ApiDocBundle\Extractor;
use Doctrine\Common\Annotations\Reader;
use Nelmio\ApiDocBundle\Util\DocCommentExtractor;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Nelmio\ApiDocBundle\Util\DocCommentExtractor;
use Symfony\Component\Config\ConfigCache;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Routing\RouterInterface;
@ -29,7 +29,6 @@ class CachingApiDocExtractor extends ApiDocExtractor
* @param HandlerInterface[] $handlers
* @param AnnotationsProviderInterface[] $annotationsProviders
* @param string[] $excludeSections
* @param string $cacheFile
* @param bool|false $debug
*/
public function __construct(
@ -40,13 +39,14 @@ class CachingApiDocExtractor extends ApiDocExtractor
array $annotationsProviders,
array $excludeSections,
private string $cacheFile,
private bool $debug = false
private bool $debug = false,
) {
parent::__construct($router, $reader, $commentExtractor, $handlers, $annotationsProviders, $excludeSections);
}
/**
* @param string $view View name
*
* @return array|mixed
*/
public function all($view = ApiDoc::DEFAULT_VIEW)
@ -54,7 +54,7 @@ class CachingApiDocExtractor extends ApiDocExtractor
$cache = $this->getViewCache($view);
if (!$cache->isFresh()) {
$resources = array();
$resources = [];
foreach ($this->getRoutes() as $route) {
if (null !== ($method = $this->getReflectionMethod($route->getDefault('_controller')))
&& null !== ($annotation = $this->reader->getMethodAnnotation($method, self::ANNOTATION_CLASS))) {
@ -84,11 +84,11 @@ class CachingApiDocExtractor extends ApiDocExtractor
/**
* @param string $view
*
* @return ConfigCache
*/
private function getViewCache($view)
{
return new ConfigCache($this->cacheFile . '.' . $view, $this->debug);
}
}

View File

@ -11,60 +11,56 @@
namespace Nelmio\ApiDocBundle\Extractor\Handler;
use FOS\RestBundle\Controller\Annotations\QueryParam;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Extractor\HandlerInterface;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Routing\Route;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Regex;
use FOS\RestBundle\Controller\Annotations\RequestParam;
use FOS\RestBundle\Controller\Annotations\QueryParam;
class FosRestHandler implements HandlerInterface
{
/**
* @inheritdoc
*/
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method)
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method): void
{
foreach ($annotations as $annot) {
if ($annot instanceof RequestParam) {
$requirements = $this->handleRequirements($annot->requirements);
$data = array(
'required' => $annot->strict && $annot->nullable === false && $annot->default === null,
$data = [
'required' => $annot->strict && false === $annot->nullable && null === $annot->default,
'dataType' => $requirements . ((property_exists($annot, 'map') ? $annot->map : $annot->array) ? '[]' : ''),
'actualType' => $this->inferType($requirements),
'subType' => null,
'description' => $annot->description,
'readonly' => false
);
if ($annot->strict === false) {
'readonly' => false,
];
if (false === $annot->strict) {
$data['default'] = $annot->default;
}
$annotation->addParameter($annot->name, $data);
} elseif ($annot instanceof QueryParam) {
if ($annot->strict && $annot->nullable === false && $annot->default === null) {
$annotation->addRequirement($annot->name, array(
if ($annot->strict && false === $annot->nullable && null === $annot->default) {
$annotation->addRequirement($annot->name, [
'requirement' => $this->handleRequirements($annot->requirements) . ((property_exists($annot, 'map') ? $annot->map : $annot->array) ? '[]' : ''),
'dataType' => '',
'description' => $annot->description,
));
} elseif ($annot->default !== null) {
$annotation->addFilter($annot->name, array(
]);
} elseif (null !== $annot->default) {
$annotation->addFilter($annot->name, [
'requirement' => $this->handleRequirements($annot->requirements) . ((property_exists($annot, 'map') ? $annot->map : $annot->array) ? '[]' : ''),
'description' => $annot->description,
'default' => $annot->default,
));
} elseif ($annot->requirements !== null) {
$annotation->addFilter($annot->name, array(
]);
} elseif (null !== $annot->requirements) {
$annotation->addFilter($annot->name, [
'requirement' => $this->handleRequirements($annot->requirements) . ((property_exists($annot, 'map') ? $annot->map : $annot->array) ? '[]' : ''),
'description' => $annot->description,
));
]);
} else {
$annotation->addFilter($annot->name, array(
$annotation->addFilter($annot->name, [
'description' => $annot->description,
));
]);
}
}
}
@ -73,7 +69,6 @@ class FosRestHandler implements HandlerInterface
/**
* Handle FOSRestBundle requirements in order to return a string.
*
* @param mixed $requirements
* @return string
*/
private function handleRequirements($requirements)
@ -82,7 +77,7 @@ class FosRestHandler implements HandlerInterface
if ($requirements instanceof Regex) {
return $requirements->getHtmlPattern();
}
$class = get_class($requirements);
$class = $requirements::class;
return substr($class, strrpos($class, '\\') + 1);
}
@ -92,19 +87,16 @@ class FosRestHandler implements HandlerInterface
}
if (is_array($requirements) && array_key_exists(0, $requirements)) {
$output = array();
$output = [];
foreach ($requirements as $req) {
if (is_object($req) && $req instanceof Constraint) {
if ($req instanceof Regex) {
$output[] = $req->getHtmlPattern();
} else {
$class = get_class($req);
$class = $req::class;
$output[] = substr($class, strrpos($class, '\\') + 1);
}
}
if (is_array($req)) {

View File

@ -12,14 +12,14 @@
namespace Nelmio\ApiDocBundle\Extractor\Handler;
use JMS\SecurityExtraBundle\Annotation\PreAuthorize;
use Nelmio\ApiDocBundle\Extractor\HandlerInterface;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Routing\Route;
use JMS\SecurityExtraBundle\Annotation\Secure;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Nelmio\ApiDocBundle\Extractor\HandlerInterface;
use Symfony\Component\Routing\Route;
class JmsSecurityExtraHandler implements HandlerInterface
{
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method)
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method): void
{
foreach ($annotations as $annot) {
if ($annot instanceof PreAuthorize) {

View File

@ -11,10 +11,10 @@
namespace Nelmio\ApiDocBundle\Extractor\Handler;
use Nelmio\ApiDocBundle\Extractor\HandlerInterface;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\Routing\Route;
use Nelmio\ApiDocBundle\Extractor\HandlerInterface;
use Nelmio\ApiDocBundle\Util\DocCommentExtractor;
use Symfony\Component\Routing\Route;
class PhpDocHandler implements HandlerInterface
{
@ -28,7 +28,7 @@ class PhpDocHandler implements HandlerInterface
$this->commentExtractor = $commentExtractor;
}
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method)
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method): void
{
// description
if (null === $annotation->getDescription()) {
@ -48,11 +48,11 @@ class PhpDocHandler implements HandlerInterface
$requirements = $annotation->getRequirements();
foreach ($route->getRequirements() as $name => $value) {
if (!isset($requirements[$name]) && '_method' !== $name && '_scheme' !== $name) {
$requirements[$name] = array(
$requirements[$name] = [
'requirement' => $value,
'dataType' => '',
'description' => '',
);
];
}
if ('_scheme' === $name) {
@ -65,7 +65,7 @@ class PhpDocHandler implements HandlerInterface
$annotation->setHttps(in_array('https', $route->getSchemes()));
}
$paramDocs = array();
$paramDocs = [];
foreach (explode("\n", $this->commentExtractor->getDocComment($method)) as $line) {
if (preg_match('{^@param (.+)}', trim($line), $matches)) {
$paramDocs[] = $matches[1];
@ -73,8 +73,8 @@ class PhpDocHandler implements HandlerInterface
if (preg_match('{^@deprecated}', trim($line))) {
$annotation->setDeprecated(true);
}
if (preg_match('{^@link (.+)}', trim($line), $matches)) {
$annotation->setLink($matches[1]);
if (preg_match('{^@(link|see) (.+)}', trim($line), $matches)) {
$annotation->setLink($matches[2]);
}
}
@ -86,7 +86,7 @@ class PhpDocHandler implements HandlerInterface
$annotationRequirements = $annotation->getrequirements();
if (!isset($annotationRequirements[$var]['dataType'])) {
$requirements[$var]['dataType'] = isset($matches[1]) ? $matches[1] : '';
$requirements[$var]['dataType'] = $matches[1] ?? '';
}
if (!isset($annotationRequirements[$var]['description'])) {
@ -103,7 +103,7 @@ class PhpDocHandler implements HandlerInterface
}
if (!isset($requirements[$var]) && false === $found) {
$requirements[$var] = array('requirement' => '', 'dataType' => '', 'description' => '');
$requirements[$var] = ['requirement' => '', 'dataType' => '', 'description' => ''];
}
}

View File

@ -18,11 +18,6 @@ interface HandlerInterface
{
/**
* Parse route parameters in order to populate ApiDoc.
*
* @param \Nelmio\ApiDocBundle\Annotation\ApiDoc $annotation
* @param array $annotations
* @param \Symfony\Component\Routing\Route $route
* @param \ReflectionMethod $method
*/
public function handle(ApiDoc $annotation, array $annotations, Route $route, \ReflectionMethod $method);
}

View File

@ -21,45 +21,31 @@ use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class DescriptionFormTypeExtension extends AbstractTypeExtension
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->setAttribute('description', $options['description']);
}
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
public function buildView(FormView $view, FormInterface $form, array $options): void
{
$view->vars['description'] = $options['description'];
}
/**
* {@inheritdoc}
*
* @deprecated Remove it when bumping requirements to Symfony 2.7+
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolverInterface $resolver): void
{
$this->configureOptions($resolver);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(array(
$resolver->setDefaults([
'description' => '',
));
]);
}
/**
* {@inheritdoc}
*/
public static function getExtendedTypes(): iterable
{
return [LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\FormType')];

View File

@ -18,14 +18,11 @@ abstract class AbstractFormatter implements FormatterInterface
{
protected $version;
public function setVersion($version)
public function setVersion($version): void
{
$this->version = $version;
}
/**
* {@inheritdoc}
*/
public function formatOne(ApiDoc $annotation)
{
return $this->renderOne(
@ -33,9 +30,6 @@ abstract class AbstractFormatter implements FormatterInterface
);
}
/**
* {@inheritdoc}
*/
public function format(array $collection)
{
return $this->render(
@ -46,7 +40,6 @@ abstract class AbstractFormatter implements FormatterInterface
/**
* Format a single array of data
*
* @param array $data
* @return string|array
*/
abstract protected function renderOne(array $data);
@ -54,7 +47,6 @@ abstract class AbstractFormatter implements FormatterInterface
/**
* Format a set of resource sections.
*
* @param array $collection
* @return string|array
*/
abstract protected function render(array $collection);
@ -62,10 +54,10 @@ abstract class AbstractFormatter implements FormatterInterface
/**
* Check that the versions range includes current version
*
* @access protected
* @param string $fromVersion (default: null)
* @param string $toVersion (default: null)
* @return boolean
*
* @return bool
*/
protected function rangeIncludesVersion($fromVersion = null, $toVersion = null)
{
@ -78,6 +70,7 @@ abstract class AbstractFormatter implements FormatterInterface
if ($toVersion && version_compare($toVersion, $this->version, '<')) {
return false;
}
return true;
}
@ -86,26 +79,25 @@ abstract class AbstractFormatter implements FormatterInterface
* names to strings which contain the nested property names, for example:
* `user[group][name]`
*
*
* @param array $data
* @param string $parentName
* @param boolean $ignoreNestedReadOnly
* @param bool $ignoreNestedReadOnly
*
* @return array
*/
protected function compressNestedParameters(array $data, $parentName = null, $ignoreNestedReadOnly = false)
{
$newParams = array();
$newParams = [];
foreach ($data as $name => $info) {
if ($this->version && !$this->rangeIncludesVersion(
isset($info['sinceVersion']) ? $info['sinceVersion'] : null,
isset($info['untilVersion']) ? $info['untilVersion'] : null
$info['sinceVersion'] ?? null,
$info['untilVersion'] ?? null
)) {
continue;
}
$newName = $this->getNewName($name, $info, $parentName);
$newParams[$newName] = array(
$newParams[$newName] = [
'dataType' => $info['dataType'],
'readonly' => array_key_exists('readonly', $info) ? $info['readonly'] : null,
'required' => $info['required'],
@ -118,7 +110,7 @@ abstract class AbstractFormatter implements FormatterInterface
'subType' => array_key_exists('subType', $info) ? $info['subType'] : null,
'parentClass' => array_key_exists('parentClass', $info) ? $info['parentClass'] : null,
'field' => array_key_exists('field', $info) ? $info['field'] : null,
);
];
if (isset($info['children']) && (!$info['readonly'] || !$ignoreNestedReadOnly)) {
foreach ($this->compressNestedParameters($info['children'], $newName, $ignoreNestedReadOnly) as $nestedItemName => $nestedItemData) {
@ -137,24 +129,26 @@ abstract class AbstractFormatter implements FormatterInterface
* @param string $name
* @param array $data
* @param string $parentName
*
* @return string
*/
protected function getNewName($name, $data, $parentName = null)
{
$array = '';
$newName = ($parentName) ? sprintf("%s[%s]", $parentName, $name) : $name;
$newName = ($parentName) ? sprintf('%s[%s]', $parentName, $name) : $name;
if (isset($data['actualType']) && $data['actualType'] == DataTypes::COLLECTION
&& isset($data['subType']) && $data['subType'] !== null
if (isset($data['actualType']) && DataTypes::COLLECTION == $data['actualType']
&& isset($data['subType']) && null !== $data['subType']
) {
$array = '[]';
}
return sprintf("%s%s", $newName, $array);
return sprintf('%s%s', $newName, $array);
}
/**
* @param array $annotation
*
* @return array
*/
protected function processAnnotation($annotation)
@ -180,16 +174,17 @@ abstract class AbstractFormatter implements FormatterInterface
/**
* @param array[ApiDoc] $collection
*
* @return array
*/
protected function processCollection(array $collection)
{
$array = array();
$array = [];
foreach ($collection as $coll) {
$array[$coll['annotation']->getSection()][$coll['resource']][] = $coll['annotation']->toArray();
}
$processedCollection = array();
$processedCollection = [];
foreach ($array as $section => $resources) {
foreach ($resources as $path => $annotations) {
foreach ($annotations as $annotation) {

View File

@ -19,6 +19,7 @@ interface FormatterInterface
* Format a collection of documentation data.
*
* @param array[ApiDoc] $collection
*
* @return string|array
*/
public function format(array $collection);

View File

@ -37,7 +37,7 @@ class HtmlFormatter extends AbstractFormatter
protected $engine;
/**
* @var boolean
* @var bool
*/
private $enableSandbox;
@ -77,14 +77,11 @@ class HtmlFormatter extends AbstractFormatter
private $motdTemplate;
/**
* @var boolean
* @var bool
*/
private $defaultSectionsOpened;
/**
* @param array $authentication
*/
public function setAuthentication(array $authentication = null)
public function setAuthentication(?array $authentication = null): void
{
$this->authentication = $authentication;
}
@ -92,7 +89,7 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param string $apiName
*/
public function setApiName($apiName)
public function setApiName($apiName): void
{
$this->apiName = $apiName;
}
@ -100,15 +97,15 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param string $endpoint
*/
public function setEndpoint($endpoint)
public function setEndpoint($endpoint): void
{
$this->endpoint = $endpoint;
}
/**
* @param boolean $enableSandbox
* @param bool $enableSandbox
*/
public function setEnableSandbox($enableSandbox)
public function setEnableSandbox($enableSandbox): void
{
$this->enableSandbox = $enableSandbox;
}
@ -116,7 +113,7 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param EngineInterface|TwigEnvironment $engine
*/
public function setTemplatingEngine($engine)
public function setTemplatingEngine($engine): void
{
$this->engine = $engine;
}
@ -124,15 +121,12 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param string $acceptType
*/
public function setAcceptType($acceptType)
public function setAcceptType($acceptType): void
{
$this->acceptType = $acceptType;
}
/**
* @param array $bodyFormats
*/
public function setBodyFormats(array $bodyFormats)
public function setBodyFormats(array $bodyFormats): void
{
$this->bodyFormats = $bodyFormats;
}
@ -140,7 +134,7 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param string $defaultBodyFormat
*/
public function setDefaultBodyFormat($defaultBodyFormat)
public function setDefaultBodyFormat($defaultBodyFormat): void
{
$this->defaultBodyFormat = $defaultBodyFormat;
}
@ -148,15 +142,12 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param string $method
*/
public function setRequestFormatMethod($method)
public function setRequestFormatMethod($method): void
{
$this->requestFormatMethod = $method;
}
/**
* @param array $formats
*/
public function setRequestFormats(array $formats)
public function setRequestFormats(array $formats): void
{
$this->requestFormats = $formats;
}
@ -164,7 +155,7 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param string $format
*/
public function setDefaultRequestFormat($format)
public function setDefaultRequestFormat($format): void
{
$this->defaultRequestFormat = $format;
}
@ -172,7 +163,7 @@ class HtmlFormatter extends AbstractFormatter
/**
* @param string $motdTemplate
*/
public function setMotdTemplate($motdTemplate)
public function setMotdTemplate($motdTemplate): void
{
$this->motdTemplate = $motdTemplate;
}
@ -186,36 +177,30 @@ class HtmlFormatter extends AbstractFormatter
}
/**
* @param boolean $defaultSectionsOpened
* @param bool $defaultSectionsOpened
*/
public function setDefaultSectionsOpened($defaultSectionsOpened)
public function setDefaultSectionsOpened($defaultSectionsOpened): void
{
$this->defaultSectionsOpened = $defaultSectionsOpened;
}
/**
* {@inheritdoc}
*/
protected function renderOne(array $data)
{
return $this->engine->render('@NelmioApiDoc/resource.html.twig', array_merge(
array(
[
'data' => $data,
'displayContent' => true,
),
],
$this->getGlobalVars()
));
}
/**
* {@inheritdoc}
*/
protected function render(array $collection)
{
return $this->engine->render('@NelmioApiDoc/resources.html.twig', array_merge(
array(
[
'resources' => $collection,
),
],
$this->getGlobalVars()
));
}
@ -225,7 +210,7 @@ class HtmlFormatter extends AbstractFormatter
*/
private function getGlobalVars()
{
return array(
return [
'apiName' => $this->apiName,
'authentication' => $this->authentication,
'endpoint' => $this->endpoint,
@ -241,6 +226,6 @@ class HtmlFormatter extends AbstractFormatter
'js' => file_get_contents(__DIR__ . '/../Resources/public/js/all.js'),
'motdTemplate' => $this->motdTemplate,
'defaultSectionsOpened' => $this->defaultSectionsOpened,
);
];
}
}

View File

@ -13,15 +13,12 @@ namespace Nelmio\ApiDocBundle\Formatter;
class MarkdownFormatter extends AbstractFormatter
{
/**
* {@inheritdoc}
*/
protected function renderOne(array $data)
{
$markdown = sprintf("### `%s` %s ###\n", $data['method'], $data['uri']);
if (isset($data['deprecated']) && false !== $data['deprecated']) {
$markdown .= "### This method is deprecated ###";
$markdown .= '### This method is deprecated ###';
$markdown .= "\n\n";
}
@ -107,7 +104,7 @@ class MarkdownFormatter extends AbstractFormatter
}
if (null !== $parameter['sinceVersion'] || null !== $parameter['untilVersion']) {
$markdown .= " * versions: ";
$markdown .= ' * versions: ';
if ($parameter['sinceVersion']) {
$markdown .= '>=' . $parameter['sinceVersion'];
}
@ -127,9 +124,6 @@ class MarkdownFormatter extends AbstractFormatter
return $markdown;
}
/**
* {@inheritdoc}
*/
protected function render(array $collection)
{
$markdown = '';

View File

@ -22,7 +22,7 @@ use Symfony\Component\HttpFoundation\Request;
class RequestAwareSwaggerFormatter implements FormatterInterface
{
/**
* @var \Symfony\Component\HttpFoundation\Request
* @var Request
*/
protected $request;
@ -31,10 +31,6 @@ class RequestAwareSwaggerFormatter implements FormatterInterface
*/
protected $formatter;
/**
* @param Request $request
* @param SwaggerFormatter $formatter
*/
public function __construct(Request $request, SwaggerFormatter $formatter)
{
$this->request = $request;
@ -44,16 +40,17 @@ class RequestAwareSwaggerFormatter implements FormatterInterface
/**
* Format a collection of documentation data.
*
* @param array $collection
* @param null $resource
*
* @internal param $array [ApiDoc] $collection
*
* @return string|array
*/
public function format(array $collection, $resource = null)
{
$result = $this->formatter->format($collection, $resource);
if ($resource !== null) {
if (null !== $resource) {
$result['basePath'] = $this->request->getBaseUrl() . $result['basePath'];
}

View File

@ -15,20 +15,14 @@ use Nelmio\ApiDocBundle\Annotation\ApiDoc;
class SimpleFormatter extends AbstractFormatter
{
/**
* {@inheritdoc}
*/
public function formatOne(ApiDoc $annotation)
{
return $annotation->toArray();
}
/**
* {@inheritdoc}
*/
public function format(array $collection)
{
$array = array();
$array = [];
foreach ($collection as $coll) {
$annotationArray = $coll['annotation']->toArray();
unset($annotationArray['parsedResponseMap']);
@ -39,17 +33,11 @@ class SimpleFormatter extends AbstractFormatter
return $array;
}
/**
* {@inheritdoc}
*/
protected function renderOne(array $data)
protected function renderOne(array $data): void
{
}
/**
* {@inheritdoc}
*/
protected function render(array $collection)
protected function render(array $collection): void
{
}
}

View File

@ -32,9 +32,9 @@ class SwaggerFormatter implements FormatterInterface
protected $swaggerVersion;
protected $info = array();
protected $info = [];
protected $typeMap = array(
protected $typeMap = [
DataTypes::INTEGER => 'integer',
DataTypes::FLOAT => 'number',
DataTypes::STRING => 'string',
@ -42,18 +42,18 @@ class SwaggerFormatter implements FormatterInterface
DataTypes::FILE => 'string',
DataTypes::DATE => 'string',
DataTypes::DATETIME => 'string',
);
];
protected $formatMap = array(
protected $formatMap = [
DataTypes::INTEGER => 'int32',
DataTypes::FLOAT => 'float',
DataTypes::FILE => 'byte',
DataTypes::DATE => 'date',
DataTypes::DATETIME => 'date-time',
);
];
/**
* @var \Nelmio\ApiDocBundle\Swagger\ModelRegistry
* @var ModelRegistry
*/
protected $modelRegistry;
@ -65,9 +65,9 @@ class SwaggerFormatter implements FormatterInterface
/**
* @var array
*/
protected $authConfig = null;
protected $authConfig;
public function setAuthenticationConfig(array $config)
public function setAuthenticationConfig(array $config): void
{
$this->authConfig = $config;
}
@ -78,12 +78,13 @@ class SwaggerFormatter implements FormatterInterface
* If resource is provided, an API declaration for that resource is produced. Otherwise, a resource listing is returned.
*
* @param array|ApiDoc[] $collection
* @param null|string $resource
* @param string|null $resource
*
* @return string|array
*/
public function format(array $collection, $resource = null)
{
if ($resource === null) {
if (null === $resource) {
return $this->produceResourceListing($collection);
} else {
return $this->produceApiDeclaration($collection, $resource);
@ -93,23 +94,21 @@ class SwaggerFormatter implements FormatterInterface
/**
* Formats the collection into Swagger-compliant output.
*
* @param array $collection
* @return array
*/
public function produceResourceListing(array $collection)
{
$resourceList = array(
$resourceList = [
'swaggerVersion' => (string) $this->swaggerVersion,
'apis' => array(),
'apis' => [],
'apiVersion' => (string) $this->apiVersion,
'info' => $this->getInfo(),
'authorizations' => $this->getAuthorizations(),
);
];
$apis = &$resourceList['apis'];
foreach ($collection as $item) {
/** @var $apiDoc ApiDoc */
$apiDoc = $item['annotation'];
$resource = $item['resource'];
@ -121,11 +120,10 @@ class SwaggerFormatter implements FormatterInterface
$subPath = $this->stripBasePath($resource);
$normalizedName = $this->normalizeResourcePath($subPath);
$apis[] = array(
$apis[] = [
'path' => '/' . $normalizedName,
'description' => $apiDoc->getResourceDescription(),
);
];
}
return $resourceList;
@ -133,23 +131,23 @@ class SwaggerFormatter implements FormatterInterface
protected function getAuthorizations()
{
$auth = array();
$auth = [];
if ($this->authConfig === null) {
if (null === $this->authConfig) {
return $auth;
}
$config = $this->authConfig;
if ($config['delivery'] === 'http') {
if ('http' === $config['delivery']) {
return $auth;
}
$auth['apiKey'] = array(
$auth['apiKey'] = [
'type' => 'apiKey',
'passAs' => $config['delivery'],
'keyname' => $config['name'],
);
];
return $auth;
}
@ -167,9 +165,10 @@ class SwaggerFormatter implements FormatterInterface
*
* @param ApiDoc $annotation
* return string|array
*
* @throws \BadMethodCallException
*/
public function formatOne(ApiDoc $annotation)
public function formatOne(ApiDoc $annotation): void
{
throw new \BadMethodCallException(sprintf('%s does not support formatting a single ApiDoc only.', __CLASS__));
}
@ -177,41 +176,39 @@ class SwaggerFormatter implements FormatterInterface
/**
* Formats collection to produce a Swagger-compliant API declaration for the given resource.
*
* @param array $collection
* @param string $resource
*
* @return array
*/
protected function produceApiDeclaration(array $collection, $resource)
{
$apiDeclaration = array(
$apiDeclaration = [
'swaggerVersion' => (string) $this->swaggerVersion,
'apiVersion' => (string) $this->apiVersion,
'basePath' => $this->basePath,
'resourcePath' => $resource,
'apis' => array(),
'models' => array(),
'produces' => array(),
'consumes' => array(),
'apis' => [],
'models' => [],
'produces' => [],
'consumes' => [],
'authorizations' => $this->getAuthorizations(),
);
];
$main = null;
$apiBag = array();
$apiBag = [];
foreach ($collection as $item) {
/** @var $apiDoc ApiDoc */
$apiDoc = $item['annotation'];
$itemResource = $this->stripBasePath($item['resource']);
$input = $apiDoc->getInput();
if (!is_array($input)) {
$input = array(
$input = [
'class' => $input,
'paramType' => 'form',
);
];
} elseif (empty($input['paramType'])) {
$input['paramType'] = 'form';
}
@ -229,21 +226,21 @@ class SwaggerFormatter implements FormatterInterface
$path = $this->stripBasePath($route->getPath());
if (!isset($apiBag[$path])) {
$apiBag[$path] = array();
$apiBag[$path] = [];
}
$parameters = array();
$responseMessages = array();
$parameters = [];
$responseMessages = [];
foreach ($compiled->getPathVariables() as $paramValue) {
$parameter = array(
$parameter = [
'paramType' => 'path',
'name' => $paramValue,
'type' => 'string',
'required' => true,
);
];
if ($paramValue === '_format' && false != ($req = $route->getRequirement('_format'))) {
if ('_format' === $paramValue && false != ($req = $route->getRequirement('_format'))) {
$parameter['enum'] = explode('|', $req);
}
@ -262,10 +259,9 @@ class SwaggerFormatter implements FormatterInterface
$responseMap = $apiDoc->getParsedResponseMap();
$statusMessages = isset($data['statusCodes']) ? $data['statusCodes'] : array();
$statusMessages = $data['statusCodes'] ?? [];
foreach ($responseMap as $statusCode => $prop) {
if (isset($statusMessages[$statusCode])) {
$message = is_array($statusMessages[$statusCode]) ? implode('; ', $statusMessages[$statusCode]) : $statusCode[$statusCode];
} else {
@ -274,8 +270,7 @@ class SwaggerFormatter implements FormatterInterface
$className = !empty($prop['type']['form_errors']) ? $prop['type']['class'] . '.ErrorResponse' : $prop['type']['class'];
if (isset($prop['type']['collection']) && $prop['type']['collection'] === true) {
if (isset($prop['type']['collection']) && true === $prop['type']['collection']) {
/*
* Without alias: Fully\Qualified\Class\Name[]
* With alias: Fully\Qualified\Class\Name[alias]
@ -286,8 +281,8 @@ class SwaggerFormatter implements FormatterInterface
$collId =
$this->registerModel(
$newName,
array(
$alias => array(
[
$alias => [
'dataType' => null,
'subType' => $className,
'actualType' => DataTypes::COLLECTION,
@ -296,22 +291,21 @@ class SwaggerFormatter implements FormatterInterface
'description' => null,
'default' => null,
'children' => $prop['model'][$alias]['children'],
)
),
],
],
''
);
$responseModel = array(
$responseModel = [
'code' => $statusCode,
'message' => $message,
'responseModel' => $collId
);
'responseModel' => $collId,
];
} else {
$responseModel = array(
$responseModel = [
'code' => $statusCode,
'message' => $message,
'responseModel' => $this->registerModel($className, $prop['model'], ''),
);
];
}
$responseMessages[$statusCode] = $responseModel;
}
@ -319,24 +313,24 @@ class SwaggerFormatter implements FormatterInterface
$unmappedMessages = array_diff(array_keys($statusMessages), array_keys($responseMessages));
foreach ($unmappedMessages as $code) {
$responseMessages[$code] = array(
$responseMessages[$code] = [
'code' => $code,
'message' => is_array($statusMessages[$code]) ? implode('; ', $statusMessages[$code]) : $statusMessages[$code],
);
];
}
$type = isset($responseMessages[200]['responseModel']) ? $responseMessages[200]['responseModel'] : null;
$type = $responseMessages[200]['responseModel'] ?? null;
foreach ($apiDoc->getRoute()->getMethods() as $method) {
$operation = array(
$operation = [
'method' => $method,
'summary' => $apiDoc->getDescription(),
'nickname' => $this->generateNickname($method, $itemResource),
'parameters' => $parameters,
'responseMessages' => array_values($responseMessages),
);
];
if ($type !== null) {
if (null !== $type) {
$operation['type'] = $type;
}
@ -347,10 +341,10 @@ class SwaggerFormatter implements FormatterInterface
$apiDeclaration['resourcePath'] = $resource;
foreach ($apiBag as $path => $operations) {
$apiDeclaration['apis'][] = array(
$apiDeclaration['apis'][] = [
'path' => $path,
'operations' => $operations,
);
];
}
$apiDeclaration['models'] = $this->modelRegistry->getModels();
@ -362,7 +356,6 @@ class SwaggerFormatter implements FormatterInterface
/**
* Slugify a URL path. Trims out path parameters wrapped in curly brackets.
*
* @param $path
* @return string
*/
protected function normalizeResourcePath($path)
@ -374,10 +367,7 @@ class SwaggerFormatter implements FormatterInterface
return $path;
}
/**
* @param $path
*/
public function setBasePath($path)
public function setBasePath($path): void
{
$this->basePath = $path;
}
@ -385,46 +375,39 @@ class SwaggerFormatter implements FormatterInterface
/**
* Formats query parameters to Swagger-compliant form.
*
* @param array $input
* @return array
*/
protected function deriveQueryParameters(array $input)
{
$parameters = array();
$parameters = [];
foreach ($input as $name => $prop) {
if (!isset($prop['dataType'])) {
$prop['dataType'] = 'string';
}
$parameters[] = array(
$parameters[] = [
'paramType' => 'query',
'name' => $name,
'type' => isset($this->typeMap[$prop['dataType']]) ? $this->typeMap[$prop['dataType']] : 'string',
'description' => isset($prop['description']) ? $prop['description'] : null,
);
'type' => $this->typeMap[$prop['dataType']] ?? 'string',
'description' => $prop['description'] ?? null,
];
}
return $parameters;
}
/**
* Builds a Swagger-compliant parameter list from the provided parameter array. Models are built when necessary.
*
* @param array $input
* @param array $models
*
* @param string $paramType
*
* @return array
*/
protected function deriveParameters(array $input, $paramType = 'form')
{
$parameters = array();
$parameters = [];
foreach ($input as $name => $prop) {
$type = null;
$format = null;
$ref = null;
@ -450,27 +433,27 @@ class SwaggerFormatter implements FormatterInterface
$ref =
$this->registerModel(
$prop['subType'],
isset($prop['children']) ? $prop['children'] : null,
$prop['children'] ?? null,
$prop['description'] ?: $prop['dataType']
);
break;
case DataTypes::COLLECTION:
$type = 'array';
if ($prop['subType'] === null) {
$items = array('type' => 'string');
if (null === $prop['subType']) {
$items = ['type' => 'string'];
} elseif (isset($this->typeMap[$prop['subType']])) {
$items = array('type' => $this->typeMap[$prop['subType']]);
$items = ['type' => $this->typeMap[$prop['subType']]];
} else {
$ref =
$this->registerModel(
$prop['subType'],
isset($prop['children']) ? $prop['children'] : null,
$prop['children'] ?? null,
$prop['description'] ?: $prop['dataType']
);
$items = array(
$items = [
'$ref' => $ref,
);
];
}
break;
}
@ -485,10 +468,10 @@ class SwaggerFormatter implements FormatterInterface
continue;
}
$parameter = array(
$parameter = [
'paramType' => $paramType,
'name' => $name,
);
];
if (null !== $type) {
$parameter['type'] = $type;
@ -528,47 +511,32 @@ class SwaggerFormatter implements FormatterInterface
/**
* Registers a model into the model array. Returns a unique identifier for the model to be used in `$ref` properties.
*
* @param $className
* @param array $parameters
* @param string $description
*
* @internal param $models
* @return mixed
*/
public function registerModel($className, array $parameters = null, $description = '')
public function registerModel($className, ?array $parameters = null, $description = '')
{
return $this->modelRegistry->register($className, $parameters, $description);
}
/**
* @param mixed $swaggerVersion
*/
public function setSwaggerVersion($swaggerVersion)
public function setSwaggerVersion($swaggerVersion): void
{
$this->swaggerVersion = $swaggerVersion;
}
/**
* @param mixed $apiVersion
*/
public function setApiVersion($apiVersion)
public function setApiVersion($apiVersion): void
{
$this->apiVersion = $apiVersion;
}
/**
* @param mixed $info
*/
public function setInfo($info)
public function setInfo($info): void
{
$this->info = $info;
}
/**
* Strips the base path from a URL path.
*
* @param $basePath
* @return mixed
*/
protected function stripBasePath($basePath)
{
@ -585,8 +553,6 @@ class SwaggerFormatter implements FormatterInterface
/**
* Generate nicknames based on support HTTP methods and the resource name.
*
* @param $method
* @param $resource
* @return string
*/
protected function generateNickname($method, $resource)

View File

@ -3,17 +3,17 @@
namespace Nelmio\ApiDocBundle;
use Nelmio\ApiDocBundle\DependencyInjection\AnnotationsProviderCompilerPass;
use Nelmio\ApiDocBundle\DependencyInjection\ExtractorHandlerCompilerPass;
use Nelmio\ApiDocBundle\DependencyInjection\FormInfoParserCompilerPass;
use Nelmio\ApiDocBundle\DependencyInjection\SwaggerConfigCompilerPass;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Nelmio\ApiDocBundle\DependencyInjection\LoadExtractorParsersPass;
use Nelmio\ApiDocBundle\DependencyInjection\RegisterExtractorParsersPass;
use Nelmio\ApiDocBundle\DependencyInjection\ExtractorHandlerCompilerPass;
use Nelmio\ApiDocBundle\DependencyInjection\SwaggerConfigCompilerPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class NelmioApiDocBundle extends Bundle
{
public function build(ContainerBuilder $container)
public function build(ContainerBuilder $container): void
{
parent::build($container);

View File

@ -20,29 +20,26 @@ use Nelmio\ApiDocBundle\DataTypes;
*/
class CollectionParser implements ParserInterface, PostParserInterface
{
/**
* Return true/false whether this class supports parsing the given class.
*
* @param array $item containing the following fields: class, groups. Of which groups is optional
*
* @return boolean
* @return bool
*/
public function supports(array $item)
{
return isset($item['collection']) && $item['collection'] === true;
return isset($item['collection']) && true === $item['collection'];
}
/**
* This doesn't parse anything at this stage.
*
* @param array $item
*
* @return array
*/
public function parse(array $item)
{
return array();
return [];
}
/**
@ -59,9 +56,9 @@ class CollectionParser implements ParserInterface, PostParserInterface
$parameters[$name] = null;
}
$collectionName = isset($item['collectionName']) ? $item['collectionName'] : '';
$collectionName = $item['collectionName'] ?? '';
$parameters[$collectionName] = array(
$parameters[$collectionName] = [
'dataType' => null, // Delegates to ApiDocExtractor#generateHumanReadableTypes
'subType' => $item['class'],
'actualType' => DataTypes::COLLECTION,
@ -70,7 +67,7 @@ class CollectionParser implements ParserInterface, PostParserInterface
'default' => true,
'description' => '',
'children' => $origParameters,
);
];
return $parameters;
}

View File

@ -25,16 +25,16 @@ use PropertyInfo\Type;
*/
class DunglasApiParser implements ParserInterface
{
const IN_PREFIX = 'dunglas_api_in';
const OUT_PREFIX = 'dunglas_api_out';
const IRI = 'IRI';
public const IN_PREFIX = 'dunglas_api_in';
public const OUT_PREFIX = 'dunglas_api_out';
public const IRI = 'IRI';
private static $typeMap = array(
private static $typeMap = [
'int' => DataTypes::INTEGER,
'bool' => DataTypes::BOOLEAN,
'string' => DataTypes::STRING,
'float' => DataTypes::FLOAT,
);
];
/**
* @var ResourceCollectionInterface
@ -47,15 +47,12 @@ class DunglasApiParser implements ParserInterface
public function __construct(
ResourceCollectionInterface $resourceCollection,
ClassMetadataFactoryInterface $classMetadataFactory
ClassMetadataFactoryInterface $classMetadataFactory,
) {
$this->resourceCollection = $resourceCollection;
$this->classMetadataFactory = $classMetadataFactory;
}
/**
* {@inheritdoc}
*/
public function supports(array $item)
{
$data = explode(':', $item['class'], 2);
@ -66,12 +63,9 @@ class DunglasApiParser implements ParserInterface
return false;
}
/**
* {@inheritdoc}
*/
public function parse(array $item)
{
list($io, $entityClass) = explode(':', $item['class'], 2);
[$io, $entityClass] = explode(':', $item['class'], 2);
$resource = $this->resourceCollection->getResourceForEntity($entityClass);
return $this->parseClass($resource, $entityClass, $io);
@ -80,14 +74,13 @@ class DunglasApiParser implements ParserInterface
/**
* Parses a class.
*
* @param ResourceInterface $resource
* @param string $entityClass
* @param string $io
* @param string[] $visited
*
* @return array
*/
private function parseClass(ResourceInterface $resource, $entityClass, $io, array $visited = array())
private function parseClass(ResourceInterface $resource, $entityClass, $io, array $visited = [])
{
$visited[] = $entityClass;
@ -98,11 +91,11 @@ class DunglasApiParser implements ParserInterface
$resource->getValidationGroups()
);
$data = array();
$data = [];
foreach ($classMetadata->getAttributes() as $attributeMetadata) {
if (
(!$attributeMetadata->isIdentifier() && $attributeMetadata->isReadable() && self::OUT_PREFIX === $io) ||
($attributeMetadata->isWritable() && self::IN_PREFIX === $io)
(!$attributeMetadata->isIdentifier() && $attributeMetadata->isReadable() && self::OUT_PREFIX === $io)
|| ($attributeMetadata->isWritable() && self::IN_PREFIX === $io)
) {
$data[$attributeMetadata->getName()] = $this->parseAttribute($resource, $attributeMetadata, $io, null, $visited);
}
@ -114,22 +107,19 @@ class DunglasApiParser implements ParserInterface
/**
* Parses an attribute.
*
* @param ResourceInterface $resource
* @param AttributeMetadataInterface $attributeMetadata
* @param string $io
* @param Type|null $type
* @param string[] $visited
*
* @return array
*/
private function parseAttribute(ResourceInterface $resource, AttributeMetadataInterface $attributeMetadata, $io, Type $type = null, array $visited = array())
private function parseAttribute(ResourceInterface $resource, AttributeMetadataInterface $attributeMetadata, $io, ?Type $type = null, array $visited = [])
{
$data = array(
$data = [
'dataType' => null,
'required' => $attributeMetadata->isRequired(),
'description' => $attributeMetadata->getDescription(),
'readonly' => !$attributeMetadata->isWritable(),
);
];
if (null == $type) {
if (!isset($attributeMetadata->getTypes()[0])) {
@ -174,8 +164,8 @@ class DunglasApiParser implements ParserInterface
}
if (
(self::OUT_PREFIX === $io && $attributeMetadata->isNormalizationLink()) ||
(self::IN_PREFIX === $io && $attributeMetadata->isDenormalizationLink())
(self::OUT_PREFIX === $io && $attributeMetadata->isNormalizationLink())
|| (self::IN_PREFIX === $io && $attributeMetadata->isDenormalizationLink())
) {
$data['dataType'] = self::IRI;
$data['actualType'] = DataTypes::STRING;

View File

@ -23,16 +23,16 @@ class FormErrorsParser implements ParserInterface, PostParserInterface
*
* @param array $item containing the following fields: class, groups. Of which groups is optional
*
* @return boolean
* @return bool
*/
public function supports(array $item)
{
return isset($item['form_errors']) && $item['form_errors'] === true;
return isset($item['form_errors']) && true === $item['form_errors'];
}
public function parse(array $item)
{
return array();
return [];
}
/**
@ -41,9 +41,6 @@ class FormErrorsParser implements ParserInterface, PostParserInterface
* - message: "Validation failed"
* - errors: contains the original parameters, but all types are changed to array of strings (array of errors for each field)
*
* @param array $item
* @param array $parameters
*
* @return array
*/
public function postParse(array $item, array $parameters)
@ -54,7 +51,7 @@ class FormErrorsParser implements ParserInterface, PostParserInterface
$params[$name] = null;
}
$params['status_code'] = array(
$params['status_code'] = [
'dataType' => 'integer',
'actualType' => DataTypes::INTEGER,
'subType' => null,
@ -62,18 +59,18 @@ class FormErrorsParser implements ParserInterface, PostParserInterface
'description' => 'The status code',
'readonly' => true,
'default' => 400,
);
];
$params['message'] = array(
$params['message'] = [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
'required' => false,
'description' => 'The error message',
'default' => 'Validation failed.',
);
];
$params['errors'] = array(
$params['errors'] = [
'dataType' => 'errors',
'actualType' => DataTypes::MODEL,
'subType' => sprintf('%s.FormErrors', $item['class']),
@ -81,42 +78,41 @@ class FormErrorsParser implements ParserInterface, PostParserInterface
'description' => 'Errors',
'readonly' => true,
'children' => $this->doPostParse($parameters),
);
];
return $params;
}
protected function doPostParse(array $parameters, $attachFieldErrors = true, array $propertyPath = array())
protected function doPostParse(array $parameters, $attachFieldErrors = true, array $propertyPath = [])
{
$data = array();
$data = [];
foreach ($parameters as $name => $parameter) {
$data[$name] = array(
$data[$name] = [
'dataType' => 'parameter errors',
'actualType' => DataTypes::MODEL,
'subType' => 'FieldErrors',
'required' => false,
'description' => 'Errors on the parameter',
'readonly' => true,
'children' => array(
'errors' => array(
'children' => [
'errors' => [
'dataType' => 'array of errors',
'actualType' => DataTypes::COLLECTION,
'subType' => 'string',
'required' => false,
'dscription' => '',
'readonly' => true,
),
),
);
],
],
];
if ($parameter['actualType'] === DataTypes::MODEL) {
if (DataTypes::MODEL === $parameter['actualType']) {
$propertyPath[] = $name;
$data[$name]['subType'] = sprintf('%s.FieldErrors[%s]', $parameter['subType'], implode('.', $propertyPath));
$data[$name]['children'] = $this->doPostParse($parameter['children'], $attachFieldErrors, $propertyPath);
} else {
if ($attachFieldErrors === false) {
if (false === $attachFieldErrors) {
unset($data[$name]['children']);
}
$attachFieldErrors = false;

View File

@ -1,6 +1,5 @@
<?php
namespace Nelmio\ApiDocBundle\Parser;
use Symfony\Component\Form\FormConfigInterface;

View File

@ -13,9 +13,9 @@ namespace Nelmio\ApiDocBundle\Parser;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Util\LegacyFormHelper;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\Exception\FormException;
use Symfony\Component\Form\Exception\InvalidArgumentException;
use Symfony\Component\Form\ChoiceList\ChoiceListInterface;
use Symfony\Component\Form\Extension\Core\View\ChoiceView;
use Symfony\Component\Form\FormConfigInterface;
use Symfony\Component\Form\FormFactoryInterface;
@ -28,12 +28,12 @@ use Symfony\Contracts\Translation\TranslatorInterface;
class FormTypeParser implements ParserInterface
{
/**
* @var \Symfony\Component\Form\FormFactoryInterface
* @var FormFactoryInterface
*/
protected $formFactory;
/**
* @var \Symfony\Component\Form\FormRegistry
* @var \Symfony\Component\Form\FormRegistry
*/
protected $formRegistry;
@ -43,7 +43,7 @@ class FormTypeParser implements ParserInterface
protected $translator;
/**
* @var boolean
* @var bool
*/
protected $entityToChoice;
@ -57,7 +57,7 @@ class FormTypeParser implements ParserInterface
*
* @deprecated since 2.12, to be removed in 3.0. Use $extendedMapTypes instead.
*/
protected $mapTypes = array(
protected $mapTypes = [
'text' => DataTypes::STRING,
'date' => DataTypes::DATE,
'datetime' => DataTypes::DATETIME,
@ -69,64 +69,61 @@ class FormTypeParser implements ParserInterface
'country' => DataTypes::STRING,
'choice' => DataTypes::ENUM,
'file' => DataTypes::FILE,
);
];
/**
* @var array
*/
protected $extendedMapTypes = array(
DataTypes::STRING => array(
protected $extendedMapTypes = [
DataTypes::STRING => [
'text',
'Symfony\Component\Form\Extension\Core\Type\TextType',
'textarea',
'Symfony\Component\Form\Extension\Core\Type\TextareaType',
'country',
'Symfony\Component\Form\Extension\Core\Type\CountryType',
),
DataTypes::DATE => array(
],
DataTypes::DATE => [
'date',
'Symfony\Component\Form\Extension\Core\Type\DateType',
),
DataTypes::DATETIME => array(
],
DataTypes::DATETIME => [
'datetime',
'Symfony\Component\Form\Extension\Core\Type\DatetimeType',
),
DataTypes::BOOLEAN => array(
],
DataTypes::BOOLEAN => [
'checkbox',
'Symfony\Component\Form\Extension\Core\Type\CheckboxType',
),
DataTypes::TIME => array(
],
DataTypes::TIME => [
'time',
'Symfony\Component\Form\Extension\Core\Type\TimeType',
),
DataTypes::FLOAT => array(
],
DataTypes::FLOAT => [
'number',
'Symfony\Component\Form\Extension\Core\Type\NumberType',
),
DataTypes::INTEGER => array(
],
DataTypes::INTEGER => [
'integer',
'Symfony\Component\Form\Extension\Core\Type\IntegerType',
),
DataTypes::ENUM => array(
],
DataTypes::ENUM => [
'choice',
'Symfony\Component\Form\Extension\Core\Type\ChoiceType',
),
DataTypes::FILE => array(
],
DataTypes::FILE => [
'file',
'Symfony\Component\Form\Extension\Core\Type\FileType',
),
);
],
];
public function __construct(FormFactoryInterface $formFactory, TranslatorInterface $translator, $entityToChoice)
{
$this->formFactory = $formFactory;
$this->translator = $translator;
$this->entityToChoice = (boolean) $entityToChoice;
$this->entityToChoice = (bool) $entityToChoice;
}
/**
* {@inheritdoc}
*/
public function supports(array $item)
{
$className = $item['class'];
@ -145,9 +142,6 @@ class FormTypeParser implements ParserInterface
return false;
}
/**
* {@inheritdoc}
*/
public function parse(array $item)
{
$type = $item['class'];
@ -180,7 +174,7 @@ class FormTypeParser implements ParserInterface
return $this->parseForm($form);
}
$subType = is_object($type) ? get_class($type) : $type;
$subType = is_object($type) ? $type::class : $type;
if ($subType && class_exists($subType)) {
$parts = explode('\\', $subType);
@ -189,8 +183,8 @@ class FormTypeParser implements ParserInterface
$dataType = sprintf('object (%s)', $subType);
}
return array(
$name => array(
return [
$name => [
'required' => true,
'readonly' => false,
'description' => '',
@ -199,13 +193,13 @@ class FormTypeParser implements ParserInterface
'actualType' => DataTypes::MODEL,
'subType' => $subType,
'children' => $this->parseForm($form),
),
);
],
];
}
public function addFormInfoParser(FormInfoParser $formInfoParser)
public function addFormInfoParser(FormInfoParser $formInfoParser): void
{
$class = get_class($formInfoParser);
$class = $formInfoParser::class;
if (isset($this->formInfoParsers[$class])) {
throw new \InvalidArgumentException($class . ' already added');
}
@ -236,7 +230,7 @@ class FormTypeParser implements ParserInterface
private function parseForm($form)
{
$parameters = array();
$parameters = [];
$domain = $form->getConfig()->getOption('translation_domain');
foreach ($form as $name => $child) {
@ -289,10 +283,10 @@ class FormTypeParser implements ParserInterface
// Embedded form collection
// BC sf < 2.8
$embbededType = $config->hasOption('entry_type') ? $config->getOption('entry_type') : $config->getOption('type');
$subForm = $this->formFactory->create($embbededType, null, $config->getOption('entry_options', array()));
$subForm = $this->formFactory->create($embbededType, null, $config->getOption('entry_options', []));
$children = $this->parseForm($subForm);
$actualType = DataTypes::COLLECTION;
$subType = is_object($embbededType) ? get_class($embbededType) : $embbededType;
$subType = is_object($embbededType) ? $embbededType::class : $embbededType;
if ($subType && class_exists($subType)) {
$parts = explode('\\', $subType);
@ -314,14 +308,13 @@ class FormTypeParser implements ParserInterface
*/
$addDefault = false;
try {
if (isset($subForm)) {
unset($subForm);
}
if (LegacyFormHelper::hasBCBreaks()) {
try {
$subForm = $this->formFactory->create(get_class($type), null, $options);
$subForm = $this->formFactory->create($type::class, null, $options);
} catch (\Exception $e) {
}
}
@ -334,11 +327,11 @@ class FormTypeParser implements ParserInterface
if (!empty($subParameters)) {
$children = $subParameters;
$config = $subForm->getConfig();
$subType = get_class($type);
$subType = $type::class;
$parts = explode('\\', $subType);
$bestType = sprintf('object (%s)', end($parts));
$parameters[$name] = array(
$parameters[$name] = [
'dataType' => $bestType,
'actualType' => DataTypes::MODEL,
'default' => null,
@ -347,8 +340,7 @@ class FormTypeParser implements ParserInterface
'description' => $this->getFormDescription($config, $domain),
'readonly' => $config->getDisabled(),
'children' => $children,
);
];
} else {
$addDefault = true;
}
@ -357,14 +349,14 @@ class FormTypeParser implements ParserInterface
}
if ($addDefault) {
$parameters[$name] = array(
$parameters[$name] = [
'dataType' => 'string',
'actualType' => 'string',
'default' => $config->getData(),
'required' => $config->getRequired(),
'description' => $this->getFormDescription($config, $domain),
'readonly' => $config->getDisabled(),
);
];
}
continue;
@ -372,7 +364,7 @@ class FormTypeParser implements ParserInterface
}
}
$parameters[$name] = array(
$parameters[$name] = [
'dataType' => $bestType,
'actualType' => $actualType,
'subType' => $subType,
@ -380,7 +372,7 @@ class FormTypeParser implements ParserInterface
'required' => $config->getRequired(),
'description' => $this->getFormDescription($config, $domain),
'readonly' => $config->getDisabled(),
);
];
if (null !== $children) {
$parameters[$name]['children'] = $children;
@ -413,19 +405,18 @@ class FormTypeParser implements ParserInterface
array_values($choices) :
array_keys($choices);
sort($choices);
$parameters[$name]['format'] = '[' . join('|', $choices) . ']';
$parameters[$name]['format'] = '[' . implode('|', $choices) . ']';
} elseif ($choiceList = $config->getOption('choice_list')) {
$choiceListType = $config->getType();
$choiceListName = method_exists($choiceListType, 'getBlockPrefix') ?
$choiceListType->getBlockPrefix() : $choiceListType->getName();
if (('entity' === $choiceListName && false === $this->entityToChoice)) {
$choices = array();
if ('entity' === $choiceListName && false === $this->entityToChoice) {
$choices = [];
} else {
// TODO: fixme
// does not work since: https://github.com/symfony/symfony/commit/03efce1b568379eac21d880e427090e43035f505
$choices = array();
$choices = [];
}
if (is_array($choices) && count($choices)) {
@ -463,7 +454,7 @@ class FormTypeParser implements ParserInterface
return $refl->newInstance();
}
private function createForm($type, $data = null, array $options = array())
private function createForm($type, $data = null, array $options = [])
{
try {
return $this->formFactory->create($type, null, $options);
@ -479,8 +470,8 @@ class FormTypeParser implements ParserInterface
private function handleChoiceListValues(ChoiceListInterface $choiceList)
{
$choices = array();
foreach (array($choiceList->getPreferredViews(), $choiceList->getRemainingViews()) as $viewList) {
$choices = [];
foreach ([$choiceList->getPreferredViews(), $choiceList->getRemainingViews()] as $viewList) {
$choices = array_merge($choices, $this->handleChoiceViewsHierarchy($viewList));
}
@ -489,7 +480,7 @@ class FormTypeParser implements ParserInterface
private function handleChoiceViewsHierarchy(array $choiceViews)
{
$choices = array();
$choices = [];
foreach ($choiceViews as $item) {
if ($item instanceof ChoiceView) {
$choices[$item->value] = $item->label;
@ -504,10 +495,9 @@ class FormTypeParser implements ParserInterface
private function getFormDescription($config, $domain = null)
{
$description = ($config->getOption('description'))
? $config->getOption('description')
: $config->getOption('label');
?: $config->getOption('label');
if ($description != null) {
if (null != $description) {
return $this->translator->trans($description, [], $domain);
}

View File

@ -12,13 +12,13 @@
namespace Nelmio\ApiDocBundle\Parser;
use JMS\Serializer\Exclusion\GroupsExclusionStrategy;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Metadata\VirtualPropertyMetadata;
use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
use JMS\Serializer\SerializationContext;
use Metadata\MetadataFactoryInterface;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Util\DocCommentExtractor;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Metadata\VirtualPropertyMetadata;
use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
/**
* Uses the JMS metadata factory to extract input/output model information
@ -26,7 +26,7 @@ use JMS\Serializer\Naming\PropertyNamingStrategyInterface;
class JmsMetadataParser implements ParserInterface, PostParserInterface
{
/**
* @var \Metadata\MetadataFactoryInterface
* @var MetadataFactoryInterface
*/
private $factory;
@ -36,11 +36,11 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
private $namingStrategy;
/**
* @var \Nelmio\ApiDocBundle\Util\DocCommentExtractor
* @var DocCommentExtractor
*/
private $commentExtractor;
private $typeMap = array(
private $typeMap = [
'integer' => DataTypes::INTEGER,
'boolean' => DataTypes::BOOLEAN,
'string' => DataTypes::STRING,
@ -48,23 +48,21 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
'double' => DataTypes::FLOAT,
'array' => DataTypes::COLLECTION,
'DateTime' => DataTypes::DATETIME,
);
];
/**
* Constructor, requires JMS Metadata factory
*/
public function __construct(
MetadataFactoryInterface $factory,
PropertyNamingStrategyInterface $namingStrategy,
DocCommentExtractor $commentExtractor
DocCommentExtractor $commentExtractor,
) {
$this->factory = $factory;
$this->namingStrategy = $namingStrategy;
$this->commentExtractor = $commentExtractor;
}
/**
* {@inheritdoc}
*/
public function supports(array $input)
{
$className = $input['class'];
@ -79,15 +77,12 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
return false;
}
/**
* {@inheritdoc}
*/
public function parse(array $input)
{
$className = $input['class'];
$groups = $input['groups'];
$result = $this->doParse($className, array(), $groups);
$result = $this->doParse($className, [], $groups);
if (!isset($input['name']) || empty($input['name'])) {
return $result;
@ -100,8 +95,8 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
$dataType = sprintf('object (%s)', $className);
}
return array(
$input['name'] => array(
return [
$input['name'] => [
'required' => null,
'readonly' => null,
'default' => null,
@ -109,8 +104,8 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
'actualType' => DataTypes::MODEL,
'subType' => $dataType,
'children' => $result,
),
);
],
];
}
/**
@ -119,27 +114,29 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
* @param string $className Class to get all metadata for
* @param array $visited Classes we've already visited to prevent infinite recursion.
* @param array $groups Serialization groups to include.
*
* @return array metadata for given class
*
* @throws \InvalidArgumentException
*/
protected function doParse($className, $visited = array(), array $groups = array())
protected function doParse($className, $visited = [], array $groups = [])
{
$meta = $this->factory->getMetadataForClass($className);
if (null === $meta) {
throw new \InvalidArgumentException(sprintf("No metadata found for class %s", $className));
throw new \InvalidArgumentException(sprintf('No metadata found for class %s', $className));
}
$exclusionStrategies = array();
$exclusionStrategies = [];
if ($groups) {
$exclusionStrategies[] = new GroupsExclusionStrategy($groups);
}
$params = array();
$params = [];
$reflection = new \ReflectionClass($className);
$defaultProperties = array_map(function ($default) {
if (is_array($default) && count($default) === 0) {
if (is_array($default) && 0 === count($default)) {
return null;
}
@ -148,7 +145,7 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
// iterate over property metadata
foreach ($meta->propertyMetadata as $item) {
if (!is_null($item->type)) {
if (null !== $item->type) {
$name = $this->namingStrategy->translateName($item);
$dataType = $this->processDataType($item);
@ -161,20 +158,20 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
}
if (!$dataType['inline']) {
$params[$name] = array(
$params[$name] = [
'dataType' => $dataType['normalized'],
'actualType' => $dataType['actualType'],
'subType' => $dataType['class'],
'required' => false,
'default' => isset($defaultProperties[$item->name]) ? $defaultProperties[$item->name] : null,
'default' => $defaultProperties[$item->name] ?? null,
// TODO: can't think of a good way to specify this one, JMS doesn't have a setting for this
'description' => $this->getDescription($item),
'readonly' => $item->readOnly,
'sinceVersion' => $item->sinceVersion,
'untilVersion' => $item->untilVersion,
);
];
if (!is_null($dataType['class']) && false === $dataType['primitive']) {
if (null !== $dataType['class'] && false === $dataType['primitive']) {
$params[$name]['class'] = $dataType['class'];
}
}
@ -210,7 +207,6 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
* Figure out a normalized data type (for documentation), and get a
* nested class name, if available.
*
* @param PropertyMetadata $item
* @return array
*/
protected function processDataType(PropertyMetadata $item)
@ -218,89 +214,84 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
// check for a type inside something that could be treated as an array
if ($nestedType = $this->getNestedTypeInArray($item)) {
if ($this->isPrimitive($nestedType)) {
return array(
'normalized' => sprintf("array of %ss", $nestedType),
return [
'normalized' => sprintf('array of %ss', $nestedType),
'actualType' => DataTypes::COLLECTION,
'class' => $this->typeMap[$nestedType],
'primitive' => true,
'inline' => false,
);
];
}
$exp = explode("\\", $nestedType);
$exp = explode('\\', $nestedType);
return array(
'normalized' => sprintf("array of objects (%s)", end($exp)),
return [
'normalized' => sprintf('array of objects (%s)', end($exp)),
'actualType' => DataTypes::COLLECTION,
'class' => $nestedType,
'primitive' => false,
'inline' => false,
);
];
}
$type = $item->type['name'];
// could be basic type
if ($this->isPrimitive($type)) {
return array(
return [
'normalized' => $type,
'actualType' => $this->typeMap[$type],
'class' => null,
'primitive' => true,
'inline' => false,
);
];
}
// we can use type property also for custom handlers, then we don't have here real class name
if (!$type || !class_exists($type)) {
return array(
'normalized' => sprintf("custom handler result for (%s)", $type),
return [
'normalized' => sprintf('custom handler result for (%s)', $type),
'class' => $type,
'actualType' => DataTypes::MODEL,
'primitive' => false,
'inline' => false,
);
];
}
// if we got this far, it's a general class name
$exp = explode("\\", $type);
$exp = explode('\\', $type);
return array(
'normalized' => sprintf("object (%s)", end($exp)),
return [
'normalized' => sprintf('object (%s)', end($exp)),
'class' => $type,
'actualType' => DataTypes::MODEL,
'primitive' => false,
'inline' => $item->inline,
);
];
}
protected function isPrimitive($type)
{
return in_array($type, array('boolean', 'integer', 'string', 'float', 'double', 'array', 'DateTime'));
return in_array($type, ['boolean', 'integer', 'string', 'float', 'double', 'array', 'DateTime']);
}
/**
* {@inheritDoc}
*/
public function postParse(array $input, array $parameters)
{
return $this->doPostParse($parameters, array(), isset($input['groups']) ? $input['groups'] : array());
return $this->doPostParse($parameters, [], $input['groups'] ?? []);
}
/**
* Recursive `doPostParse` to avoid circular post parsing.
*
* @param array $parameters
* @param array $visited
* @return array
*/
protected function doPostParse (array $parameters, array $visited = array(), array $groups = array())
protected function doPostParse(array $parameters, array $visited = [], array $groups = [])
{
foreach ($parameters as $param => $data) {
if (isset($data['class']) && isset($data['children']) && !in_array($data['class'], $visited)) {
$visited[] = $data['class'];
$input = array('class' => $data['class'], 'groups' => isset($data['groups']) ? $data['groups'] : array());
$input = ['class' => $data['class'], 'groups' => $data['groups'] ?? []];
$parameters[$param]['children'] = array_merge(
$parameters[$param]['children'], $this->doPostParse($parameters[$param]['children'], $visited, $groups)
);
@ -317,12 +308,11 @@ class JmsMetadataParser implements ParserInterface, PostParserInterface
* Check the various ways JMS describes values in arrays, and
* get the value type in the array
*
* @param PropertyMetadata $item
* @return string|null
*/
protected function getNestedTypeInArray(PropertyMetadata $item)
{
if (isset($item->type['name']) && in_array($item->type['name'], array('array', 'ArrayCollection'))) {
if (isset($item->type['name']) && in_array($item->type['name'], ['array', 'ArrayCollection'])) {
if (isset($item->type['params'][1]['name'])) {
// E.g. array<string, MyNamespaceMyObject>
return $item->type['params'][1]['name'];

View File

@ -7,9 +7,6 @@ namespace Nelmio\ApiDocBundle\Parser;
class JsonSerializableParser implements ParserInterface
{
/**
* {@inheritdoc}
*/
public function supports(array $item)
{
if (!is_subclass_of($item['class'], 'JsonSerializable')) {
@ -28,9 +25,6 @@ class JsonSerializableParser implements ParserInterface
return true;
}
/**
* {@inheritdoc}
*/
public function parse(array $input)
{
/** @var \JsonSerializable $obj */
@ -40,7 +34,7 @@ class JsonSerializableParser implements ParserInterface
$parsed = $this->getItemMetaData($encoded);
if (isset($input['name']) && !empty($input['name'])) {
$output = array();
$output = [];
$output[$input['name']] = $parsed;
return $output;
@ -53,22 +47,22 @@ class JsonSerializableParser implements ParserInterface
{
$type = gettype($item);
$meta = array(
'dataType' => $type == 'NULL' ? null : $type,
$meta = [
'dataType' => 'NULL' == $type ? null : $type,
'actualType' => $type,
'subType' => null,
'required' => null,
'description' => null,
'readonly' => null,
'default' => is_scalar($item) ? $item : null,
);
];
if ($type == 'object' && $item instanceof \JsonSerializable) {
if ('object' == $type && $item instanceof \JsonSerializable) {
$meta = $this->getItemMetaData($item->jsonSerialize());
$meta['class'] = get_class($item);
} elseif (($type == 'object' && $item instanceof \stdClass) || ($type == 'array' && !$this->isSequential($item))) {
$meta['class'] = $item::class;
} elseif (('object' == $type && $item instanceof \stdClass) || ('array' == $type && !$this->isSequential($item))) {
$meta['dataType'] = 'object';
$meta['children'] = array();
$meta['children'] = [];
foreach ($item as $key => $value) {
$meta['children'][$key] = $this->getItemMetaData($value);
}
@ -81,12 +75,11 @@ class JsonSerializableParser implements ParserInterface
* Check for numeric sequential keys, just like the json encoder does
* Credit: http://stackoverflow.com/a/25206156/859027
*
* @param array $arr
* @return bool
*/
private function isSequential(array $arr)
{
for ($i = count($arr) - 1; $i >= 0; $i--) {
for ($i = count($arr) - 1; $i >= 0; --$i) {
if (!isset($arr[$i]) && !array_key_exists($i, $arr)) {
return false;
}

View File

@ -20,7 +20,8 @@ interface ParserInterface
* Return true/false whether this class supports parsing the given class.
*
* @param array $item containing the following fields: class, groups. Of which groups is optional
* @return boolean
*
* @return bool
*/
public function supports(array $item);
@ -37,6 +38,7 @@ interface ParserInterface
* it is represented by an object
*
* @param array $item The string type of input to parse.
*
* @return array
*/
public function parse(array $item);

View File

@ -32,6 +32,7 @@ interface PostParserInterface
*
* @param string $item The string type of input to parse.
* @param array $parameters The previously-parsed parameters array.
*
* @return array
*/
public function postParse(array $item, array $parameters);

View File

@ -12,11 +12,11 @@
namespace Nelmio\ApiDocBundle\Parser;
use Nelmio\ApiDocBundle\DataTypes;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Mapping\Factory\MetadataFactoryInterface;
use Symfony\Component\Validator\MetadataFactoryInterface as LegacyMetadataFactoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Type;
/**
* Uses the Symfony Validation component to extract information about API objects.
@ -24,11 +24,11 @@ use Symfony\Component\Validator\Constraints\Type;
class ValidationParser implements ParserInterface, PostParserInterface
{
/**
* @var \Symfony\Component\Validator\MetadataFactoryInterface
* @var LegacyMetadataFactoryInterface
*/
protected $factory;
protected $typeMap = array(
protected $typeMap = [
'integer' => DataTypes::INTEGER,
'int' => DataTypes::INTEGER,
'scalar' => DataTypes::STRING,
@ -41,7 +41,7 @@ class ValidationParser implements ParserInterface, PostParserInterface
'object' => DataTypes::MODEL,
'array' => DataTypes::COLLECTION,
'DateTime' => DataTypes::DATETIME,
);
];
/**
* Requires a validation MetadataFactory.
@ -56,9 +56,6 @@ class ValidationParser implements ParserInterface, PostParserInterface
$this->factory = $factory;
}
/**
* {@inheritdoc}
*/
public function supports(array $input)
{
$className = $input['class'];
@ -66,19 +63,16 @@ class ValidationParser implements ParserInterface, PostParserInterface
return $this->factory->hasMetadataFor($className);
}
/**
* {@inheritdoc}
*/
public function parse(array $input)
{
$className = $input['class'];
$groups = array();
if (isset($input["groups"]) && $input["groups"]) {
$groups = $input["groups"];
$groups = [];
if (isset($input['groups']) && $input['groups']) {
$groups = $input['groups'];
}
$parsed = $this->doParse($className, array(), $groups);
$parsed = $this->doParse($className, [], $groups);
if (!isset($input['name']) || empty($input['name'])) {
return $parsed;
@ -91,8 +85,8 @@ class ValidationParser implements ParserInterface, PostParserInterface
$dataType = sprintf('object (%s)', $className);
}
return array(
$input['name'] => array(
return [
$input['name'] => [
'dataType' => $dataType,
'actualType' => DataTypes::MODEL,
'class' => $className,
@ -101,21 +95,18 @@ class ValidationParser implements ParserInterface, PostParserInterface
'readonly' => null,
'children' => $parsed,
'default' => null,
),
);
],
];
}
/**
* Recursively parse constraints.
*
* @param $className
* @param array $visited
* @param array $groups
* @return array
*/
protected function doParse($className, array $visited, array $groups = array())
protected function doParse($className, array $visited, array $groups = [])
{
$params = array();
$params = [];
$classdata = $this->factory->getMetadataFor($className);
$properties = $classdata->getConstrainedProperties();
@ -123,9 +114,9 @@ class ValidationParser implements ParserInterface, PostParserInterface
$defaults = $refl->getDefaultProperties();
foreach ($properties as $property) {
$vparams = array();
$vparams = [];
$vparams['default'] = isset($defaults[$property]) ? $defaults[$property] : null;
$vparams['default'] = $defaults[$property] ?? null;
$pds = $classdata->getPropertyMetadata($property);
foreach ($pds as $propdata) {
@ -137,10 +128,10 @@ class ValidationParser implements ParserInterface, PostParserInterface
}
if (isset($vparams['format'])) {
$vparams['format'] = join(', ', array_unique($vparams['format']));
$vparams['format'] = implode(', ', array_unique($vparams['format']));
}
foreach (array('dataType', 'readonly', 'required', 'subType') as $reqprop) {
foreach (['dataType', 'readonly', 'required', 'subType'] as $reqprop) {
if (!isset($vparams[$reqprop])) {
$vparams[$reqprop] = null;
}
@ -152,7 +143,7 @@ class ValidationParser implements ParserInterface, PostParserInterface
$vparams['children'] = $this->doParse($vparams['class'], $visited, $groups);
}
$vparams['actualType'] = isset($vparams['actualType']) ? $vparams['actualType'] : DataTypes::STRING;
$vparams['actualType'] = $vparams['actualType'] ?? DataTypes::STRING;
$params[$property] = $vparams;
}
@ -160,19 +151,16 @@ class ValidationParser implements ParserInterface, PostParserInterface
return $params;
}
/**
* {@inheritDoc}
*/
public function postParse(array $input, array $parameters)
{
$groups = [];
if (isset($input["groups"]) && $input["groups"]) {
$groups = $input["groups"];
if (isset($input['groups']) && $input['groups']) {
$groups = $input['groups'];
}
foreach ($parameters as $param => $data) {
if (isset($data['class']) && isset($data['children'])) {
$input = array('class' => $data['class'], "groups" => $groups);
$input = ['class' => $data['class'], 'groups' => $groups];
$parameters[$param]['children'] = array_merge(
$parameters[$param]['children'], $this->postParse($input, $parameters[$param]['children'])
);
@ -200,17 +188,17 @@ class ValidationParser implements ParserInterface, PostParserInterface
* @param Constraint $constraint The constraint metadata object.
* @param array $vparams The existing validation parameters.
* @param array $groups Validation groups.
*
* @return mixed The parsed list of validation parameters.
*/
protected function parseConstraint(
Constraint $constraint,
$vparams,
$className,
&$visited = array(),
array $groups = array()
)
{
$class = substr(get_class($constraint), strlen('Symfony\\Component\\Validator\\Constraints\\'));
&$visited = [],
array $groups = [],
) {
$class = substr($constraint::class, strlen('Symfony\\Component\\Validator\\Constraints\\'));
$vparams['actualType'] = DataTypes::STRING;
$vparams['subType'] = null;
@ -231,6 +219,7 @@ class ValidationParser implements ParserInterface, PostParserInterface
switch ($class) {
case 'NotBlank':
$vparams['format'][] = '{not blank}';
// no break
case 'NotNull':
$vparams['required'] = true;
break;
@ -262,40 +251,40 @@ class ValidationParser implements ParserInterface, PostParserInterface
$vparams['actualType'] = DataTypes::TIME;
break;
case 'Range':
$messages = array();
$messages = [];
if (isset($constraint->min)) {
$messages[] = ">={$constraint->min}";
}
if (isset($constraint->max)) {
$messages[] = "<={$constraint->max}";
}
$vparams['format'][] = '{range: {' . join(', ', $messages) . '}}';
$vparams['format'][] = '{range: {' . implode(', ', $messages) . '}}';
break;
case 'Length':
$messages = array();
$messages = [];
if (isset($constraint->min)) {
$messages[] = "min: {$constraint->min}";
}
if (isset($constraint->max)) {
$messages[] = "max: {$constraint->max}";
}
$vparams['format'][] = '{length: {' . join(', ', $messages) . '}}';
$vparams['format'][] = '{length: {' . implode(', ', $messages) . '}}';
break;
case 'Choice':
$choices = $this->getChoices($constraint, $className);
sort($choices);
$format = '[' . join('|', $choices) . ']';
$format = '[' . implode('|', $choices) . ']';
if ($constraint->multiple) {
$vparams['actualType'] = DataTypes::COLLECTION;
$vparams['subType'] = DataTypes::ENUM;
$messages = array();
$messages = [];
if (isset($constraint->min)) {
$messages[] = "min: {$constraint->min} ";
}
if (isset($constraint->max)) {
$messages[] = "max: {$constraint->max} ";
}
$vparams['format'][] = '{' . join ('', $messages) . 'choice of ' . $format . '}';
$vparams['format'][] = '{' . implode('', $messages) . 'choice of ' . $format . '}';
} else {
$vparams['actualType'] = DataTypes::ENUM;
$vparams['format'][] = $format;
@ -312,7 +301,7 @@ class ValidationParser implements ParserInterface, PostParserInterface
foreach ($constraint->constraints as $childConstraint) {
if ($childConstraint instanceof Type) {
$nestedType = $childConstraint->type;
$exp = explode("\\", $nestedType);
$exp = explode('\\', $nestedType);
if (!$nestedType || !class_exists($nestedType)) {
$nestedType = substr($className, 0, strrpos($className, '\\') + 1) . $nestedType;
@ -321,7 +310,7 @@ class ValidationParser implements ParserInterface, PostParserInterface
}
}
$vparams['dataType'] = sprintf("array of objects (%s)", end($exp));
$vparams['dataType'] = sprintf('array of objects (%s)', end($exp));
$vparams['actualType'] = DataTypes::COLLECTION;
$vparams['subType'] = $nestedType;
$vparams['class'] = $nestedType;
@ -341,16 +330,15 @@ class ValidationParser implements ParserInterface, PostParserInterface
/**
* Return Choice constraint choices.
*
* @param Constraint $constraint
* @param $className
* @return array
* @throws \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*
* @throws ConstraintDefinitionException
*/
protected function getChoices(Constraint $constraint, $className)
{
if ($constraint->callback) {
if (is_callable(array($className, $constraint->callback))) {
$choices = call_user_func(array($className, $constraint->callback));
if (is_callable([$className, $constraint->callback])) {
$choices = call_user_func([$className, $constraint->callback]);
} elseif (is_callable($constraint->callback)) {
$choices = call_user_func($constraint->callback);
} else {

View File

@ -12,7 +12,6 @@
namespace Nelmio\ApiDocBundle\Parser;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
use Symfony\Component\Validator\Constraint;
/**
* Uses the Symfony Validation component to extract information about API objects. This is a backwards-compatible Validation component for Symfony2.1
@ -20,7 +19,7 @@ use Symfony\Component\Validator\Constraint;
class ValidationParserLegacy extends ValidationParser
{
/**
* @var \Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface
* @var ClassMetadataFactoryInterface
*/
protected $factory;
@ -34,9 +33,6 @@ class ValidationParserLegacy extends ValidationParser
$this->factory = $factory;
}
/**
* {@inheritdoc}
*/
public function supports(array $input)
{
$className = $input['class'];
@ -44,12 +40,9 @@ class ValidationParserLegacy extends ValidationParser
return null !== $this->factory->getClassMetadata($className);
}
/**
* {@inheritdoc}
*/
public function parse(array $input)
{
$params = array();
$params = [];
$className = $input['class'];
$classdata = $this->factory->getClassMetadata($className);
@ -60,9 +53,9 @@ class ValidationParserLegacy extends ValidationParser
$defaults = $refl->getDefaultProperties();
foreach ($properties as $property) {
$vparams = array();
$vparams = [];
$vparams['default'] = isset($defaults[$property]) ? $defaults[$property] : null;
$vparams['default'] = $defaults[$property] ?? null;
$pds = $classdata->getMemberMetadatas($property);
@ -75,10 +68,10 @@ class ValidationParserLegacy extends ValidationParser
}
if (isset($vparams['format'])) {
$vparams['format'] = join(', ', $vparams['format']);
$vparams['format'] = implode(', ', $vparams['format']);
}
foreach (array('dataType', 'readonly', 'required') as $reqprop) {
foreach (['dataType', 'readonly', 'required'] as $reqprop) {
if (!isset($vparams[$reqprop])) {
$vparams[$reqprop] = null;
}
@ -89,5 +82,4 @@ class ValidationParserLegacy extends ValidationParser
return $params;
}
}

View File

@ -8,6 +8,7 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Nelmio\ApiDocBundle\Swagger;
use Nelmio\ApiDocBundle\DataTypes;
@ -22,24 +23,24 @@ class ModelRegistry
/**
* @var array
*/
protected $namingStrategies = array(
protected $namingStrategies = [
'dot_notation' => 'nameDotNotation',
'last_segment_only' => 'nameLastSegmentOnly',
);
];
/**
* @var array
*/
protected $models = array();
protected $models = [];
protected $classes = array();
protected $classes = [];
/**
* @var callable
*/
protected $namingStategy;
protected $typeMap = array(
protected $typeMap = [
DataTypes::INTEGER => 'integer',
DataTypes::FLOAT => 'number',
DataTypes::STRING => 'string',
@ -47,15 +48,15 @@ class ModelRegistry
DataTypes::FILE => 'string',
DataTypes::DATE => 'string',
DataTypes::DATETIME => 'string',
);
];
protected $formatMap = array(
protected $formatMap = [
DataTypes::INTEGER => 'int32',
DataTypes::FLOAT => 'float',
DataTypes::FILE => 'byte',
DataTypes::DATE => 'date',
DataTypes::DATETIME => 'date-time',
);
];
public function __construct($namingStrategy)
{
@ -66,16 +67,16 @@ class ModelRegistry
));
}
$this->namingStategy = array($this, $this->namingStrategies[$namingStrategy]);
$this->namingStategy = [$this, $this->namingStrategies[$namingStrategy]];
}
public function register($className, array $parameters = null, $description = '')
public function register($className, ?array $parameters = null, $description = '')
{
if (!isset($this->classes[$className])) {
$this->classes[$className] = array();
$this->classes[$className] = [];
}
$id = call_user_func_array($this->namingStategy, array($className));
$id = call_user_func_array($this->namingStategy, [$className]);
if (isset($this->models[$id])) {
return $id;
@ -83,30 +84,25 @@ class ModelRegistry
$this->classes[$className][] = $id;
$model = array(
$model = [
'id' => $id,
'description' => $description,
);
];
if (is_array($parameters)) {
$required = array();
$properties = array();
$required = [];
$properties = [];
foreach ($parameters as $name => $prop) {
$subParam = [];
$subParam = array();
if ($prop['actualType'] === DataTypes::MODEL) {
if (DataTypes::MODEL === $prop['actualType']) {
$subParam['$ref'] = $this->register(
$prop['subType'],
isset($prop['children']) ? $prop['children'] : null,
$prop['children'] ?? null,
$prop['description'] ?: $prop['dataType']
);
} else {
$type = null;
$format = null;
$items = null;
@ -114,11 +110,8 @@ class ModelRegistry
$ref = null;
if (isset($this->typeMap[$prop['actualType']])) {
$type = $this->typeMap[$prop['actualType']];
} else {
switch ($prop['actualType']) {
case DataTypes::ENUM:
$type = 'string';
@ -130,23 +123,22 @@ class ModelRegistry
case DataTypes::COLLECTION:
$type = 'array';
if ($prop['subType'] === null) {
$items = array(
if (null === $prop['subType']) {
$items = [
'type' => 'string',
);
];
} elseif (isset($this->typeMap[$prop['subType']])) {
$items = array(
'type' => $this->typeMap[$prop['subType']]
);
$items = [
'type' => $this->typeMap[$prop['subType']],
];
} elseif (!isset($this->typeMap[$prop['subType']])) {
$items = array(
'$ref' =>
$this->register(
$items = [
'$ref' => $this->register(
$prop['subType'],
isset($prop['children']) ? $prop['children'] : null,
$prop['children'] ?? null,
$prop['description'] ?: $prop['dataType']
)
);
),
];
}
/* @TODO: Handle recursion if subtype is a model. */
break;
@ -154,7 +146,7 @@ class ModelRegistry
case DataTypes::MODEL:
$ref = $this->register(
$prop['subType'],
isset($prop['children']) ? $prop['children'] : null,
$prop['children'] ?? null,
$prop['description'] ?: $prop['dataType']
);
@ -168,31 +160,30 @@ class ModelRegistry
$format = $this->formatMap[$prop['actualType']];
}
$subParam = array(
$subParam = [
'type' => $type,
'description' => empty($prop['description']) === false ? (string) $prop['description'] : $prop['dataType'],
);
'description' => false === empty($prop['description']) ? (string) $prop['description'] : $prop['dataType'],
];
if ($format !== null) {
if (null !== $format) {
$subParam['format'] = $format;
}
if ($enum !== null) {
if (null !== $enum) {
$subParam['enum'] = $enum;
}
if ($ref !== null) {
if (null !== $ref) {
$subParam['$ref'] = $ref;
}
if ($items !== null) {
if (null !== $items) {
$subParam['items'] = $items;
}
if ($prop['required']) {
$required[] = $name;
}
}
$properties[$name] = $subParam;
@ -204,7 +195,6 @@ class ModelRegistry
}
return $id;
}
public function nameDotNotation($className)
@ -220,7 +210,6 @@ class ModelRegistry
$id = preg_replace('/^\./', '', $id);
return $id;
}
public function nameLastSegmentOnly($className)
@ -239,9 +228,9 @@ class ModelRegistry
return $this->models;
}
public function clear()
public function clear(): void
{
$this->models = array();
$this->classes = array();
$this->models = [];
$this->classes = [];
}
}

View File

@ -17,9 +17,9 @@ use Symfony\Component\Routing\Route;
class ApiDocTest extends TestCase
{
public function testConstructWithoutData()
public function testConstructWithoutData(): void
{
$data = array();
$data = [];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -38,12 +38,12 @@ class ApiDocTest extends TestCase
$this->assertTrue(is_array($array['authenticationRoles']));
}
public function testConstructWithInvalidData()
public function testConstructWithInvalidData(): void
{
$data = array(
$data = [
'unknown' => 'foo',
'array' => array('bar' => 'bar'),
);
'array' => ['bar' => 'bar'],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -58,11 +58,11 @@ class ApiDocTest extends TestCase
$this->assertNull($annot->getInput());
}
public function testConstruct()
public function testConstruct(): void
{
$data = array(
$data = [
'description' => 'Heya',
);
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -77,12 +77,12 @@ class ApiDocTest extends TestCase
$this->assertNull($annot->getInput());
}
public function testConstructDefinesAFormType()
public function testConstructDefinesAFormType(): void
{
$data = array(
$data = [
'description' => 'Heya',
'input' => 'My\Form\Type',
);
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -97,14 +97,14 @@ class ApiDocTest extends TestCase
$this->assertEquals($data['input'], $annot->getInput());
}
public function testConstructMethodIsResource()
public function testConstructMethodIsResource(): void
{
$data = array(
$data = [
'resource' => true,
'description' => 'Heya',
'deprecated' => true,
'input' => 'My\Form\Type',
);
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -119,14 +119,14 @@ class ApiDocTest extends TestCase
$this->assertEquals($data['input'], $annot->getInput());
}
public function testConstructMethodResourceIsFalse()
public function testConstructMethodResourceIsFalse(): void
{
$data = array(
$data = [
'resource' => false,
'description' => 'Heya',
'deprecated' => false,
'input' => 'My\Form\Type',
);
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -141,16 +141,16 @@ class ApiDocTest extends TestCase
$this->assertEquals($data['input'], $annot->getInput());
}
public function testConstructMethodHasFilters()
public function testConstructMethodHasFilters(): void
{
$data = array(
$data = [
'resource' => true,
'deprecated' => false,
'description' => 'Heya',
'filters' => array(
array('name' => 'a-filter'),
),
);
'filters' => [
['name' => 'a-filter'],
],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -158,7 +158,7 @@ class ApiDocTest extends TestCase
$this->assertTrue(is_array($array));
$this->assertTrue(is_array($array['filters']));
$this->assertCount(1, $array['filters']);
$this->assertEquals(array('a-filter' => array()), $array['filters']);
$this->assertEquals(['a-filter' => []], $array['filters']);
$this->assertTrue($annot->isResource());
$this->assertEquals($data['description'], $array['description']);
$this->assertFalse(isset($array['requirements']));
@ -167,33 +167,33 @@ class ApiDocTest extends TestCase
$this->assertNull($annot->getInput());
}
public function testConstructMethodHasFiltersWithoutName()
public function testConstructMethodHasFiltersWithoutName(): void
{
$this->expectException(\InvalidArgumentException::class);
$data = array(
$data = [
'description' => 'Heya',
'filters' => array(
array('parameter' => 'foo'),
),
);
'filters' => [
['parameter' => 'foo'],
],
];
$annot = new ApiDoc($data);
}
public function testConstructWithStatusCodes()
public function testConstructWithStatusCodes(): void
{
$data = array(
$data = [
'description' => 'Heya',
'statusCodes' => array(
200 => "Returned when successful",
403 => "Returned when the user is not authorized",
404 => array(
"Returned when the user is not found",
"Returned when when something else is not found"
)
)
);
'statusCodes' => [
200 => 'Returned when successful',
403 => 'Returned when the user is not authorized',
404 => [
'Returned when the user is not found',
'Returned when when something else is not found',
],
],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -201,15 +201,15 @@ class ApiDocTest extends TestCase
$this->assertTrue(is_array($array));
$this->assertTrue(is_array($array['statusCodes']));
foreach ($data['statusCodes'] as $code => $message) {
$this->assertEquals($array['statusCodes'][$code], !is_array($message) ? array($message) : $message);
$this->assertEquals($array['statusCodes'][$code], !is_array($message) ? [$message] : $message);
}
}
public function testConstructWithAuthentication()
public function testConstructWithAuthentication(): void
{
$data = array(
'authentication' => true
);
$data = [
'authentication' => true,
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -217,11 +217,11 @@ class ApiDocTest extends TestCase
$this->assertTrue($array['authentication']);
}
public function testConstructWithCache()
public function testConstructWithCache(): void
{
$data = array(
'cache' => '60'
);
$data = [
'cache' => '60',
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -229,18 +229,18 @@ class ApiDocTest extends TestCase
$this->assertEquals($data['cache'], $array['cache']);
}
public function testConstructWithRequirements()
public function testConstructWithRequirements(): void
{
$data = array(
'requirements' => array(
array(
$data = [
'requirements' => [
[
'name' => 'fooId',
'requirement' => '\d+',
'dataType' => 'integer',
'description' => 'This requirement might be used withing action method directly from Request object'
)
)
);
'description' => 'This requirement might be used withing action method directly from Request object',
],
],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -250,17 +250,17 @@ class ApiDocTest extends TestCase
$this->assertTrue(isset($array['requirements']['fooId']['dataType']));
}
public function testConstructWithParameters()
public function testConstructWithParameters(): void
{
$data = array(
'parameters' => array(
array(
$data = [
'parameters' => [
[
'name' => 'fooId',
'dataType' => 'integer',
'description' => 'Some description'
)
)
);
'description' => 'Some description',
],
],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -270,16 +270,16 @@ class ApiDocTest extends TestCase
$this->assertTrue(isset($array['parameters']['fooId']['dataType']));
}
public function testConstructWithHeaders()
public function testConstructWithHeaders(): void
{
$data = array(
'headers' => array(
array(
$data = [
'headers' => [
[
'name' => 'headerName',
'description' => 'Some description'
)
)
);
'description' => 'Some description',
],
],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -292,44 +292,44 @@ class ApiDocTest extends TestCase
$this->assertEquals($data['headers'][0]['description'], $array['headers']['headerName']['description']);
}
public function testConstructWithOneTag()
public function testConstructWithOneTag(): void
{
$data = array(
'tags' => 'beta'
);
$data = [
'tags' => 'beta',
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
$this->assertTrue(is_array($array));
$this->assertTrue(is_array($array['tags']), 'Single tag should be put in array');
$this->assertEquals(array('beta'), $array['tags']);
$this->assertEquals(['beta'], $array['tags']);
}
public function testConstructWithOneTagAndColorCode()
public function testConstructWithOneTagAndColorCode(): void
{
$data = array(
'tags' => array(
'beta' => '#ff0000'
)
);
$data = [
'tags' => [
'beta' => '#ff0000',
],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
$this->assertTrue(is_array($array));
$this->assertTrue(is_array($array['tags']), 'Single tag should be put in array');
$this->assertEquals(array('beta' => '#ff0000'), $array['tags']);
$this->assertEquals(['beta' => '#ff0000'], $array['tags']);
}
public function testConstructWithMultipleTags()
public function testConstructWithMultipleTags(): void
{
$data = array(
'tags' => array(
$data = [
'tags' => [
'experimental' => '#0000ff',
'beta' => '#0000ff',
)
);
],
];
$annot = new ApiDoc($data);
$array = $annot->toArray();
@ -339,14 +339,14 @@ class ApiDocTest extends TestCase
$this->assertEquals($data['tags'], $array['tags']);
}
public function testAlignmentOfOutputAndResponseModels()
public function testAlignmentOfOutputAndResponseModels(): void
{
$data = array(
$data = [
'output' => 'FooBar',
'responseMap' => array(
'responseMap' => [
400 => 'Foo\\ValidationErrorCollection',
),
);
],
];
$apiDoc = new ApiDoc($data);
@ -358,14 +358,14 @@ class ApiDocTest extends TestCase
$this->assertEquals($data['output'], $map[200]);
}
public function testAlignmentOfOutputAndResponseModels2()
public function testAlignmentOfOutputAndResponseModels2(): void
{
$data = array(
'responseMap' => array(
$data = [
'responseMap' => [
200 => 'FooBar',
400 => 'Foo\\ValidationErrorCollection',
),
);
],
];
$apiDoc = new ApiDoc($data);
$map = $apiDoc->getResponseMap();
@ -376,7 +376,7 @@ class ApiDocTest extends TestCase
$this->assertEquals($apiDoc->getOutput(), $map[200]);
}
public function testSetRoute()
public function testSetRoute(): void
{
$route = new Route(
'/path/{foo}',
@ -385,7 +385,7 @@ class ApiDocTest extends TestCase
'nested' => [
'key1' => 'value1',
'key2' => 'value2',
]
],
],
[],
[],

View File

@ -25,7 +25,7 @@ class DumpCommandTest extends WebTestCase
* @param array $expectedMethodsCount Expected resource methods count
* @param array $expectedMethodValues Expected resource method values
*/
public function testDumpWithViewOption($view, array $expectedMethodsCount, array $expectedMethodValues)
public function testDumpWithViewOption($view, array $expectedMethodsCount, array $expectedMethodValues): void
{
$this->getContainer();
@ -35,11 +35,11 @@ class DumpCommandTest extends WebTestCase
$tester = new ApplicationTester($application);
$input = array(
$input = [
'command' => 'api:doc:dump',
'--view' => $view,
'--format' => 'json',
);
];
$tester->run($input);
$display = $tester->getDisplay();
@ -64,35 +64,35 @@ class DumpCommandTest extends WebTestCase
*/
public static function viewProvider()
{
return array(
'test' => array(
return [
'test' => [
'test',
array(
[
'/api/resources' => 1,
),
array(
],
[
'/api/resources[0].method' => 'GET',
'/api/resources[0].uri' => '/api/resources.{_format}',
)
),
'premium' => array(
],
],
'premium' => [
'premium',
array(
[
'/api/resources' => 2,
),
array(
],
[
'/api/resources[0].method' => 'GET',
'/api/resources[0].uri' => '/api/resources.{_format}',
'/api/resources[1].method' => 'POST',
'/api/resources[1].uri' => '/api/resources.{_format}',
)
),
'default' => array(
],
],
'default' => [
'default',
array(
[
'/api/resources' => 4,
),
array(
],
[
'/api/resources[0].method' => 'GET',
'/api/resources[0].uri' => '/api/resources.{_format}',
'/api/resources[1].method' => 'POST',
@ -101,8 +101,8 @@ class DumpCommandTest extends WebTestCase
'/api/resources[2].uri' => '/api/resources/{id}.{_format}',
'/api/resources[3].method' => 'GET',
'/api/resources[3].uri' => '/api/resources/{id}.{_format}',
)
),
);
],
],
];
}
}

View File

@ -10,17 +10,17 @@
*/
namespace NelmioApiDocBundle\Tests\Controller;
use Nelmio\ApiDocBundle\Tests\WebTestCase;
/**
* Class ApiDocControllerTest
*
* @package NelmioApiDocBundle\Tests\Controller
* @author Bez Hermoso <bez@activelamp.com>
*/
class ApiDocControllerTest extends WebTestCase
{
public function testSwaggerDocResourceListRoute()
public function testSwaggerDocResourceListRoute(): void
{
$client = static::createClient();
$client->request('GET', '/api-docs');
@ -29,23 +29,22 @@ class ApiDocControllerTest extends WebTestCase
$this->assertEquals(200, $response->getStatusCode());
$this->assertEquals('text/html; charset=UTF-8', $response->headers->get('Content-type'));
}
public function dataTestApiDeclarations()
{
return array(
array('resources'),
array('tests'),
array('tests2'),
array('TestResource'),
);
return [
['resources'],
['tests'],
['tests2'],
['TestResource'],
];
}
/**
* @dataProvider dataTestApiDeclarations
*/
public function testApiDeclarationRoutes($resource)
public function testApiDeclarationRoutes($resource): void
{
$client = static::createClient();
$client->request('GET', '/api-docs/' . $resource);
@ -56,13 +55,12 @@ class ApiDocControllerTest extends WebTestCase
$this->assertEquals('application/json', $response->headers->get('Content-type'));
}
public function testNonExistingApiDeclaration()
public function testNonExistingApiDeclaration(): void
{
$client = static::createClient();
$client->request('GET', '/api-docs/santa');
$response = $client->getResponse();
$this->assertEquals(404, $response->getStatusCode());
}
}

View File

@ -15,14 +15,14 @@ use Nelmio\ApiDocBundle\Tests\WebTestCase;
class RequestListenerTest extends WebTestCase
{
public function testDocQueryArg()
public function testDocQueryArg(): void
{
$client = $this->createClient();
$client->request('GET', '/tests?_doc=1');
$content = $client->getResponse()->getContent();
$this->assertTrue(0 !== strpos($content, '<h1>API documentation</h1>'), 'Event listener should capture ?_doc=1 requests');
$this->assertTrue(0 !== strpos($content, '/tests.{_format}'), 'Event listener should capture ?_doc=1 requests');
$this->assertTrue(!str_starts_with($content, '<h1>API documentation</h1>'), 'Event listener should capture ?_doc=1 requests');
$this->assertTrue(!str_starts_with($content, '/tests.{_format}'), 'Event listener should capture ?_doc=1 requests');
$client->request('GET', '/tests');
$this->assertEquals('tests', $client->getResponse()->getContent(), 'Event listener should let normal requests through');

View File

@ -27,7 +27,7 @@ class DunglasApiProviderTest extends WebTestCase
}
}
public function testGetAnnotations()
public function testGetAnnotations(): void
{
$container = $this->getContainer();
$provider = $container->get('nelmio_api_doc.annotations_provider.dunglas_api_annotation_provider');

View File

@ -17,7 +17,7 @@ use Nelmio\ApiDocBundle\Tests\WebTestCase;
class ApiDocExtractorTest extends WebTestCase
{
const NB_ROUTES_ADDED_BY_DUNGLAS_API_BUNDLE = 5;
public const NB_ROUTES_ADDED_BY_DUNGLAS_API_BUNDLE = 5;
private static $ROUTES_QUANTITY_DEFAULT = 36; // Routes in the default view
private static $ROUTES_QUANTITY_PREMIUM = 5; // Routes in the premium view
@ -32,11 +32,11 @@ class ApiDocExtractorTest extends WebTestCase
}
}
public function testAll()
public function testAll(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$data = $extractor->all();
restore_error_handler();
@ -96,7 +96,7 @@ class ApiDocExtractorTest extends WebTestCase
// $this->assertEquals('test.dev|test.com', $a5requirements['domain']['requirement']);
}
public function testRouteVersionChecking()
public function testRouteVersionChecking(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -108,7 +108,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertCount(self::$ROUTES_QUANTITY_DEFAULT - 1, $data);
}
public function testGet()
public function testGet(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -126,11 +126,12 @@ class ApiDocExtractorTest extends WebTestCase
$annotation2 = $extractor->get('Nelmio\ApiDocBundle\Tests\Fixtures\Controller\TestController::indexAction', 'test_service_route_1');
$annotation2->getRoute()
->setDefault('_controller', $annotation->getRoute()->getDefault('_controller'))
->compile(); // compile as we changed a default value
->compile() // compile as we changed a default value
;
$this->assertEquals($annotation, $annotation2);
}
public function testGetWithBadController()
public function testGetWithBadController(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -143,7 +144,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertNull($data);
}
public function testGetWithBadRoute()
public function testGetWithBadRoute(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -156,7 +157,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertNull($data);
}
public function testGetWithInvalidPath()
public function testGetWithInvalidPath(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -169,7 +170,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertNull($data);
}
public function testGetWithMethodWithoutApiDocAnnotation()
public function testGetWithMethodWithoutApiDocAnnotation(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -182,7 +183,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertNull($data);
}
public function testGetWithDocComment()
public function testGetWithDocComment(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -190,7 +191,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertNotNull($annotation);
$this->assertEquals(
"This method is useful to test if the getDocComment works.",
'This method is useful to test if the getDocComment works.',
$annotation->getDescription()
);
@ -209,7 +210,7 @@ class ApiDocExtractorTest extends WebTestCase
);
}
public function testGetWithAuthentication()
public function testGetWithAuthentication(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -224,7 +225,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertCount(2, $annotation->getAuthenticationRoles());
}
public function testGetWithDeprecated()
public function testGetWithDeprecated(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -236,7 +237,7 @@ class ApiDocExtractorTest extends WebTestCase
);
}
public function testOutputWithSelectedParsers()
public function testOutputWithSelectedParsers(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -247,17 +248,17 @@ class ApiDocExtractorTest extends WebTestCase
$parsers = $output['parsers'];
$this->assertEquals(
"Nelmio\\ApiDocBundle\\Parser\\JmsMetadataParser",
'Nelmio\\ApiDocBundle\\Parser\\JmsMetadataParser',
$parsers[0]
);
$this->assertEquals(
"Nelmio\\ApiDocBundle\\Parser\\ValidationParser",
'Nelmio\\ApiDocBundle\\Parser\\ValidationParser',
$parsers[1]
);
$this->assertCount(2, $parsers);
}
public function testInputWithSelectedParsers()
public function testInputWithSelectedParsers(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -267,13 +268,13 @@ class ApiDocExtractorTest extends WebTestCase
$input = $annotation->getInput();
$parsers = $input['parsers'];
$this->assertEquals(
"Nelmio\\ApiDocBundle\\Parser\\FormTypeParser",
'Nelmio\\ApiDocBundle\\Parser\\FormTypeParser',
$parsers[0]
);
$this->assertCount(1, $parsers);
}
public function testPostRequestDoesRequireParametersWhenMarkedAsSuch()
public function testPostRequestDoesRequireParametersWhenMarkedAsSuch(): void
{
$container = $this->getContainer();
/** @var ApiDocExtractor $extractor */
@ -285,7 +286,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertTrue($parameters['required_field']['required']);
}
public function testPatchRequestDoesNeverRequireParameters()
public function testPatchRequestDoesNeverRequireParameters(): void
{
$container = $this->getContainer();
/** @var ApiDocExtractor $extractor */
@ -304,21 +305,21 @@ class ApiDocExtractorTest extends WebTestCase
$offset = self::NB_ROUTES_ADDED_BY_DUNGLAS_API_BUNDLE;
}
return array(
array('default', self::$ROUTES_QUANTITY_DEFAULT + $offset),
array('premium', self::$ROUTES_QUANTITY_PREMIUM + $offset),
array('test', self::$ROUTES_QUANTITY_TEST + $offset),
array('foobar', $offset),
array("", $offset),
array(null, $offset),
);
return [
['default', self::$ROUTES_QUANTITY_DEFAULT + $offset],
['premium', self::$ROUTES_QUANTITY_PREMIUM + $offset],
['test', self::$ROUTES_QUANTITY_TEST + $offset],
['foobar', $offset],
['', $offset],
[null, $offset],
];
}
public function testViewNamedTest()
public function testViewNamedTest(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$data = $extractor->all('test');
restore_error_handler();
@ -334,11 +335,11 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertEquals('create another test', $a2->getDescription());
}
public function testViewNamedPremium()
public function testViewNamedPremium(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$data = $extractor->all('premium');
restore_error_handler();
@ -357,11 +358,11 @@ class ApiDocExtractorTest extends WebTestCase
/**
* @dataProvider dataProviderForViews
*/
public function testForViews($view, $count)
public function testForViews($view, $count): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$data = $extractor->all($view);
restore_error_handler();
@ -369,7 +370,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertCount($count, $data);
}
public function testOverrideJmsAnnotationWithApiDocParameters()
public function testOverrideJmsAnnotationWithApiDocParameters(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -388,10 +389,10 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertEquals('integer', $array['parameters']['number']['dataType']);
$this->assertEquals('string', $array['parameters']['number']['actualType']);
$this->assertEquals(null, $array['parameters']['number']['subType']);
$this->assertEquals(true, $array['parameters']['number']['required']);
$this->assertNull($array['parameters']['number']['subType']);
$this->assertTrue($array['parameters']['number']['required']);
$this->assertEquals('This is the new description', $array['parameters']['number']['description']);
$this->assertEquals(false, $array['parameters']['number']['readonly']);
$this->assertFalse($array['parameters']['number']['readonly']);
$this->assertEquals('v3.0', $array['parameters']['number']['sinceVersion']);
$this->assertEquals('v4.0', $array['parameters']['number']['untilVersion']);
@ -402,7 +403,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertEquals('d+', $array['parameters']['nested']['children']['bar']['format']);
}
public function testJmsAnnotation()
public function testJmsAnnotation(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -421,12 +422,12 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertEquals('double', $array['parameters']['number']['dataType']);
$this->assertEquals('float', $array['parameters']['number']['actualType']);
$this->assertEquals(null, $array['parameters']['number']['subType']);
$this->assertEquals(false, $array['parameters']['number']['required']);
$this->assertNull($array['parameters']['number']['subType']);
$this->assertFalse($array['parameters']['number']['required']);
$this->assertEquals('', $array['parameters']['number']['description']);
$this->assertEquals(false, $array['parameters']['number']['readonly']);
$this->assertEquals(null, $array['parameters']['number']['sinceVersion']);
$this->assertEquals(null, $array['parameters']['number']['untilVersion']);
$this->assertFalse($array['parameters']['number']['readonly']);
$this->assertNull($array['parameters']['number']['sinceVersion']);
$this->assertNull($array['parameters']['number']['untilVersion']);
$this->assertEquals('array', $array['parameters']['arr']['dataType']);
@ -434,7 +435,7 @@ class ApiDocExtractorTest extends WebTestCase
$this->assertEquals('string', $array['parameters']['nested']['children']['bar']['dataType']);
}
public function testMergeParametersDefaultKeyNotExistingInFirstArray()
public function testMergeParametersDefaultKeyNotExistingInFirstArray(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -450,7 +451,7 @@ class ApiDocExtractorTest extends WebTestCase
'required' => null,
'description' => null,
'readonly' => null,
]
],
];
$p2 = [
@ -462,7 +463,7 @@ class ApiDocExtractorTest extends WebTestCase
'description' => null,
'readonly' => null,
'default' => '',
]
],
];
$mergedResult = $mergeMethod->invokeArgs($extractor, [$p1, $p2]);

View File

@ -33,16 +33,17 @@ class CachingApiDocExtractorTest extends WebTestCase
* Test that every view cache is saved in its own cache file
*
* @dataProvider viewsWithoutDefaultProvider
*
* @param string $view View name
*/
public function testDifferentCacheFilesAreCreatedForDifferentViews($view)
public function testDifferentCacheFilesAreCreatedForDifferentViews($view): void
{
$container = $this->getContainer();
/* @var CachingApiDocExtractor $extractor */
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
$this->assertInstanceOf('\Nelmio\ApiDocBundle\Extractor\CachingApiDocExtractor', $extractor);
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$defaultData = $extractor->all(ApiDoc::DEFAULT_VIEW);
$data = $extractor->all($view);
restore_error_handler();
@ -63,9 +64,10 @@ class CachingApiDocExtractorTest extends WebTestCase
/**
* @dataProvider \Nelmio\ApiDocBundle\Tests\Extractor\ApiDocExtractorTest::dataProviderForViews
*
* @param string $view View name to test
*/
public function testCachedResultSameAsGenerated($view)
public function testCachedResultSameAsGenerated($view): void
{
$container = $this->getContainer();
/* @var CachingApiDocExtractor $extractor */
@ -76,7 +78,7 @@ class CachingApiDocExtractorTest extends WebTestCase
$expectedViewCacheFile = $cacheFile . '.' . $view;
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$data = $extractor->all($view);
$this->assertFileExists($expectedViewCacheFile);

View File

@ -20,7 +20,7 @@ class CollectionDirectiveTest extends TestCase
*/
private $testExtractor;
public function setUp(): void
protected function setUp(): void
{
$this->testExtractor = new TestExtractor();
}
@ -33,17 +33,17 @@ class CollectionDirectiveTest extends TestCase
/**
* @dataProvider dataNormalizationTests
*/
public function testNormalizations($input, callable $callable)
public function testNormalizations($input, callable $callable): void
{
call_user_func($callable, $this->normalize($input), $this);
}
public function dataNormalizationTests()
{
return array(
'test_simple_notation' => array(
return [
'test_simple_notation' => [
'array<User>',
function ($actual, TestCase $case) {
function ($actual, TestCase $case): void {
$case->assertArrayHasKey('collection', $actual);
$case->assertArrayHasKey('collectionName', $actual);
$case->assertArrayHasKey('class', $actual);
@ -51,11 +51,11 @@ class CollectionDirectiveTest extends TestCase
$case->assertTrue($actual['collection']);
$case->assertEquals('', $actual['collectionName']);
$case->assertEquals('User', $actual['class']);
}
),
'test_simple_notation_with_namespaces' => array(
},
],
'test_simple_notation_with_namespaces' => [
'array<Vendor0_2\\_Namespace1\\Namespace_2\\User>',
function ($actual, TestCase $case) {
function ($actual, TestCase $case): void {
$case->assertArrayHasKey('collection', $actual);
$case->assertArrayHasKey('collectionName', $actual);
$case->assertArrayHasKey('class', $actual);
@ -63,11 +63,11 @@ class CollectionDirectiveTest extends TestCase
$case->assertTrue($actual['collection']);
$case->assertEquals('', $actual['collectionName']);
$case->assertEquals('Vendor0_2\\_Namespace1\\Namespace_2\\User', $actual['class']);
}
),
'test_simple_named_collections' => array(
},
],
'test_simple_named_collections' => [
'array<Group> as groups',
function ($actual, TestCase $case) {
function ($actual, TestCase $case): void {
$case->assertArrayHasKey('collection', $actual);
$case->assertArrayHasKey('collectionName', $actual);
$case->assertArrayHasKey('class', $actual);
@ -75,11 +75,11 @@ class CollectionDirectiveTest extends TestCase
$case->assertTrue($actual['collection']);
$case->assertEquals('groups', $actual['collectionName']);
$case->assertEquals('Group', $actual['class']);
}
),
'test_namespaced_named_collections' => array(
},
],
'test_namespaced_named_collections' => [
'array<_Vendor\\Namespace0\\Namespace_2F3\\Group> as groups',
function ($actual, TestCase $case) {
function ($actual, TestCase $case): void {
$case->assertArrayHasKey('collection', $actual);
$case->assertArrayHasKey('collectionName', $actual);
$case->assertArrayHasKey('class', $actual);
@ -87,17 +87,15 @@ class CollectionDirectiveTest extends TestCase
$case->assertTrue($actual['collection']);
$case->assertEquals('groups', $actual['collectionName']);
$case->assertEquals('_Vendor\\Namespace0\\Namespace_2F3\\Group', $actual['class']);
}
),
);
},
],
];
}
/**
* @dataProvider dataInvalidDirectives
* @param $input
*/
public function testInvalidDirectives($input)
public function testInvalidDirectives($input): void
{
$this->expectException(\InvalidArgumentException::class);
@ -106,13 +104,13 @@ class CollectionDirectiveTest extends TestCase
public function dataInvalidDirectives()
{
return array(
array('array<>'),
array('array<Vendor\\>'),
array('array<2Vendor\\>'),
array('array<Vendor\\2Class>'),
array('array<User> as'),
array('array<User> as '),
);
return [
['array<>'],
['array<Vendor\\>'],
['array<2Vendor\\>'],
['array<Vendor\\2Class>'],
['array<User> as'],
['array<User> as '],
];
}
}

View File

@ -15,8 +15,7 @@ use Nelmio\ApiDocBundle\Tests\WebTestCase;
class FosRestHandlerTest extends WebTestCase
{
public function testGetWithQueryParamStrict()
public function testGetWithQueryParamStrict(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -41,7 +40,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertArrayNotHasKey('default', $requirement);
}
public function testGetWithQueryParam()
public function testGetWithQueryParam(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -65,7 +64,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertEquals($filter['default'], '1');
}
public function testGetWithQueryParamNoDefault()
public function testGetWithQueryParamNoDefault(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -88,7 +87,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertArrayNotHasKey('default', $filter);
}
public function testGetWithConstraintAsRequirements()
public function testGetWithConstraintAsRequirements(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -106,7 +105,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertEquals($filter['requirement'], 'Email');
}
public function testGetWithRequestParam()
public function testGetWithRequestParam(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -132,7 +131,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertArrayNotHasKey('default', $parameter);
}
public function testGetWithRequestParamNullable()
public function testGetWithRequestParamNullable(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -158,7 +157,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertArrayNotHasKey('default', $parameter);
}
public function testWithRequestParamArrayRequirements()
public function testWithRequestParamArrayRequirements(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -172,7 +171,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertEquals('regexp', $filters['param1']['requirement']);
}
public function testWithRequestParamPlainArrayRequirements()
public function testWithRequestParamPlainArrayRequirements(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
@ -186,7 +185,7 @@ class FosRestHandlerTest extends WebTestCase
$this->assertEquals('NotNull, NotBlank', $filters['param1']['requirement']);
}
public function testWithRequirementParamNotSet()
public function testWithRequirementParamNotSet(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');

View File

@ -17,7 +17,6 @@ class TestExtractor extends ApiDocExtractor
{
public function __construct()
{
}
public function getNormalization($input)

View File

@ -25,25 +25,22 @@ class ResourceController
* statusCodes={200 = "Returned on success.", 404 = "Returned if resource cannot be found."}
* )
*/
public function listResourcesAction()
public function listResourcesAction(): void
{
}
/**
* @ApiDoc(description="Retrieve a resource by ID.")
*/
public function getResourceAction()
public function getResourceAction(): void
{
}
/**
* @ApiDoc(description="Delete a resource by ID.")
*/
public function deleteResourceAction()
public function deleteResourceAction(): void
{
}
/**
@ -57,9 +54,8 @@ class ResourceController
* }
* )
*/
public function createResourceAction()
public function createResourceAction(): void
{
}
/**
@ -71,24 +67,21 @@ class ResourceController
* output="array<Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest>"
* )
*/
public function listAnotherResourcesAction()
public function listAnotherResourcesAction(): void
{
}
/**
* @ApiDoc(description="Retrieve another resource by ID.")
*/
public function getAnotherResourceAction()
public function getAnotherResourceAction(): void
{
}
/**
* @ApiDoc(description="Update a resource bu ID.")
*/
public function updateAnotherResourceAction()
public function updateAnotherResourceAction(): void
{
}
}

View File

@ -26,7 +26,7 @@ class TestController
* views="default"
* )
*/
public function namedResourceAction()
public function namedResourceAction(): void
{
}
@ -53,7 +53,7 @@ class TestController
* input="Nelmio\ApiDocBundle\Tests\Fixtures\Form\TestType"
* )
*/
public function postTestAction()
public function postTestAction(): void
{
}
@ -64,7 +64,7 @@ class TestController
* resource=true
* )
*/
public function postTest2Action()
public function postTest2Action(): void
{
}
@ -73,25 +73,25 @@ class TestController
* input="Nelmio\ApiDocBundle\Tests\Fixtures\Form\RequiredType"
* )
*/
public function requiredParametersAction()
public function requiredParametersAction(): void
{
}
public function anotherAction()
public function anotherAction(): void
{
}
/**
* @ApiDoc()
*/
public function routeVersionAction()
public function routeVersionAction(): void
{
}
/**
* @ApiDoc(description="Action without HTTP verb")
*/
public function anyAction()
public function anyAction(): void
{
}
@ -106,14 +106,14 @@ class TestController
* @param int $paramType The param type
* @param int $param The param id
*/
public function myCommentedAction()
public function myCommentedAction($id, $page, int $paramType, int $param): void
{
}
/**
* @ApiDoc()
*/
public function yetAnotherAction()
public function yetAnotherAction(): void
{
}
@ -124,39 +124,43 @@ class TestController
* input=DependencyTypePath::TYPE
* )
*/
public function anotherPostAction()
public function anotherPostAction(): void
{
}
/**
* @ApiDoc()
*
* @QueryParam(strict=true, name="page", requirements="\d+", description="Page of the overview.")
*/
public function zActionWithQueryParamStrictAction()
public function zActionWithQueryParamStrictAction(): void
{
}
/**
* @ApiDoc()
*
* @QueryParam(name="page", requirements="\d+", default="1", description="Page of the overview.")
*/
public function zActionWithQueryParamAction()
public function zActionWithQueryParamAction(): void
{
}
/**
* @ApiDoc()
*
* @QueryParam(name="page", requirements="\d+", description="Page of the overview.")
*/
public function zActionWithQueryParamNoDefaultAction()
public function zActionWithQueryParamNoDefaultAction(): void
{
}
/**
* @ApiDoc()
*
* @QueryParam(name="mail", requirements=@Assert\Email, description="Email of someone.")
*/
public function zActionWithConstraintAsRequirements()
public function zActionWithConstraintAsRequirements(): void
{
}
@ -166,7 +170,7 @@ class TestController
* input="Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest"
* )
*/
public function jmsInputTestAction()
public function jmsInputTestAction(): void
{
}
@ -176,30 +180,32 @@ class TestController
* output=DependencyTypePath::TYPE
* )
*/
public function jmsReturnTestAction()
public function jmsReturnTestAction(): void
{
}
/**
* @ApiDoc()
*
* @RequestParam(name="param1", requirements="string", description="Param1 description.")
*/
public function zActionWithRequestParamAction()
public function zActionWithRequestParamAction(): void
{
}
/**
* @ApiDoc()
*
* @RequestParam(name="param1", requirements="string", description="Param1 description.", nullable=true)
*/
public function zActionWithNullableRequestParamAction()
public function zActionWithNullableRequestParamAction(): void
{
}
/**
* @ApiDoc()
*/
public function secureRouteAction()
public function secureRouteAction(): void
{
}
@ -209,29 +215,30 @@ class TestController
* authenticationRoles={"ROLE_USER","ROLE_FOOBAR"}
* )
*/
public function authenticatedAction()
public function authenticatedAction(): void
{
}
/**
* @ApiDoc()
*/
public function zCachedAction()
public function zCachedAction(): void
{
}
/**
* @ApiDoc()
*/
public function zSecuredAction()
public function zSecuredAction(): void
{
}
/**
* @ApiDoc()
*
* @deprecated
*/
public function deprecatedAction()
public function deprecatedAction(): void
{
}
@ -240,7 +247,7 @@ class TestController
* output="Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest"
* )
*/
public function jmsReturnNestedOutputAction()
public function jmsReturnNestedOutputAction(): void
{
}
@ -249,7 +256,7 @@ class TestController
* output="Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsChild"
* )
*/
public function jmsReturnNestedExtendedOutputAction()
public function jmsReturnNestedExtendedOutputAction(): void
{
}
@ -258,7 +265,7 @@ class TestController
* output="Nelmio\ApiDocBundle\Tests\Fixtures\Model\MultipleTest"
* )
*/
public function zReturnJmsAndValidationOutputAction()
public function zReturnJmsAndValidationOutputAction(): void
{
}
@ -273,7 +280,7 @@ class TestController
* }
* )
*/
public function cgetAction($id)
public function cgetAction($id): void
{
}
@ -287,7 +294,7 @@ class TestController
* }
* )
*/
public function zReturnSelectedParsersInputAction()
public function zReturnSelectedParsersInputAction(): void
{
}
@ -302,7 +309,7 @@ class TestController
* }
* )
*/
public function zReturnSelectedParsersOutputAction()
public function zReturnSelectedParsersOutputAction(): void
{
}
@ -311,7 +318,7 @@ class TestController
* section="private"
* )
*/
public function privateAction()
public function privateAction(): void
{
}
@ -320,15 +327,16 @@ class TestController
* section="exclusive"
* )
*/
public function exclusiveAction()
public function exclusiveAction(): void
{
}
/**
* @ApiDoc()
* @link http://symfony.com
*
* @see http://symfony.com
*/
public function withLinkAction()
public function withLinkAction(): void
{
}
@ -367,7 +375,7 @@ class TestController
* }
* )
*/
public function overrideJmsAnnotationWithApiDocParametersAction()
public function overrideJmsAnnotationWithApiDocParametersAction(): void
{
}
@ -379,7 +387,7 @@ class TestController
* }
* )
*/
public function defaultJmsAnnotations()
public function defaultJmsAnnotations(): void
{
}
@ -389,31 +397,34 @@ class TestController
* views={ "default" }
* )
*/
public function routeWithHostAction()
public function routeWithHostAction(): void
{
}
/**
* @ApiDoc()
*
* @QueryParam(name="param1", requirements={"rule": "regexp", "error_message": "warning"}, description="Param1 description.")
*/
public function routeWithQueryParamArrayRequirementsAction()
public function routeWithQueryParamArrayRequirementsAction(): void
{
}
/**
* @ApiDoc()
*
* @QueryParam(name="param1", requirements={@Assert\NotNull(), @Assert\NotBlank()}, description="Param1 description.")
*/
public function routeWithQueryParamPlainArrayRequirementsAction()
public function routeWithQueryParamPlainArrayRequirementsAction(): void
{
}
/**
* @ApiDoc()
*
* @QueryParam(name="param1", description="Param1 description.")
*/
public function zActionWithRequirementParamNotSet()
public function zActionWithRequirementParamNotSet(): void
{
}
}

View File

@ -13,7 +13,7 @@ namespace Nelmio\ApiDocBundle\Tests\Fixtures;
use Nelmio\ApiDocBundle\Util\LegacyFormHelper;
/**
/*
* This class is used to have dynamic annotations for BC.
* {@see Nelmio\ApiDocBundle\Tests\Fixtures\Controller\TestController}
*
@ -22,11 +22,11 @@ use Nelmio\ApiDocBundle\Util\LegacyFormHelper;
if (LegacyFormHelper::isLegacy()) {
class DependencyTypePath
{
const TYPE = 'dependency_type';
public const TYPE = 'dependency_type';
}
} else {
class DependencyTypePath
{
const TYPE = 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\DependencyType';
public const TYPE = 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\DependencyType';
}
}

View File

@ -14,23 +14,19 @@ namespace Nelmio\ApiDocBundle\Tests\Fixtures\Form;
use Nelmio\ApiDocBundle\Util\LegacyFormHelper;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class CollectionType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$collectionType = 'Symfony\Component\Form\Extension\Core\Type\CollectionType';
$builder
->add('a', LegacyFormHelper::getType($collectionType), array(
LegacyFormHelper::hasBCBreaks() ? 'entry_type' : 'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType')
))
->add('b', LegacyFormHelper::getType($collectionType), array(
LegacyFormHelper::hasBCBreaks() ? 'entry_type' : 'type' => LegacyFormHelper::isLegacy() ? new TestType() : __NAMESPACE__.'\TestType'
))
->add('a', LegacyFormHelper::getType($collectionType), [
LegacyFormHelper::hasBCBreaks() ? 'entry_type' : 'type' => LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType'),
])
->add('b', LegacyFormHelper::getType($collectionType), [
LegacyFormHelper::hasBCBreaks() ? 'entry_type' : 'type' => LegacyFormHelper::isLegacy() ? new TestType() : __NAMESPACE__ . '\TestType',
])
;
}
@ -43,9 +39,6 @@ class CollectionType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'collection_type';

View File

@ -22,7 +22,7 @@ use Symfony\Component\Form\FormBuilderInterface;
*/
class CompoundType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('sub_form', LegacyFormHelper::isLegacy() ? new SimpleType() : __NAMESPACE__ . '\SimpleType')
@ -39,9 +39,6 @@ class CompoundType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';

View File

@ -22,34 +22,26 @@ class DependencyType extends AbstractType
{
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('a', null, array('description' => 'A nice description'))
->add('a', null, ['description' => 'A nice description'])
;
}
/**
* {@inheritdoc}
*
* @deprecated Remove it when bumping requirements to Symfony 2.7+
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolverInterface $resolver): void
{
$this->configureOptions($resolver);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(array(
$resolver->setDefaults([
'data_class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\Test',
));
]);
return;
}
@ -63,9 +55,6 @@ class DependencyType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'dependency_type';

View File

@ -13,31 +13,24 @@ namespace Nelmio\ApiDocBundle\Tests\Fixtures\Form;
use Nelmio\ApiDocBundle\Util\LegacyFormHelper;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\ChoiceList\SimpleChoiceList;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class EntityType extends AbstractType
{
/**
* {@inheritdoc}
*
* @deprecated Remove it when bumping requirements to Symfony 2.7+
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolverInterface $resolver): void
{
$this->configureOptions($resolver);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(array(
$resolver->setDefaults([
'data_class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\EntityTest',
));
]);
return;
}
@ -56,9 +49,6 @@ class EntityType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'entity';

View File

@ -20,53 +20,45 @@ use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ImprovedTestType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$choiceType = LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\ChoiceType');
$datetimeType = LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\DateTimeType');
$dateType = LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\DateType');
$builder
->add('dt1', $datetimeType, array('widget' => 'single_text', 'description' => 'A nice description'))
->add('dt2', $datetimeType, array('date_format' => 'M/d/y', 'html5' => false))
->add('dt3', $datetimeType, array('widget' => 'single_text', 'format' => 'M/d/y H:i:s', 'html5' => false))
->add('dt4', $datetimeType, array('date_format' => \IntlDateFormatter::MEDIUM))
->add('dt5', $datetimeType, array('format' => 'M/d/y H:i:s', 'html5' => false))
->add('d1', $dateType, array('format' => \IntlDateFormatter::MEDIUM))
->add('d2', $dateType, array('format' => 'd-M-y'))
->add('c1', $choiceType, array('choices' => array('Male' => 'm', 'Female' => 'f')))
->add('c2', $choiceType, array('choices' => array('Male' => 'm', 'Female' => 'f') , 'multiple' => true))
->add('c3', $choiceType, array('choices' => array()))
->add('c4', $choiceType, array('choices' => array('bar' => 'foo', 'bazgroup' => array('Buzz' => 'baz'))))
->add('dt1', $datetimeType, ['widget' => 'single_text', 'description' => 'A nice description'])
->add('dt2', $datetimeType, ['date_format' => 'M/d/y', 'html5' => false])
->add('dt3', $datetimeType, ['widget' => 'single_text', 'format' => 'M/d/y H:i:s', 'html5' => false])
->add('dt4', $datetimeType, ['date_format' => \IntlDateFormatter::MEDIUM])
->add('dt5', $datetimeType, ['format' => 'M/d/y H:i:s', 'html5' => false])
->add('d1', $dateType, ['format' => \IntlDateFormatter::MEDIUM])
->add('d2', $dateType, ['format' => 'd-M-y'])
->add('c1', $choiceType, ['choices' => ['Male' => 'm', 'Female' => 'f']])
->add('c2', $choiceType, ['choices' => ['Male' => 'm', 'Female' => 'f'], 'multiple' => true])
->add('c3', $choiceType, ['choices' => []])
->add('c4', $choiceType, ['choices' => ['bar' => 'foo', 'bazgroup' => ['Buzz' => 'baz']]])
->add('e1', LegacyFormHelper::isLegacy() ? new EntityType() : __NAMESPACE__ . '\EntityType',
LegacyFormHelper::isLegacy()
? array('choice_list' => new SimpleChoiceList(array('bar' => 'foo', 'bazgroup' => array('Buzz' => 'baz'))))
: array('choices' => array('bar' => 'foo', 'bazgroup' => array('Buzz' => 'baz')))
? ['choice_list' => new SimpleChoiceList(['bar' => 'foo', 'bazgroup' => ['Buzz' => 'baz']])]
: ['choices' => ['bar' => 'foo', 'bazgroup' => ['Buzz' => 'baz']]]
)
;
}
/**
* {@inheritdoc}
*
* @deprecated Remove it when bumping requirements to Symfony 2.7+
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolverInterface $resolver): void
{
$this->configureOptions($resolver);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(array(
$resolver->setDefaults([
'data_class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\ImprovedTest',
));
]);
return;
}
@ -80,9 +72,6 @@ class ImprovedTestType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';

View File

@ -25,37 +25,30 @@ class RequireConstructionType extends AbstractType
$this->noThrow = true;
}
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
if ($this->noThrow !== true)
throw new \RuntimeException(__CLASS__ . " require contruction");
if (true !== $this->noThrow) {
throw new \RuntimeException(__CLASS__ . ' require contruction');
}
$builder
->add('a', null, array('description' => 'A nice description'))
->add('a', null, ['description' => 'A nice description'])
;
}
/**
* {@inheritdoc}
*
* @deprecated Remove it when bumping requirements to Symfony 2.7+
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolverInterface $resolver): void
{
$this->configureOptions($resolver);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(array(
$resolver->setDefaults([
'data_class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\Test',
));
]);
return;
}
@ -69,9 +62,6 @@ class RequireConstructionType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'require_construction_type';

View File

@ -22,9 +22,9 @@ use Symfony\Component\Form\FormBuilderInterface;
*/
class RequiredType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('required_field', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType'), array('required' => true));
$builder->add('required_field', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType'), ['required' => true]);
}
/**
@ -36,9 +36,6 @@ class RequiredType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';

View File

@ -22,14 +22,14 @@ use Symfony\Component\Form\FormBuilderInterface;
*/
class SimpleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('a', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType'), array(
$builder->add('a', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType'), [
'description' => 'Something that describes A.',
))
])
->add('b', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\NumberType'))
->add('c', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\ChoiceType'),
array('choices' => array('X' => 'x', 'Y' => 'y', 'Z' => 'z'))
['choices' => ['X' => 'x', 'Y' => 'y', 'Z' => 'z']]
)
->add('d', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\DateTimeType'))
->add('e', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\DateType'))
@ -46,9 +46,6 @@ class SimpleType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'simple';

View File

@ -19,37 +19,29 @@ use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class TestType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('a', null, array('description' => 'A nice description'))
->add('a', null, ['description' => 'A nice description'])
->add('b')
->add($builder->create('c', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\CheckboxType')))
->add('d', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType'),array( 'data' => 'DefaultTest'))
->add('d', LegacyFormHelper::getType('Symfony\Component\Form\Extension\Core\Type\TextType'), ['data' => 'DefaultTest'])
;
}
/**
* {@inheritdoc}
*
* @deprecated Remove it when bumping requirements to Symfony 2.7+
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
public function setDefaultOptions(OptionsResolverInterface $resolver): void
{
$this->configureOptions($resolver);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(array(
$resolver->setDefaults([
'data_class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\Test',
));
]);
return;
}
@ -63,9 +55,6 @@ class TestType extends AbstractType
return $this->getBlockPrefix();
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return '';

View File

@ -11,9 +11,6 @@
namespace Nelmio\ApiDocBundle\Tests\Fixtures\Model;
use Symfony\Component\Validator\Constraints as Assert;
class EntityTest
{
}

View File

@ -11,8 +11,6 @@
namespace Nelmio\ApiDocBundle\Tests\Fixtures\Model;
use Symfony\Component\Validator\Constraints as Assert;
class ImprovedTest
{
public $dt1;

View File

@ -19,5 +19,4 @@ class JmsChild extends JmsTest
* @JMS\Type("string");
*/
public $child;
}

View File

@ -15,9 +15,9 @@ use JMS\Serializer\Annotation as JMS;
class JmsNested
{
/**
* @JMS\Type("DateTime");
*
* @JMS\ReadOnlyProperty
*/
public $foo;
@ -48,19 +48,23 @@ class JmsNested
/**
* @Jms\Type("string")
*
* @Jms\Since("0.2")
*/
public $since;
/**
* @Jms\Type("string")
*
* @Jms\Until("0.3")
*/
public $until;
/**
* @Jms\Type("string")
*
* @Jms\Since("0.4")
*
* @Jms\Until("0.5")
*/
public $sinceAndUntil;

View File

@ -24,12 +24,14 @@ class JmsTest
/**
* @JMS\Type("DateTime");
*
* @JMS\ReadOnlyProperty
*/
public $bar;
/**
* @JMS\Type("double");
*
* @JMS\SerializedName("number");
*/
public $baz;

View File

@ -15,14 +15,10 @@ class JsonSerializableOptionalConstructorTest implements \JsonSerializable
{
public function __construct($optional = null)
{
}
/**
* {@inheritdoc}
*/
public function jsonSerialize(): mixed
{
return array();
return [];
}
}

View File

@ -15,14 +15,10 @@ class JsonSerializableRequiredConstructorTest implements \JsonSerializable
{
public function __construct($required)
{
}
/**
* {@inheritdoc}
*/
public function jsonSerialize(): mixed
{
return array();
return [];
}
}

View File

@ -13,18 +13,15 @@ namespace Nelmio\ApiDocBundle\Tests\Fixtures\Model;
class JsonSerializableTest implements \JsonSerializable
{
/**
* {@inheritdoc}
*/
public function jsonSerialize(): mixed
{
return array(
return [
'id' => 123,
'name' => 'My name',
'child' => array(
'value' => array(1, 2, 3)
),
'another' => new JsonSerializableOptionalConstructorTest()
);
'child' => [
'value' => [1, 2, 3],
],
'another' => new JsonSerializableOptionalConstructorTest(),
];
}
}

View File

@ -25,6 +25,7 @@ class MultipleTest
/**
* @JMS\Type("DateTime")
*
* @JMS\SerializedName("number");
*/
public $baz;
@ -36,7 +37,9 @@ class MultipleTest
/**
* @Assert\Type(type="array")
*
* @Assert\All({
*
* @Assert\Type(type="Test")
* })
*/

View File

@ -17,7 +17,9 @@ class Test
{
/**
* @Assert\Length(min="foo");
*
* @Assert\NotBlank
*
* @Assert\Type("string")
*/
public $a = 'nelmio';

View File

@ -97,13 +97,16 @@ class ValidatorTest
/**
* @Assert\NotNull()
*
* @Assert\Type("string")
*
* @Assert\Email()
*/
public $multipleassertions;
/**
* @Assert\Url()
*
* @Assert\Length(min=10)
*/
public $multipleformats;

View File

@ -21,13 +21,13 @@ class AppKernel extends Kernel
{
public function registerBundles(): iterable
{
$bundles = array(
$bundles = [
new \Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new \Symfony\Bundle\TwigBundle\TwigBundle(),
new \JMS\SerializerBundle\JMSSerializerBundle($this),
new \Nelmio\ApiDocBundle\NelmioApiDocBundle(),
new \Nelmio\ApiDocBundle\Tests\Fixtures\NelmioApiDocTestBundle(),
);
];
if (class_exists('Dunglas\ApiBundle\DunglasApiBundle')) {
$bundles[] = new \Doctrine\Bundle\DoctrineBundle\DoctrineBundle();
@ -52,7 +52,7 @@ class AppKernel extends Kernel
return sys_get_temp_dir() . '/' . Kernel::VERSION . '/nelmio-api-doc/logs';
}
public function registerContainerConfiguration(LoaderInterface $loader)
public function registerContainerConfiguration(LoaderInterface $loader): void
{
$loader->load(__DIR__ . '/config/' . $this->environment . '.yml');
@ -68,11 +68,11 @@ class AppKernel extends Kernel
public function serialize()
{
return serialize(array($this->getEnvironment(), $this->isDebug()));
return serialize([$this->getEnvironment(), $this->isDebug()]);
}
public function unserialize($str)
public function unserialize($str): void
{
call_user_func_array(array($this, '__construct'), unserialize($str));
call_user_func_array([$this, '__construct'], unserialize($str));
}
}

View File

@ -16,12 +16,12 @@ use Nelmio\ApiDocBundle\Util\LegacyFormHelper;
class MarkdownFormatterTest extends WebTestCase
{
public function testFormat()
public function testFormat(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$data = $extractor->all();
restore_error_handler();
$result = $container->get('nelmio_api_doc.formatter.markdown_formatter')->format($data);
@ -35,7 +35,7 @@ class MarkdownFormatterTest extends WebTestCase
$this->assertEquals($expected, $result . "\n");
}
public function testFormatOne()
public function testFormatOne(): void
{
$container = $this->getContainer();

View File

@ -15,12 +15,12 @@ use Nelmio\ApiDocBundle\Tests\WebTestCase;
class SimpleFormatterTest extends WebTestCase
{
public function testFormat()
public function testFormat(): void
{
$container = $this->getContainer();
$extractor = $container->get('nelmio_api_doc.extractor.api_doc_extractor');
set_error_handler(array($this, 'handleDeprecation'));
set_error_handler([$this, 'handleDeprecation']);
$data = $extractor->all();
restore_error_handler();
$result = $container->get('nelmio_api_doc.formatter.simple_formatter')->format($data);
@ -31,7 +31,7 @@ class SimpleFormatterTest extends WebTestCase
$this->assertEquals($expected, $result);
}
public function testFormatOne()
public function testFormatOne(): void
{
$container = $this->getContainer();
@ -39,30 +39,30 @@ class SimpleFormatterTest extends WebTestCase
$annotation = $extractor->get('Nelmio\ApiDocBundle\Tests\Fixtures\Controller\TestController::indexAction', 'test_route_1');
$result = $container->get('nelmio_api_doc.formatter.simple_formatter')->formatOne($annotation);
$expected = array(
$expected = [
'method' => 'GET',
'uri' => '/tests.{_format}',
'filters' => array(
'a' => array(
'filters' => [
'a' => [
'dataType' => 'integer',
),
'b' => array(
],
'b' => [
'dataType' => 'string',
'arbitrary' => array(
'arbitrary' => [
'arg1',
'arg2',
),
),
),
],
],
],
'description' => 'index action',
'requirements' => array(
'_format' => array('dataType' => '', 'description' => '', 'requirement' => ''),
),
'requirements' => [
'_format' => ['dataType' => '', 'description' => '', 'requirement' => ''],
],
'https' => false,
'authentication' => false,
'authenticationRoles' => array(),
'authenticationRoles' => [],
'deprecated' => false,
);
];
$this->assertEquals($expected, $result);
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -29,22 +29,21 @@ class DunglasApiParserTest extends WebTestCase
}
}
public function testParser()
public function testParser(): void
{
$container = $this->getContainer();
$parser = $container->get('nelmio_api_doc.parser.dunglas_api_parser');
$item = array('class' => DunglasApiParser::OUT_PREFIX.':Nelmio\ApiDocBundle\Tests\Fixtures\Model\Popo');
$item = ['class' => DunglasApiParser::OUT_PREFIX . ':Nelmio\ApiDocBundle\Tests\Fixtures\Model\Popo'];
$expected = array (
'foo' =>
array (
$expected = [
'foo' => [
'required' => false,
'description' => '',
'readonly' => false,
'dataType' => DataTypes::STRING,
),
);
],
];
$this->assertTrue($parser->supports($item));
$this->assertEquals($expected, $parser->parse($item));

View File

@ -14,13 +14,11 @@ namespace NelmioApiDocBundle\Tests\Parser;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Form\Extension\DescriptionFormTypeExtension;
use Nelmio\ApiDocBundle\Parser\FormTypeParser;
use Nelmio\ApiDocBundle\Tests\Fixtures;
use Nelmio\ApiDocBundle\Tests\Fixtures\Form\DependencyType;
use Nelmio\ApiDocBundle\Util\LegacyFormHelper;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\Extension\Core\CoreExtension;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\FormFactory;
use Symfony\Component\Form\FormFactoryBuilder;
use Symfony\Component\Form\ResolvedFormTypeFactory;
use Symfony\Component\Translation\Translator;
@ -30,19 +28,19 @@ class FormTypeParserTest extends TestCase
/**
* @dataProvider dataTestParse
*/
public function testParse($typeName, $expected)
public function testParse($typeName, $expected): void
{
$resolvedTypeFactory = new ResolvedFormTypeFactory();
$formFactoryBuilder = new FormFactoryBuilder();
$formFactoryBuilder->setResolvedTypeFactory($resolvedTypeFactory);
$formFactoryBuilder->addExtension(new CoreExtension());
$formFactoryBuilder->addTypeExtension(new DescriptionFormTypeExtension());
$formFactoryBuilder->addType(new DependencyType(array('foo')));
$formFactoryBuilder->addType(new DependencyType(['foo']));
$formFactory = $formFactoryBuilder->getFormFactory();
$formTypeParser = new FormTypeParser($formFactory, new Translator('en'), $entityToChoice = true);
set_error_handler(array('Nelmio\ApiDocBundle\Tests\WebTestCase', 'handleDeprecation'));
trigger_error('test', E_USER_DEPRECATED);
set_error_handler(['Nelmio\ApiDocBundle\Tests\WebTestCase', 'handleDeprecation']);
@trigger_error('test', E_USER_DEPRECATED);
$output = $formTypeParser->parse($typeName);
restore_error_handler();
@ -52,9 +50,10 @@ class FormTypeParserTest extends TestCase
/**
* Checks that we can still use FormType with required arguments without defining them as services.
*
* @dataProvider dataTestParse
*/
public function testLegacyParse($typeName, $expected)
public function testLegacyParse($typeName, $expected): void
{
if (LegacyFormHelper::hasBCBreaks()) {
$this->markTestSkipped('Not supported on symfony 3.0.');
@ -68,8 +67,8 @@ class FormTypeParserTest extends TestCase
$formFactory = $formFactoryBuilder->getFormFactory();
$formTypeParser = new FormTypeParser($formFactory, new Translator('en'), $entityToChoice = true);
set_error_handler(array('Nelmio\ApiDocBundle\Tests\WebTestCase', 'handleDeprecation'));
trigger_error('test', E_USER_DEPRECATED);
set_error_handler(['Nelmio\ApiDocBundle\Tests\WebTestCase', 'handleDeprecation']);
@trigger_error('test', E_USER_DEPRECATED);
$output = $formTypeParser->parse($typeName);
restore_error_handler();
@ -80,19 +79,19 @@ class FormTypeParserTest extends TestCase
/**
* @dataProvider dataTestParseWithoutEntity
*/
public function testParseWithoutEntity($typeName, $expected)
public function testParseWithoutEntity($typeName, $expected): void
{
$resolvedTypeFactory = new ResolvedFormTypeFactory();
$formFactoryBuilder = new FormFactoryBuilder();
$formFactoryBuilder->setResolvedTypeFactory($resolvedTypeFactory);
$formFactoryBuilder->addExtension(new CoreExtension());
$formFactoryBuilder->addTypeExtension(new DescriptionFormTypeExtension());
$formFactoryBuilder->addType(new DependencyType(array('bar')));
$formFactoryBuilder->addType(new DependencyType(['bar']));
$formFactory = $formFactoryBuilder->getFormFactory();
$formTypeParser = new FormTypeParser($formFactory, new Translator('en'), $entityToChoice = false);
set_error_handler(array('Nelmio\ApiDocBundle\Tests\WebTestCase', 'handleDeprecation'));
trigger_error('test', E_USER_DEPRECATED);
set_error_handler(['Nelmio\ApiDocBundle\Tests\WebTestCase', 'handleDeprecation']);
@trigger_error('test', E_USER_DEPRECATED);
$output = $formTypeParser->parse($typeName);
restore_error_handler();
@ -113,7 +112,7 @@ class FormTypeParserTest extends TestCase
protected function expectedData($entityToChoice)
{
$entityData = array_merge(
array(
[
'dataType' => 'choice',
'actualType' => DataTypes::ENUM,
'subType' => null,
@ -121,33 +120,33 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => null,
'readonly' => false,
),
LegacyFormHelper::isLegacy() ? array() : array('format' => '[bar|bazgroup]',)
],
LegacyFormHelper::isLegacy() ? [] : ['format' => '[bar|bazgroup]']
);
return array(
array(
array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\TestType', 'options' => array()),
array(
'a' => array(
return [
[
['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\TestType', 'options' => []],
[
'a' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
'required' => true,
'description' => 'A nice description',
'readonly' => false,
'default' => null
),
'b' => array(
'default' => null,
],
'b' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
'required' => true,
'description' => '',
'readonly' => false,
'default' => null
),
'c' => array(
'default' => null,
],
'c' => [
'dataType' => 'boolean',
'actualType' => DataTypes::BOOLEAN,
'subType' => null,
@ -155,22 +154,22 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'd' => array(
],
'd' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
'required' => true,
'description' => '',
'readonly' => false,
'default' => "DefaultTest"
)
)
),
array(
array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\CollectionType', 'options' => array()),
array(
'collection_type' => array(
'default' => 'DefaultTest',
],
],
],
[
['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\CollectionType', 'options' => []],
[
'collection_type' => [
'dataType' => 'object (CollectionType)',
'actualType' => DataTypes::MODEL,
'subType' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\CollectionType',
@ -178,8 +177,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
'children' => array(
'a' => array(
'children' => [
'a' => [
'dataType' => 'array of strings',
'actualType' => DataTypes::COLLECTION,
'subType' => DataTypes::STRING,
@ -187,8 +186,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'b' => array(
],
'b' => [
'dataType' => 'array of objects (TestType)',
'actualType' => DataTypes::COLLECTION,
'subType' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\TestType',
@ -196,8 +195,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
'children' => array(
'a' => array(
'children' => [
'a' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'default' => null,
@ -205,8 +204,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => 'A nice description',
'readonly' => false,
),
'b' => array(
],
'b' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'default' => null,
@ -214,8 +213,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'c' => array(
],
'c' => [
'dataType' => 'boolean',
'actualType' => DataTypes::BOOLEAN,
'subType' => null,
@ -223,30 +222,30 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'd' => array(
],
'd' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
'required' => true,
'description' => '',
'readonly' => false,
'default' => "DefaultTest"
),
),
),
),
),
),
),
array(
array(
'default' => 'DefaultTest',
],
],
],
],
],
],
],
[
[
'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\CollectionType',
'name' => '',
'options' => array(),
),
array(
'a' => array(
'options' => [],
],
[
'a' => [
'dataType' => 'array of strings',
'actualType' => DataTypes::COLLECTION,
'subType' => DataTypes::STRING,
@ -254,8 +253,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'b' => array(
],
'b' => [
'dataType' => 'array of objects (TestType)',
'actualType' => DataTypes::COLLECTION,
'subType' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\TestType',
@ -263,8 +262,8 @@ class FormTypeParserTest extends TestCase
'description' => '',
'default' => null,
'readonly' => false,
'children' => array(
'a' => array(
'children' => [
'a' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -272,8 +271,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => 'A nice description',
'readonly' => false,
),
'b' => array(
],
'b' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -281,8 +280,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'c' => array(
],
'c' => [
'dataType' => 'boolean',
'actualType' => DataTypes::BOOLEAN,
'subType' => null,
@ -290,28 +289,28 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'd' => array(
],
'd' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
'required' => true,
'description' => '',
'readonly' => false,
'default' => "DefaultTest"
),
),
),
),
),
array(
array(
'default' => 'DefaultTest',
],
],
],
],
],
[
[
'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\CollectionType',
'name' => null,
'options' => array(),
),
array(
'a' => array(
'options' => [],
],
[
'a' => [
'dataType' => 'array of strings',
'actualType' => DataTypes::COLLECTION,
'subType' => DataTypes::STRING,
@ -319,8 +318,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'b' => array(
],
'b' => [
'dataType' => 'array of objects (TestType)',
'actualType' => DataTypes::COLLECTION,
'subType' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\TestType',
@ -328,8 +327,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
'children' => array(
'a' => array(
'children' => [
'a' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -337,8 +336,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => 'A nice description',
'readonly' => false,
),
'b' => array(
],
'b' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -346,8 +345,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'c' => array(
],
'c' => [
'dataType' => 'boolean',
'actualType' => DataTypes::BOOLEAN,
'subType' => null,
@ -355,24 +354,24 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'd' => array(
],
'd' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
'default' => "DefaultTest",
'default' => 'DefaultTest',
'required' => true,
'description' => '',
'readonly' => false
),
),
),
),
),
array(
array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\ImprovedTestType', 'options' => array()),
array(
'dt1' => array(
'readonly' => false,
],
],
],
],
],
[
['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\ImprovedTestType', 'options' => []],
[
'dt1' => [
'dataType' => 'datetime',
'actualType' => DataTypes::DATETIME,
'subType' => null,
@ -381,8 +380,8 @@ class FormTypeParserTest extends TestCase
'description' => 'A nice description',
'readonly' => false,
'format' => DateTimeType::HTML5_FORMAT,
),
'dt2' => array(
],
'dt2' => [
'dataType' => 'datetime',
'actualType' => DataTypes::DATETIME,
'subType' => null,
@ -391,8 +390,8 @@ class FormTypeParserTest extends TestCase
'description' => '',
'readonly' => false,
'format' => 'M/d/y',
),
'dt3' => array(
],
'dt3' => [
'dataType' => 'datetime',
'actualType' => DataTypes::DATETIME,
'subType' => null,
@ -401,8 +400,8 @@ class FormTypeParserTest extends TestCase
'description' => '',
'readonly' => false,
'format' => 'M/d/y H:i:s',
),
'dt4' => array(
],
'dt4' => [
'dataType' => 'datetime',
'actualType' => DataTypes::DATETIME,
'subType' => null,
@ -410,8 +409,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'dt5' => array(
],
'dt5' => [
'dataType' => 'datetime',
'actualType' => DataTypes::DATETIME,
'subType' => null,
@ -419,8 +418,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'd1' => array(
],
'd1' => [
'dataType' => 'date',
'actualType' => DataTypes::DATE,
'subType' => null,
@ -428,8 +427,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'd2' => array(
],
'd2' => [
'dataType' => 'date',
'actualType' => DataTypes::DATE,
'subType' => null,
@ -438,8 +437,8 @@ class FormTypeParserTest extends TestCase
'description' => '',
'readonly' => false,
'format' => 'd-M-y',
),
'c1' => array(
],
'c1' => [
'dataType' => 'choice',
'actualType' => DataTypes::ENUM,
'subType' => null,
@ -448,8 +447,8 @@ class FormTypeParserTest extends TestCase
'description' => '',
'readonly' => false,
'format' => '[Female|Male]',
),
'c2' => array(
],
'c2' => [
'dataType' => 'array of choices',
'actualType' => DataTypes::COLLECTION,
'subType' => DataTypes::ENUM,
@ -458,8 +457,8 @@ class FormTypeParserTest extends TestCase
'description' => '',
'readonly' => false,
'format' => '[Female|Male]',
),
'c3' => array(
],
'c3' => [
'dataType' => 'choice',
'actualType' => DataTypes::ENUM,
'subType' => null,
@ -467,8 +466,8 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
),
'c4' => array(
],
'c4' => [
'dataType' => 'choice',
'actualType' => DataTypes::ENUM,
'subType' => null,
@ -477,15 +476,14 @@ class FormTypeParserTest extends TestCase
'description' => null,
'readonly' => false,
'format' => '[bar|bazgroup]',
),
'e1' => $entityData
),
),
array(
array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\CompoundType', 'options' => array()),
array (
'sub_form' =>
array (
],
'e1' => $entityData,
],
],
[
['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\CompoundType', 'options' => []],
[
'sub_form' => [
'dataType' => 'object (SimpleType)',
'actualType' => 'model',
'subType' => 'Nelmio\\ApiDocBundle\\Tests\\Fixtures\\Form\\SimpleType',
@ -493,87 +491,79 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => '',
'readonly' => false,
'children' =>
array (
'a' =>
array (
'children' => [
'a' => [
'dataType' => 'string',
'actualType' => 'string',
'subType' => NULL,
'subType' => null,
'default' => null,
'required' => true,
'description' => 'Something that describes A.',
'readonly' => false,
),
'b' =>
array (
],
'b' => [
'dataType' => 'float',
'actualType' => 'float',
'subType' => NULL,
'subType' => null,
'default' => null,
'required' => true,
'description' => '',
'readonly' => false,
),
'c' =>
array (
],
'c' => [
'dataType' => 'choice',
'actualType' => 'choice',
'subType' => NULL,
'subType' => null,
'default' => null,
'required' => true,
'description' => '',
'readonly' => false,
'format' => '[X|Y|Z]',
),
'd' =>
array (
],
'd' => [
'dataType' => 'datetime',
'actualType' => 'datetime',
'subType' => NULL,
'subType' => null,
'default' => null,
'required' => true,
'description' => '',
'readonly' => false,
),
'e' =>
array (
],
'e' => [
'dataType' => 'date',
'actualType' => 'date',
'subType' => NULL,
'subType' => null,
'default' => null,
'required' => true,
'description' => '',
'readonly' => false,
),
'g' =>
array (
],
'g' => [
'dataType' => 'string',
'actualType' => 'string',
'subType' => NULL,
'subType' => null,
'default' => null,
'required' => true,
'description' => '',
'readonly' => false,
),
),
),
'a' =>
array (
],
],
],
'a' => [
'dataType' => 'float',
'actualType' => 'float',
'subType' => NULL,
'subType' => null,
'default' => null,
'required' => true,
'description' => '',
'readonly' => false,
),
),
),
array(
array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\RequireConstructionType', 'options' => array()),
array(
'require_construction_type' => array(
],
],
],
[
['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\RequireConstructionType', 'options' => []],
[
'require_construction_type' => [
'dataType' => 'object (RequireConstructionType)',
'required' => true,
'description' => '',
@ -581,8 +571,8 @@ class FormTypeParserTest extends TestCase
'default' => null,
'actualType' => 'model',
'subType' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\RequireConstructionType',
'children' => array(
'a' => array(
'children' => [
'a' => [
'dataType' => 'string',
'actualType' => 'string',
'subType' => null,
@ -590,15 +580,15 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => 'A nice description',
'readonly' => false,
),
),
),
),
),
array(
array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\DependencyType', 'options' => array()),
array(
'dependency_type' => array(
],
],
],
],
],
[
['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\DependencyType', 'options' => []],
[
'dependency_type' => [
'dataType' => 'object (DependencyType)',
'required' => true,
'description' => '',
@ -606,8 +596,8 @@ class FormTypeParserTest extends TestCase
'default' => null,
'actualType' => 'model',
'subType' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Form\DependencyType',
'children' => array(
'a' => array(
'children' => [
'a' => [
'dataType' => 'string',
'actualType' => 'string',
'subType' => null,
@ -615,13 +605,11 @@ class FormTypeParserTest extends TestCase
'required' => true,
'description' => 'A nice description',
'readonly' => false,
),
),
),
),
),
);
],
],
],
],
],
];
}
}

View File

@ -11,12 +11,11 @@
namespace NelmioApiDocBundle\Tests\Parser;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested;
use Nelmio\ApiDocBundle\Parser\JmsMetadataParser;
use JMS\Serializer\Metadata\ClassMetadata;
use JMS\Serializer\Metadata\PropertyMetadata;
use JMS\Serializer\Naming\CamelCaseNamingStrategy;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Parser\JmsMetadataParser;
use PHPUnit\Framework\TestCase;
class JmsMetadataParserTest extends TestCase
@ -24,33 +23,34 @@ class JmsMetadataParserTest extends TestCase
/**
* @dataProvider dataTestParserWithNestedType
*/
public function testParserWithNestedType($type)
public function testParserWithNestedType($type): void
{
$metadataFactory = $this->createMock('Metadata\MetadataFactoryInterface');
$docCommentExtractor = $this->getMockBuilder('Nelmio\ApiDocBundle\Util\DocCommentExtractor')
->disableOriginalConstructor()
->getMock();
->getMock()
;
$propertyMetadataFoo = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'foo');
$propertyMetadataFoo->type = array(
'name' => 'DateTime'
);
$propertyMetadataFoo->type = [
'name' => 'DateTime',
];
$propertyMetadataBar = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'bar');
$propertyMetadataBar->type = array(
'name' => 'string'
);
$propertyMetadataBar->type = [
'name' => 'string',
];
$propertyMetadataBaz = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'baz');
$propertyMetadataBaz->type = array(
$propertyMetadataBaz->type = [
'name' => $type,
'params' => array(
array(
'params' => [
[
'name' => 'integer',
'params' => array()
)
)
);
'params' => [],
],
],
];
$metadata = new ClassMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested');
$metadata->addPropertyMetadata($propertyMetadataFoo);
@ -74,20 +74,21 @@ class JmsMetadataParserTest extends TestCase
$metadataFactory->expects($this->once())
->method('getMetadataForClass')
->with($input)
->will($this->returnValue($metadata));
->willReturn($metadata)
;
$jmsMetadataParser = new JmsMetadataParser($metadataFactory, $propertyNamingStrategy, $docCommentExtractor);
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array(),
)
'groups' => [],
]
);
$this->assertEquals(
array(
'foo' => array(
[
'foo' => [
'dataType' => 'DateTime',
'actualType' => DataTypes::DATETIME,
'subType' => null,
@ -97,8 +98,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'bar' => array(
],
'bar' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -108,8 +109,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'baz' => array(
],
'baz' => [
'dataType' => 'array of integers',
'actualType' => DataTypes::COLLECTION,
'subType' => DataTypes::INTEGER,
@ -119,29 +120,30 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
)
),
],
],
$output
);
}
public function testParserWithGroups()
public function testParserWithGroups(): void
{
$metadataFactory = $this->createMock('Metadata\MetadataFactoryInterface');
$docCommentExtractor = $this->getMockBuilder('Nelmio\ApiDocBundle\Util\DocCommentExtractor')
->disableOriginalConstructor()
->getMock();
->getMock()
;
$propertyMetadataFoo = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'foo');
$propertyMetadataFoo->type = array('name' => 'string');
$propertyMetadataFoo->type = ['name' => 'string'];
$propertyMetadataBar = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'bar');
$propertyMetadataBar->type = array('name' => 'string');
$propertyMetadataBar->groups = array('Default', 'Special');
$propertyMetadataBar->type = ['name' => 'string'];
$propertyMetadataBar->groups = ['Default', 'Special'];
$propertyMetadataBaz = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'baz');
$propertyMetadataBaz->type = array('name' => 'string');
$propertyMetadataBaz->groups = array('Special');
$propertyMetadataBaz->type = ['name' => 'string'];
$propertyMetadataBaz->groups = ['Special'];
$input = 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested';
@ -153,7 +155,8 @@ class JmsMetadataParserTest extends TestCase
$metadataFactory->expects($this->any())
->method('getMetadataForClass')
->with($input)
->will($this->returnValue($metadata));
->willReturn($metadata)
;
$propertyNamingStrategy = new CamelCaseNamingStrategy();
@ -161,15 +164,15 @@ class JmsMetadataParserTest extends TestCase
// No group specified.
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array(),
)
'groups' => [],
]
);
$this->assertEquals(
array(
'foo' => array(
[
'foo' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -179,8 +182,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'bar' => array(
],
'bar' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -190,8 +193,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'baz' => array(
],
'baz' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -201,22 +204,22 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
),
],
],
$output
);
// Default group.
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array('Default'),
)
'groups' => ['Default'],
]
);
$this->assertEquals(
array(
'foo' => array(
[
'foo' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -226,8 +229,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'bar' => array(
],
'bar' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -237,22 +240,22 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
),
],
],
$output
);
// Special group.
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array('Special'),
)
'groups' => ['Special'],
]
);
$this->assertEquals(
array(
'bar' => array(
[
'bar' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -262,8 +265,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'baz' => array(
],
'baz' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -273,22 +276,22 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
),
],
],
$output
);
// Default + Special groups.
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array('Default', 'Special'),
)
'groups' => ['Default', 'Special'],
]
);
$this->assertEquals(
array(
'foo' => array(
[
'foo' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -298,8 +301,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'bar' => array(
],
'bar' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -309,8 +312,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'baz' => array(
],
'baz' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -320,43 +323,44 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
)
),
],
],
$output
);
}
public function testNestedGroups()
public function testNestedGroups(): void
{
$metadataFactory = $this->createMock('Metadata\MetadataFactoryInterface');
$docCommentExtractor = $this->getMockBuilder('Nelmio\ApiDocBundle\Util\DocCommentExtractor')
->disableOriginalConstructor()
->getMock();
->getMock()
;
$input = 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested';
$nestedInput = 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest';
$nestedPropertyMetadataHidden = new PropertyMetadata($nestedInput, 'hidden');
$nestedPropertyMetadataHidden->type = array('name' => 'string');
$nestedPropertyMetadataHidden->groups = array('hidden');
$nestedPropertyMetadataHidden->type = ['name' => 'string'];
$nestedPropertyMetadataHidden->groups = ['hidden'];
$nestedPropertyMetadataFoo = new PropertyMetadata($nestedInput, 'foo');
$nestedPropertyMetadataFoo->type = array('name' => 'string');
$nestedPropertyMetadataFoo->type = ['name' => 'string'];
$nestedMetadata = new ClassMetadata($nestedInput);
$nestedMetadata->addPropertyMetadata($nestedPropertyMetadataHidden);
$nestedMetadata->addPropertyMetadata($nestedPropertyMetadataFoo);
$propertyMetadataFoo = new PropertyMetadata($input, 'foo');
$propertyMetadataFoo->type = array('name' => 'string');
$propertyMetadataFoo->type = ['name' => 'string'];
$propertyMetadataBar = new PropertyMetadata($input, 'bar');
$propertyMetadataBar->type = array('name' => 'string');
$propertyMetadataBar->groups = array('Default');
$propertyMetadataBar->type = ['name' => 'string'];
$propertyMetadataBar->groups = ['Default'];
$propertyMetadataParent = new PropertyMetadata($input, 'parent');
$propertyMetadataParent->type = array('name' => $nestedInput);
$propertyMetadataParent->groups = array('hidden');
$propertyMetadataParent->type = ['name' => $nestedInput];
$propertyMetadataParent->groups = ['hidden'];
$metadata = new ClassMetadata($input);
$metadata->addPropertyMetadata($propertyMetadataFoo);
@ -365,25 +369,26 @@ class JmsMetadataParserTest extends TestCase
$metadataFactory->expects($this->any())
->method('getMetadataForClass')
->will($this->returnValueMap(array(
array($input, $metadata),
array($nestedInput, $nestedMetadata)
)));
->willReturnMap([
[$input, $metadata],
[$nestedInput, $nestedMetadata],
])
;
$propertyNamingStrategy = new CamelCaseNamingStrategy();
$jmsMetadataParser = new JmsMetadataParser($metadataFactory, $propertyNamingStrategy, $docCommentExtractor);
// No group specified.
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array('hidden'),
)
'groups' => ['hidden'],
]
);
$this->assertEquals(
array(
'parent' => array(
[
'parent' => [
'dataType' => 'object (JmsTest)',
'actualType' => DataTypes::MODEL,
'subType' => $nestedInput,
@ -394,8 +399,8 @@ class JmsMetadataParserTest extends TestCase
'sinceVersion' => null,
'untilVersion' => null,
'class' => $nestedInput,
'children' => array(
'hidden' => array(
'children' => [
'hidden' => [
'dataType' => 'string',
'actualType' => 'string',
'subType' => null,
@ -404,31 +409,32 @@ class JmsMetadataParserTest extends TestCase
'description' => null,
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null
)
)
)
),
'untilVersion' => null,
],
],
],
],
$output
);
}
public function testParserWithVersion()
public function testParserWithVersion(): void
{
$metadataFactory = $this->createMock('Metadata\MetadataFactoryInterface');
$docCommentExtractor = $this->getMockBuilder('Nelmio\ApiDocBundle\Util\DocCommentExtractor')
->disableOriginalConstructor()
->getMock();
->getMock()
;
$propertyMetadataFoo = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'foo');
$propertyMetadataFoo->type = array('name' => 'string');
$propertyMetadataFoo->type = ['name' => 'string'];
$propertyMetadataBar = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'bar');
$propertyMetadataBar->type = array('name' => 'string');
$propertyMetadataBar->type = ['name' => 'string'];
$propertyMetadataBar->sinceVersion = '2.0';
$propertyMetadataBaz = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested', 'baz');
$propertyMetadataBaz->type = array('name' => 'string');
$propertyMetadataBaz->type = ['name' => 'string'];
$propertyMetadataBaz->untilVersion = '3.0';
$input = 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsNested';
@ -441,7 +447,8 @@ class JmsMetadataParserTest extends TestCase
$metadataFactory->expects($this->any())
->method('getMetadataForClass')
->with($input)
->will($this->returnValue($metadata));
->willReturn($metadata)
;
$propertyNamingStrategy = new CamelCaseNamingStrategy();
@ -449,15 +456,15 @@ class JmsMetadataParserTest extends TestCase
// No group specified.
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array(),
)
'groups' => [],
]
);
$this->assertEquals(
array(
'foo' => array(
[
'foo' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -467,8 +474,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'bar' => array(
],
'bar' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -478,8 +485,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => '2.0',
'untilVersion' => null,
),
'baz' => array(
],
'baz' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -489,24 +496,25 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => '3.0',
)
),
],
],
$output
);
}
public function testParserWithInline()
public function testParserWithInline(): void
{
$metadataFactory = $this->createMock('Metadata\MetadataFactoryInterface');
$docCommentExtractor = $this->getMockBuilder('Nelmio\ApiDocBundle\Util\DocCommentExtractor')
->disableOriginalConstructor()
->getMock();
->getMock()
;
$propertyMetadataFoo = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsInline', 'foo');
$propertyMetadataFoo->type = array('name' => 'string');
$propertyMetadataFoo->type = ['name' => 'string'];
$propertyMetadataInline = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsInline', 'inline');
$propertyMetadataInline->type = array('name' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest');
$propertyMetadataInline->type = ['name' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest'];
$propertyMetadataInline->inline = true;
$input = 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsInline';
@ -516,7 +524,7 @@ class JmsMetadataParserTest extends TestCase
$metadata->addPropertyMetadata($propertyMetadataInline);
$propertyMetadataBar = new PropertyMetadata('Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest', 'bar');
$propertyMetadataBar->type = array('name' => 'string');
$propertyMetadataBar->type = ['name' => 'string'];
$subInput = 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JmsTest';
@ -535,21 +543,22 @@ class JmsMetadataParserTest extends TestCase
$metadata,
$subMetadata,
$subMetadata
);
)
;
$propertyNamingStrategy = new CamelCaseNamingStrategy();
$jmsMetadataParser = new JmsMetadataParser($metadataFactory, $propertyNamingStrategy, $docCommentExtractor);
$output = $jmsMetadataParser->parse(
array(
[
'class' => $input,
'groups' => array(),
)
'groups' => [],
]
);
$this->assertEquals(
array(
'foo' => array(
[
'foo' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -559,8 +568,8 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
'bar' => array(
],
'bar' => [
'dataType' => 'string',
'actualType' => DataTypes::STRING,
'subType' => null,
@ -570,17 +579,17 @@ class JmsMetadataParserTest extends TestCase
'readonly' => false,
'sinceVersion' => null,
'untilVersion' => null,
),
),
],
],
$output
);
}
public function dataTestParserWithNestedType()
{
return array(
array('array'),
array('ArrayCollection')
);
return [
['array'],
['ArrayCollection'],
];
}
}

View File

@ -21,7 +21,7 @@ class JsonSerializableParserTest extends TestCase
*/
private $parser;
public function setUp(): void
protected function setUp(): void
{
$this->parser = new JsonSerializableParser();
}
@ -29,9 +29,9 @@ class JsonSerializableParserTest extends TestCase
/**
* @dataProvider dataTestParser
*/
public function testParser($property, $expected)
public function testParser($property, $expected): void
{
$result = $this->parser->parse(array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableTest'));
$result = $this->parser->parse(['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableTest']);
foreach ($expected as $name => $value) {
$this->assertArrayHasKey($property, $result);
$this->assertArrayHasKey($name, $result[$property]);
@ -42,34 +42,34 @@ class JsonSerializableParserTest extends TestCase
/**
* @dataProvider dataTestSupports
*/
public function testSupports($class, $expected)
public function testSupports($class, $expected): void
{
$this->assertEquals($this->parser->supports(array('class' => $class)), $expected);
$this->assertEquals($this->parser->supports(['class' => $class]), $expected);
}
public function dataTestParser()
{
return array(
array(
return [
[
'property' => 'id',
'expected' => array(
'expected' => [
'dataType' => 'integer',
'default' => 123
)
),
array(
'default' => 123,
],
],
[
'property' => 'name',
'expected' => array(
'expected' => [
'dataType' => 'string',
'default' => 'My name',
)
),
array(
],
],
[
'property' => 'child',
'expected' => array(
'expected' => [
'dataType' => 'object',
'children' => array(
'value' => array(
'children' => [
'value' => [
'dataType' => 'array',
'actualType' => 'array',
'subType' => null,
@ -77,32 +77,32 @@ class JsonSerializableParserTest extends TestCase
'description' => null,
'readonly' => null,
'default' => null,
)
)
)
)
);
],
],
],
],
];
}
public function dataTestSupports()
{
return array(
array(
return [
[
'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableTest',
'expected' => true
),
array(
'expected' => true,
],
[
'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableRequiredConstructorTest',
'expected' => false
),
array(
'expected' => false,
],
[
'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\JsonSerializableOptionalConstructorTest',
'expected' => true
),
array(
'expected' => true,
],
[
'class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\Popo',
'expected' => false
)
);
'expected' => false,
],
];
}
}

View File

@ -12,9 +12,9 @@
namespace NelmioApiDocBundle\Tests\Parser;
use Nelmio\ApiDocBundle\DataTypes;
use Nelmio\ApiDocBundle\Tests\WebTestCase;
use Nelmio\ApiDocBundle\Parser\ValidationParser;
use Nelmio\ApiDocBundle\Parser\ValidationParserLegacy;
use Nelmio\ApiDocBundle\Tests\WebTestCase;
use Symfony\Component\HttpKernel\Kernel;
class ValidationParserTest extends WebTestCase
@ -22,7 +22,7 @@ class ValidationParserTest extends WebTestCase
protected $handler;
private ValidationParser $parser;
public function setUp(): void
protected function setUp(): void
{
$container = $this->getContainer();
@ -42,9 +42,9 @@ class ValidationParserTest extends WebTestCase
/**
* @dataProvider dataTestParser
*/
public function testParser($property, $expected)
public function testParser($property, $expected): void
{
$result = $this->parser->parse(array('class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\ValidatorTest'));
$result = $this->parser->parse(['class' => 'Nelmio\ApiDocBundle\Tests\Fixtures\Model\ValidatorTest']);
foreach ($expected as $name => $value) {
$this->assertArrayHasKey($property, $result);
$this->assertArrayHasKey($name, $result[$property]);
@ -54,144 +54,144 @@ class ValidationParserTest extends WebTestCase
public function dataTestParser()
{
return array(
array(
return [
[
'property' => 'length10',
'expected' => array(
'expected' => [
'format' => '{length: {min: 10}}',
'default' => 'validate this',
)
),
array(
],
],
[
'property' => 'length1to10',
'expected' => array(
'expected' => [
'format' => '{length: {min: 1, max: 10}}',
'default' => null,
)
),
array(
],
],
[
'property' => 'notblank',
'expected' => array(
'expected' => [
'required' => true,
'default' => null,
)
),
array(
],
],
[
'property' => 'notnull',
'expected' => array(
'expected' => [
'required' => true,
'default' => null,
)
),
array(
],
],
[
'property' => 'type',
'expected' => array(
'expected' => [
'dataType' => 'DateTime',
'actualType' => DataTypes::DATETIME,
'default' => null,
)
),
array(
],
],
[
'property' => 'date',
'expected' => array(
'expected' => [
'format' => '{Date YYYY-MM-DD}',
'actualType' => DataTypes::DATE,
'default' => null,
)
),
array(
],
],
[
'property' => 'dateTime',
'expected' => array(
'expected' => [
'format' => '{DateTime YYYY-MM-DD HH:MM:SS}',
'actualType' => DataTypes::DATETIME,
'default' => null,
)
),
array(
],
],
[
'property' => 'time',
'expected' => array(
'expected' => [
'format' => '{Time HH:MM:SS}',
'actualType' => DataTypes::TIME,
'default' => null,
)
),
array(
],
],
[
'property' => 'email',
'expected' => array(
'expected' => [
'format' => '{email address}',
'default' => null,
)
),
array(
],
],
[
'property' => 'url',
'expected' => array(
'expected' => [
'format' => '{url}',
'default' => 'https://github.com',
)
),
array(
],
],
[
'property' => 'ip',
'expected' => array(
'expected' => [
'format' => '{ip address}',
'default' => null,
)
),
array(
],
],
[
'property' => 'singlechoice',
'expected' => array(
'expected' => [
'format' => '[a|b]',
'actualType' => DataTypes::ENUM,
'default' => null,
)
),
array(
],
],
[
'property' => 'multiplechoice',
'expected' => array(
'expected' => [
'format' => '{choice of [x|y|z]}',
'actualType' => DataTypes::COLLECTION,
'subType' => DataTypes::ENUM,
'default' => null,
)
),
array(
],
],
[
'property' => 'multiplerangechoice',
'expected' => array(
'expected' => [
'format' => '{min: 2 max: 3 choice of [bar|baz|foo|qux]}',
'actualType' => DataTypes::COLLECTION,
'subType' => DataTypes::ENUM,
'default' => null,
)
),
array(
],
],
[
'property' => 'regexmatch',
'expected' => array(
'expected' => [
'format' => '{match: /^\d{1,4}\w{1,4}$/}',
'default' => null,
)
),
array(
],
],
[
'property' => 'regexnomatch',
'expected' => array(
'expected' => [
'format' => '{not match: /\d/}',
'default' => null,
)
),
array(
],
],
[
'property' => 'multipleassertions',
'expected' => array(
'expected' => [
'required' => true,
'dataType' => 'string',
'format' => '{email address}',
'default' => null,
)
),
array(
],
],
[
'property' => 'multipleformats',
'expected' => array(
'expected' => [
'format' => '{url}, {length: {min: 10}}',
'default' => null,
)
)
);
],
],
];
}
}

View File

@ -13,7 +13,6 @@ namespace Nelmio\ApiDocBundle\Tests;
use PHPUnit\Util\ErrorHandler;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\HttpKernel\KernelInterface;
@ -46,13 +45,13 @@ abstract class WebTestCase extends BaseWebTestCase
return 'Nelmio\ApiDocBundle\Tests\Functional\AppKernel';
}
protected static function createKernel(array $options = array()): KernelInterface
protected static function createKernel(array $options = []): KernelInterface
{
$class = self::getKernelClass();
return new $class(
'default',
isset($options['debug']) ? $options['debug'] : true
$options['debug'] ?? true
);
}
}

View File

@ -8,13 +8,13 @@ function includeIfExists($file)
}
if ((!$loader = includeIfExists(__DIR__ . '/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__ . '/../../../../../autoload.php'))) {
die('You must set up the project dependencies, run the following commands:'.PHP_EOL.
exit('You must set up the project dependencies, run the following commands:' . PHP_EOL .
'curl -s http://getcomposer.org/installer | php' . PHP_EOL .
'php composer.phar install' . PHP_EOL);
}
if (class_exists('Doctrine\Common\Annotations\AnnotationRegistry')) {
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(array($loader, 'loadClass'));
Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);
}
// force loading the ApiDoc annotation since the composer target-dir autoloader does not run through $loader::loadClass

View File

@ -14,19 +14,13 @@ class MarkdownExtension extends AbstractExtension
$this->markdownParser = new MarkdownExtra();
}
/**
* {@inheritdoc}
*/
public function getFilters()
{
return array(
new \Twig\TwigFilter('extra_markdown', array($this, 'markdown'), array('is_safe' => array('html'))),
);
return [
new \Twig\TwigFilter('extra_markdown', [$this, 'markdown'], ['is_safe' => ['html']]),
];
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'nelmio_api_doc';

View File

@ -5,7 +5,6 @@ namespace Nelmio\ApiDocBundle\Util;
class DocCommentExtractor
{
/**
* @param \Reflector $reflected
* @return string
*/
public function getDocComment(\Reflector $reflected)
@ -19,13 +18,12 @@ class DocCommentExtractor
$comment = str_replace("\r", '', trim($comment));
$comment = preg_replace("#^\n[ \t]+[*]?#i", "\n", trim($comment));
$comment = preg_replace("#[\t ]+#i", ' ', trim($comment));
$comment = str_replace("\"", "\\\"", $comment);
$comment = str_replace('"', '\\"', $comment);
return $comment;
}
/**
* @param \Reflector $reflected
* @return string
*/
public function getDocCommentText(\Reflector $reflected)
@ -42,5 +40,4 @@ class DocCommentExtractor
return trim($comment);
}
}

View File

@ -18,7 +18,7 @@ namespace Nelmio\ApiDocBundle\Util;
*/
final class LegacyFormHelper
{
private static $map = array(
private static $map = [
'Symfony\Component\Form\Extension\Core\Type\FormType' => 'form',
// Tests
@ -31,7 +31,7 @@ final class LegacyFormHelper
'Symfony\Component\Form\Extension\Core\Type\TextareaType' => 'textarea',
'Symfony\Component\Form\Extension\Core\Type\CheckboxType' => 'checkbox',
'Nelmio\ApiDocBundle\Tests\Fixtures\Form\DependencyType' => 'dependency_type',
);
];
public static function getType($class)
{