From 9b0ff43a944f3c36e41bf04aeb7f787f691aea1f Mon Sep 17 00:00:00 2001 From: Ion Bazan Date: Tue, 1 Mar 2022 18:23:59 +0800 Subject: [PATCH 1/2] use latest PHP 8.0 features --- Command/DumpCommand.php | 31 ++++--- Command/RouterDebugExposedCommand.php | 34 +++---- Controller/Controller.php | 21 ++--- DependencyInjection/Configuration.php | 12 +-- DependencyInjection/FOSJsRoutingExtension.php | 6 +- Extractor/ExposedRoutesExtractor.php | 63 ++++++------- Extractor/ExposedRoutesExtractorInterface.php | 27 +++--- FOSJsRoutingBundle.php | 2 + Response/RoutesResponse.php | 30 +++---- .../RouteCollectionDenormalizer.php | 4 +- .../Normalizer/RouteCollectionNormalizer.php | 26 +++--- .../Normalizer/RoutesResponseNormalizer.php | 20 +++-- Tests/Command/DumpCommandTest.php | 26 +++--- .../Command/RouterDebugExposedCommandTest.php | 20 +++-- Tests/Controller/ControllerTest.php | 90 ++++++++++--------- .../FOSJsRoutingExtensionTest.php | 16 ++-- .../Extractor/ExposedRoutesExtractorTest.php | 68 +++++++------- .../RouteCollectionNormalizerTest.php | 78 ++++++++-------- .../RoutesResponseNormalizerTest.php | 28 +++--- Util/CacheControlConfig.php | 5 +- 20 files changed, 314 insertions(+), 293 deletions(-) diff --git a/Command/DumpCommand.php b/Command/DumpCommand.php index f74291d9..e67008b0 100644 --- a/Command/DumpCommand.php +++ b/Command/DumpCommand.php @@ -1,5 +1,7 @@ getOption('format'), array('js', 'json'))) { + if (!in_array($input->getOption('format'), ['js', 'json'])) { $output->writeln('Invalid format specified. Use js or json.'); + return 1; } $callback = $input->getOption('callback'); - if(empty($callback)) { + if (empty($callback)) { $output->writeln('If you include --callback it must not be empty. Do you perhaps want --format=json'); + return 1; } @@ -98,6 +102,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $output->writeln(''); $this->doDump($input, $output); + return 0; } @@ -114,18 +119,18 @@ private function doDump(InputInterface $input, OutputInterface $output): void sprintf( '%s/web/js/fos_js_routes%s.%s', $this->projectDir, - empty($domain) ? '' : ('_' . implode('_', $domain)), + empty($domain) ? '' : ('_'.implode('_', $domain)), $input->getOption('format') ); - + if (!is_dir($dir = dirname($targetPath))) { - $output->writeln('[dir+] ' . $dir); + $output->writeln('[dir+] '.$dir); if (false === @mkdir($dir, 0777, true)) { - throw new \RuntimeException('Unable to create directory ' . $dir); + throw new \RuntimeException('Unable to create directory '.$dir); } } - $output->writeln('[file+] ' . $targetPath); + $output->writeln('[file+] '.$targetPath); $baseUrl = null !== $this->requestContextBaseUrl ? $this->requestContextBaseUrl : @@ -133,9 +138,9 @@ private function doDump(InputInterface $input, OutputInterface $output): void ; if ($input->getOption('pretty-print')) { - $params = array('json_encode_options' => JSON_PRETTY_PRINT); + $params = ['json_encode_options' => JSON_PRETTY_PRINT]; } else { - $params = array(); + $params = []; } $content = $serializer->serialize( @@ -153,12 +158,12 @@ private function doDump(InputInterface $input, OutputInterface $output): void $params ); - if('js' == $input->getOption('format')) { - $content = sprintf("%s(%s);", $input->getOption('callback'), $content); + if ('js' == $input->getOption('format')) { + $content = sprintf('%s(%s);', $input->getOption('callback'), $content); } if (false === @file_put_contents($targetPath, $content)) { - throw new \RuntimeException('Unable to write file ' . $targetPath); + throw new \RuntimeException('Unable to write file '.$targetPath); } } } diff --git a/Command/RouterDebugExposedCommand.php b/Command/RouterDebugExposedCommand.php index 59c4324c..5fe47108 100644 --- a/Command/RouterDebugExposedCommand.php +++ b/Command/RouterDebugExposedCommand.php @@ -1,5 +1,7 @@ setDefinition(array( + ->setDefinition([ new InputArgument('name', InputArgument::OPTIONAL, 'A route name'), new InputOption('show-controllers', null, InputOption::VALUE_NONE, 'Show assigned controllers in overview'), new InputOption('format', null, InputOption::VALUE_REQUIRED, 'The output format (txt, xml, json, or md)', 'txt'), new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw route(s)'), - new InputOption('domain', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify expose domain', array()) - )) + new InputOption('domain', null, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, 'Specify expose domain', []), + ]) ->setName('fos:js-routing:debug') ->setDescription('Displays currently exposed routes for an application') ->setHelp(<<describe($output, $route, array( - 'format' => $input->getOption('format'), - 'raw_text' => $input->getOption('raw'), + $helper->describe($output, $route, [ + 'format' => $input->getOption('format'), + 'raw_text' => $input->getOption('raw'), 'show_controllers' => $input->getOption('show-controllers'), - )); + ]); } else { $helper = new DescriptorHelper(); - $helper->describe($output, $this->getRoutes($input->getOption('domain')), array( - 'format' => $input->getOption('format'), - 'raw_text' => $input->getOption('raw'), + $helper->describe($output, $this->getRoutes($input->getOption('domain')), [ + 'format' => $input->getOption('format'), + 'raw_text' => $input->getOption('raw'), 'show_controllers' => $input->getOption('show-controllers'), - )); + ]); } + return 0; } - protected function getRoutes($domain = array()): RouteCollection + protected function getRoutes($domain = []): RouteCollection { $routes = $this->extractor->getRoutes(); @@ -108,14 +110,12 @@ protected function getRoutes($domain = array()): RouteCollection $targetRoutes = new RouteCollection(); foreach ($routes as $name => $route) { - $expose = $route->getOption('expose'); - $expose = is_string($expose) ? ($expose === 'true' ? 'default' : $expose) : 'default'; + $expose = is_string($expose) ? ('true' === $expose ? 'default' : $expose) : 'default'; if (in_array($expose, $domain, true)) { $targetRoutes->add($name, $route); } - } return $targetRoutes; diff --git a/Controller/Controller.php b/Controller/Controller.php index 8c6d6177..22f83052 100644 --- a/Controller/Controller.php +++ b/Controller/Controller.php @@ -1,5 +1,7 @@ cacheControlConfig = new CacheControlConfig($cacheControl); + $this->cacheControlConfig = new CacheControlConfig($cacheControl); } public function indexAction(Request $request, $_format): Response @@ -54,13 +55,13 @@ public function indexAction(Request $request, $_format): Response $cache = new ConfigCache($this->exposedRoutesExtractor->getCachePath($request->getLocale()), $this->debug); if (!$cache->isFresh() || $this->debug) { - $exposedRoutes = $this->exposedRoutesExtractor->getRoutes(); + $exposedRoutes = $this->exposedRoutesExtractor->getRoutes(); $serializedRoutes = $this->serializer->serialize($exposedRoutes, 'json'); $cache->write($serializedRoutes, $this->exposedRoutesExtractor->getResources()); } else { $path = method_exists($cache, 'getPath') ? $cache->getPath() : (string) $cache; $serializedRoutes = file_get_contents($path); - $exposedRoutes = $this->serializer->deserialize( + $exposedRoutes = $this->serializer->deserialize( $serializedRoutes, 'Symfony\Component\Routing\RouteCollection', 'json' @@ -75,7 +76,7 @@ public function indexAction(Request $request, $_format): Response $this->exposedRoutesExtractor->getPort(), $this->exposedRoutesExtractor->getScheme(), $request->getLocale(), - $request->query->has('domain') ? explode(',', $request->query->get('domain')) : array() + $request->query->has('domain') ? explode(',', $request->query->get('domain')) : [] ); $content = $this->serializer->serialize($routesResponse, 'json'); @@ -86,10 +87,10 @@ public function indexAction(Request $request, $_format): Response throw new HttpException(400, 'Invalid JSONP callback value'); } - $content = '/**/' . $callback . '(' . $content . ');'; + $content = '/**/'.$callback.'('.$content.');'; } - $response = new Response($content, 200, array('Content-Type' => $request->getMimeType($_format))); + $response = new Response($content, 200, ['Content-Type' => $request->getMimeType($_format)]); $this->cacheControlConfig->apply($response); return $response; diff --git a/DependencyInjection/Configuration.php b/DependencyInjection/Configuration.php index 1697e659..078b6447 100644 --- a/DependencyInjection/Configuration.php +++ b/DependencyInjection/Configuration.php @@ -1,5 +1,7 @@ scalarNode('serializer')->cannotBeEmpty()->end() ->arrayNode('routes_to_expose') ->beforeNormalization() - ->ifTrue(function ($v) { return !is_array($v); }) - ->then(function ($v) { return array($v); }) + ->ifTrue(fn ($v) => !is_array($v)) + ->then(fn ($v) => [$v]) ->end() ->prototype('scalar')->end() ->end() @@ -52,8 +54,8 @@ public function getConfigTreeBuilder(): TreeBuilder ->scalarNode('smaxage')->defaultNull()->end() ->arrayNode('vary') ->beforeNormalization() - ->ifTrue(function ($v) { return !is_array($v); }) - ->then(function ($v) { return array($v); }) + ->ifTrue(fn ($v) => !is_array($v)) + ->then(fn ($v) => [$v]) ->end() ->prototype('scalar')->end() ->end() diff --git a/DependencyInjection/FOSJsRoutingExtension.php b/DependencyInjection/FOSJsRoutingExtension.php index 48c81342..80348355 100644 --- a/DependencyInjection/FOSJsRoutingExtension.php +++ b/DependencyInjection/FOSJsRoutingExtension.php @@ -1,5 +1,7 @@ false); + $config['cache_control'] = ['enabled' => false]; } $container->setParameter('fos_js_routing.cache_control', $config['cache_control']); diff --git a/Extractor/ExposedRoutesExtractor.php b/Extractor/ExposedRoutesExtractor.php index fd20c7ea..1a1e1dc1 100644 --- a/Extractor/ExposedRoutesExtractor.php +++ b/Extractor/ExposedRoutesExtractor.php @@ -1,5 +1,7 @@ @@ -28,14 +30,13 @@ class ExposedRoutesExtractor implements ExposedRoutesExtractorInterface /** * Default constructor. * - * @param array $routesToExpose Some route names to expose. - * @param array $bundles list of loaded bundles to check when generating the prefix + * @param array $routesToExpose some route names to expose + * @param array $bundles list of loaded bundles to check when generating the prefix * * @throws \Exception */ public function __construct(private RouterInterface $router, array $routesToExpose, private string $cacheDir, private array $bundles = []) { - $domainPatterns = $this->extractDomainPatterns($routesToExpose); $this->availableDomains = array_keys($domainPatterns); @@ -49,24 +50,22 @@ public function __construct(private RouterInterface $router, array $routesToExpo public function getRoutes(): RouteCollection { $collection = $this->router->getRouteCollection(); - $routes = new RouteCollection(); + $routes = new RouteCollection(); /** @var Route $route */ foreach ($collection->all() as $name => $route) { - if ($route->hasOption('expose')) { - $expose = $route->getOption('expose'); - if ($expose !== false && $expose !== 'false') { + if (false !== $expose && 'false' !== $expose) { $routes->add($name, $route); } continue; } - preg_match('#^' . $this->pattern . '$#', $name, $matches); + preg_match('#^'.$this->pattern.'$#', $name, $matches); - if (count($matches) === 0) { + if (0 === count($matches)) { continue; } @@ -98,7 +97,7 @@ public function getBaseUrl(): string public function getPrefix(string $locale): string { if (isset($this->bundles['JMSI18nRoutingBundle'])) { - return $locale . I18nLoader::ROUTING_PREFIX; + return $locale.I18nLoader::ROUTING_PREFIX; } return ''; @@ -111,8 +110,8 @@ public function getHost(): string { $requestContext = $this->router->getContext(); - $host = $requestContext->getHost() . - ('' === $this->getPort() ? $this->getPort() : ':' . $this->getPort()); + $host = $requestContext->getHost(). + ('' === $this->getPort() ? $this->getPort() : ':'.$this->getPort()); return $host; } @@ -124,7 +123,7 @@ public function getPort(): ?string { $requestContext = $this->router->getContext(); - $port=""; + $port = ''; if ($this->usesNonStandardPort()) { $method = sprintf('get%sPort', ucfirst($requestContext->getScheme())); $port = $requestContext->$method(); @@ -144,17 +143,17 @@ public function getScheme(): string /** * {@inheritDoc} */ - public function getCachePath(string $locale = NULL): string + public function getCachePath(string $locale = null): string { - $cachePath = $this->cacheDir . DIRECTORY_SEPARATOR . 'fosJsRouting'; + $cachePath = $this->cacheDir.DIRECTORY_SEPARATOR.'fosJsRouting'; if (!file_exists($cachePath)) { mkdir($cachePath); } if (isset($this->bundles['JMSI18nRoutingBundle'])) { - $cachePath = $cachePath . DIRECTORY_SEPARATOR . 'data.' . $locale . '.json'; + $cachePath = $cachePath.DIRECTORY_SEPARATOR.'data.'.$locale.'.json'; } else { - $cachePath = $cachePath . DIRECTORY_SEPARATOR . 'data.json'; + $cachePath = $cachePath.DIRECTORY_SEPARATOR.'data.json'; } return $cachePath; @@ -174,18 +173,17 @@ public function getResources(): array public function isRouteExposed(Route $route, $name): bool { if (false === $route->hasOption('expose')) { - return ('' !== $this->pattern && preg_match('#^' . $this->pattern . '$#', $name)); + return '' !== $this->pattern && preg_match('#^'.$this->pattern.'$#', $name); } $status = $route->getOption('expose'); - return ($status !== false && $status !== 'false'); + + return false !== $status && 'false' !== $status; } protected function getDomainByRouteMatches($matches, $name): int|string|null { - $matches = array_filter($matches, function($match) { - return !empty($match); - }); + $matches = array_filter($matches, fn ($match) => !empty($match)); $matches = array_flip(array_intersect_key($matches, array_flip($this->availableDomains))); @@ -194,17 +192,15 @@ protected function getDomainByRouteMatches($matches, $name): int|string|null protected function extractDomainPatterns($routesToExpose): array { - $domainPatterns = array(); + $domainPatterns = []; foreach ($routesToExpose as $item) { - if (is_string($item)) { $domainPatterns['default'][] = $item; continue; } if (is_array($item) && is_string($item['pattern'])) { - if (!isset($item['domain'])) { $domainPatterns['default'][] = $item['pattern']; continue; @@ -212,7 +208,6 @@ protected function extractDomainPatterns($routesToExpose): array $domainPatterns[$item['domain']][] = $item['pattern']; continue; } - } throw new \Exception('routes_to_expose definition is invalid'); @@ -222,23 +217,23 @@ protected function extractDomainPatterns($routesToExpose): array } /** - * Convert the routesToExpose array in a regular expression pattern + * Convert the routesToExpose array in a regular expression pattern. + * * @throws \Exception */ protected function buildPattern(array $domainPatterns): string { - $patterns = array(); + $patterns = []; foreach ($domainPatterns as $domain => $items) { - - $patterns[] = '(?P<' . $domain . '>' . implode('|', $items) . ')'; + $patterns[] = '(?P<'.$domain.'>'.implode('|', $items).')'; } return implode('|', $patterns); } /** - * Check whether server is serving this request from a non-standard port + * Check whether server is serving this request from a non-standard port. */ private function usesNonStandardPort(): bool { @@ -246,7 +241,7 @@ private function usesNonStandardPort(): bool } /** - * Check whether server is serving HTTP over a non-standard port + * Check whether server is serving HTTP over a non-standard port. */ private function usesNonStandardHttpPort(): bool { @@ -254,7 +249,7 @@ private function usesNonStandardHttpPort(): bool } /** - * Check whether server is serving HTTPS over a non-standard port + * Check whether server is serving HTTPS over a non-standard port. */ private function usesNonStandardHttpsPort(): bool { diff --git a/Extractor/ExposedRoutesExtractorInterface.php b/Extractor/ExposedRoutesExtractorInterface.php index 2a4d0414..dd0b5666 100644 --- a/Extractor/ExposedRoutesExtractorInterface.php +++ b/Extractor/ExposedRoutesExtractorInterface.php @@ -1,5 +1,7 @@ routes = $routes ?: new RouteCollection(); + $this->routes = $routes ?: new RouteCollection(); } public function getBaseUrl(): string @@ -32,19 +34,17 @@ public function getBaseUrl(): string public function getRoutes(): array { - $exposedRoutes = array(); + $exposedRoutes = []; foreach ($this->routes->all() as $name => $route) { - if (!$route->hasOption('expose')) { $domain = 'default'; } else { $domain = $route->getOption('expose'); - $domain = is_string($domain) ? ($domain === 'true' ? 'default' : $domain) : 'default'; + $domain = is_string($domain) ? ('true' === $domain ? 'default' : $domain) : 'default'; } - - if (count($this->domains) === 0) { - if ($domain !== 'default') { + if (0 === count($this->domains)) { + if ('default' !== $domain) { continue; } } elseif (!in_array($domain, $this->domains, true)) { @@ -52,7 +52,7 @@ public function getRoutes(): array } $compiledRoute = $route->compile(); - $defaults = array_intersect_key( + $defaults = array_intersect_key( $route->getDefaults(), array_fill_keys($compiledRoute->getVariables(), null) ); @@ -61,14 +61,14 @@ public function getRoutes(): array $defaults['_locale'] = $this->locale; } - $exposedRoutes[$name] = array( - 'tokens' => $compiledRoute->getTokens(), - 'defaults' => $defaults, + $exposedRoutes[$name] = [ + 'tokens' => $compiledRoute->getTokens(), + 'defaults' => $defaults, 'requirements' => $route->getRequirements(), - 'hosttokens' => method_exists($compiledRoute, 'getHostTokens') ? $compiledRoute->getHostTokens() : array(), - 'methods' => $route->getMethods(), - 'schemes' => $route->getSchemes(), - ); + 'hosttokens' => method_exists($compiledRoute, 'getHostTokens') ? $compiledRoute->getHostTokens() : [], + 'methods' => $route->getMethods(), + 'schemes' => $route->getSchemes(), + ]; } return $exposedRoutes; diff --git a/Serializer/Denormalizer/RouteCollectionDenormalizer.php b/Serializer/Denormalizer/RouteCollectionDenormalizer.php index 79b1ce2e..2f7dcef1 100644 --- a/Serializer/Denormalizer/RouteCollectionDenormalizer.php +++ b/Serializer/Denormalizer/RouteCollectionDenormalizer.php @@ -1,5 +1,7 @@ all() as $name => $route) { - $collection[$name] = array( - 'path' => $route->getPath(), - 'host' => $route->getHost(), - 'defaults' => $route->getDefaults(), + $collection[$name] = [ + 'path' => $route->getPath(), + 'host' => $route->getHost(), + 'defaults' => $route->getDefaults(), 'requirements' => $route->getRequirements(), - 'options' => $route->getOptions(), - 'schemes' => $route->getSchemes(), - 'methods' => $route->getMethods(), - 'condition' => method_exists($route, 'getCondition') ? $route->getCondition() : '', - ); + 'options' => $route->getOptions(), + 'schemes' => $route->getSchemes(), + 'methods' => $route->getMethods(), + 'condition' => method_exists($route, 'getCondition') ? $route->getCondition() : '', + ]; } return $collection; diff --git a/Serializer/Normalizer/RoutesResponseNormalizer.php b/Serializer/Normalizer/RoutesResponseNormalizer.php index e803eece..6a651838 100644 --- a/Serializer/Normalizer/RoutesResponseNormalizer.php +++ b/Serializer/Normalizer/RoutesResponseNormalizer.php @@ -1,5 +1,7 @@ $object->getBaseUrl(), - 'routes' => $object->getRoutes(), - 'prefix' => $object->getPrefix(), - 'host' => $object->getHost(), - 'port' => $object->getPort(), - 'scheme' => $object->getScheme(), - 'locale' => $object->getLocale(), - ); + 'routes' => $object->getRoutes(), + 'prefix' => $object->getPrefix(), + 'host' => $object->getHost(), + 'port' => $object->getPort(), + 'scheme' => $object->getScheme(), + 'locale' => $object->getLocale(), + ]; } /** diff --git a/Tests/Command/DumpCommandTest.php b/Tests/Command/DumpCommandTest.php index 6d8da188..bb722345 100644 --- a/Tests/Command/DumpCommandTest.php +++ b/Tests/Command/DumpCommandTest.php @@ -1,5 +1,7 @@ getMock(); } - public function testExecute() + public function testExecute(): void { $this->serializer->expects($this->once()) ->method('serialize') @@ -45,7 +47,7 @@ public function testExecute() $command = new DumpCommand($this->extractor, $this->serializer, '/root/dir'); $tester = new CommandTester($command); - $tester->execute(array('--target' => '/tmp/dump-command-test')); + $tester->execute(['--target' => '/tmp/dump-command-test']); $this->assertStringContainsString('Dumping exposed routes.', $tester->getDisplay()); $this->assertStringContainsString('[file+] /tmp/dump-command-test', $tester->getDisplay()); @@ -53,7 +55,7 @@ public function testExecute() $this->assertEquals('fos.Router.setData({"base_url":"","routes":{"literal":{"tokens":[["text","\/homepage"]],"defaults":[],"requirements":[],"hosttokens":[]},"blog":{"tokens":[["variable","\/","[^\/]++","slug"],["text","\/blog-post"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]]}},"prefix":"","host":"","scheme":""});', file_get_contents('/tmp/dump-command-test')); } - public function testExecuteCallbackOption() + public function testExecuteCallbackOption(): void { $this->serializer->expects($this->once()) ->method('serialize') @@ -62,10 +64,10 @@ public function testExecuteCallbackOption() $command = new DumpCommand($this->extractor, $this->serializer, '/root/dir'); $tester = new CommandTester($command); - $tester->execute(array( + $tester->execute([ '--target' => '/tmp/dump-command-test', '--callback' => 'test', - )); + ]); $this->assertStringContainsString('Dumping exposed routes.', $tester->getDisplay()); $this->assertStringContainsString('[file+] /tmp/dump-command-test', $tester->getDisplay()); @@ -73,7 +75,7 @@ public function testExecuteCallbackOption() $this->assertEquals('test({"base_url":"","routes":{"literal":{"tokens":[["text","\/homepage"]],"defaults":[],"requirements":[],"hosttokens":[]},"blog":{"tokens":[["variable","\/","[^\/]++","slug"],["text","\/blog-post"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]]}},"prefix":"","host":"","scheme":""});', file_get_contents('/tmp/dump-command-test')); } - public function testExecuteFormatOption() + public function testExecuteFormatOption(): void { $json = '{"base_url":"","routes":{"literal":{"tokens":[["text","\/homepage"]],"defaults":[],"requirements":[],"hosttokens":[]},"blog":{"tokens":[["variable","\/","[^\/]++","slug"],["text","\/blog-post"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]]}},"prefix":"","host":"","scheme":""}'; @@ -84,10 +86,10 @@ public function testExecuteFormatOption() $command = new DumpCommand($this->extractor, $this->serializer, '/root/dir'); $tester = new CommandTester($command); - $tester->execute(array( + $tester->execute([ '--target' => '/tmp/dump-command-test', '--format' => 'json', - )); + ]); $this->assertStringContainsString('Dumping exposed routes.', $tester->getDisplay()); $this->assertStringContainsString('[file+] /tmp/dump-command-test', $tester->getDisplay()); @@ -95,17 +97,17 @@ public function testExecuteFormatOption() $this->assertEquals($json, file_get_contents('/tmp/dump-command-test')); } - public function testExecuteUnableToCreateDirectory() + public function testExecuteUnableToCreateDirectory(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unable to create directory /root/dir/web/js'); $command = new DumpCommand($this->extractor, $this->serializer, '/root/dir'); $tester = new CommandTester($command); - $tester->execute(array()); + $tester->execute([]); } - public function testExecuteUnableToWriteFile() + public function testExecuteUnableToWriteFile(): void { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unable to write file /tmp'); @@ -116,6 +118,6 @@ public function testExecuteUnableToWriteFile() $command = new DumpCommand($this->extractor, $this->serializer, '/root/dir'); $tester = new CommandTester($command); - $tester->execute(array('--target' => '/tmp')); + $tester->execute(['--target' => '/tmp']); } } diff --git a/Tests/Command/RouterDebugExposedCommandTest.php b/Tests/Command/RouterDebugExposedCommandTest.php index bc4ec293..0e604dea 100644 --- a/Tests/Command/RouterDebugExposedCommandTest.php +++ b/Tests/Command/RouterDebugExposedCommandTest.php @@ -1,5 +1,7 @@ getMock(); } - public function testExecute() + public function testExecute(): void { $routes = new RouteCollection(); $routes->add('literal', new Route('/literal')); @@ -47,14 +49,14 @@ public function testExecute() $command = new RouterDebugExposedCommand($this->extractor, $this->router); $tester = new CommandTester($command); - $tester->execute(array()); + $tester->execute([]); $this->assertMatchesRegularExpression('/literal(.*ANY){3}.*\/literal/', $tester->getDisplay()); $this->assertMatchesRegularExpression('/blog_post(.*ANY){3}.*\/blog-post\/{slug}/', $tester->getDisplay()); $this->assertMatchesRegularExpression('/list(.*ANY){3}.*\/literal/', $tester->getDisplay()); } - public function testExecuteWithNameUnknown() + public function testExecuteWithNameUnknown(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The route "foobar" does not exist.'); @@ -70,10 +72,10 @@ public function testExecuteWithNameUnknown() $command = new RouterDebugExposedCommand($this->extractor, $this->router); $tester = new CommandTester($command); - $tester->execute(array('name' => 'foobar')); + $tester->execute(['name' => 'foobar']); } - public function testExecuteWithNameNotExposed() + public function testExecuteWithNameNotExposed(): void { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('The route "literal" was found, but it is not an exposed route.'); @@ -89,13 +91,13 @@ public function testExecuteWithNameNotExposed() $command = new RouterDebugExposedCommand($this->extractor, $this->router); $tester = new CommandTester($command); - $tester->execute(array('name' => 'literal')); + $tester->execute(['name' => 'literal']); } - public function testExecuteWithName() + public function testExecuteWithName(): void { $routes = new RouteCollection(); - $routes->add('literal', new Route('/literal', array(), array(), array('exposed' => true))); + $routes->add('literal', new Route('/literal', [], [], ['exposed' => true])); $routes->add('blog_post', new Route('/blog-post/{slug}')); $routes->add('list', new Route('/literal')); @@ -110,7 +112,7 @@ public function testExecuteWithName() $command = new RouterDebugExposedCommand($this->extractor, $this->router); $tester = new CommandTester($command); - $tester->execute(array('name' => 'literal')); + $tester->execute(['name' => 'literal']); $this->assertStringContainsString('exposed: true', $tester->getDisplay()); } diff --git a/Tests/Controller/ControllerTest.php b/Tests/Controller/ControllerTest.php index 3facde42..11e251f3 100644 --- a/Tests/Controller/ControllerTest.php +++ b/Tests/Controller/ControllerTest.php @@ -1,5 +1,7 @@ cachePath = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'fosJsRouting' . DIRECTORY_SEPARATOR . 'data.json'; + $this->cachePath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'fosJsRouting'.DIRECTORY_SEPARATOR.'data.json'; } public function tearDown(): void @@ -37,11 +39,11 @@ public function tearDown(): void unlink($this->cachePath); } - public function testIndexAction() + public function testIndexAction(): void { $routes = new RouteCollection(); $routes->add('literal', new Route('/homepage')); - $routes->add('blog', new Route('/blog-post/{slug}', array(), array(), array(), 'localhost')); + $routes->add('blog', new Route('/blog-post/{slug}', [], [], [], 'localhost')); $controller = new Controller( $this->getSerializer(), @@ -53,11 +55,11 @@ public function testIndexAction() $this->assertEquals('{"base_url":"","routes":{"literal":{"tokens":[["text","\/homepage"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"blog":{"tokens":[["variable","\/","[^\/]++","slug"],["text","\/blog-post"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); } - public function testIndexWithExplicitTokenAction() + public function testIndexWithExplicitTokenAction(): void { $routes = new RouteCollection(); $routes->add('literal', new Route('/homepage')); - $routes->add('blog', new Route('/blog-post/{!slug}', array(), array(), array(), 'localhost')); + $routes->add('blog', new Route('/blog-post/{!slug}', [], [], [], 'localhost')); $controller = new Controller( $this->getSerializer(), @@ -69,11 +71,11 @@ public function testIndexWithExplicitTokenAction() $this->assertEquals('{"base_url":"","routes":{"literal":{"tokens":[["text","\/homepage"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"blog":{"tokens":[["variable","\/","[^\/]++","slug",false,true],["text","\/blog-post"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); } - public function testIndexActionWithLocalizedRoutes() + public function testIndexActionWithLocalizedRoutes(): void { $routes = new RouteCollection(); $routes->add('literal', new Route('/homepage')); - $routes->add('blog', new Route('/blog-post/{slug}/{_locale}', array(), array(), array(), 'localhost')); + $routes->add('blog', new Route('/blog-post/{slug}/{_locale}', [], [], [], 'localhost')); $controller = new Controller( $this->getSerializer(), @@ -85,7 +87,7 @@ public function testIndexActionWithLocalizedRoutes() $this->assertEquals('{"base_url":"","routes":{"literal":{"tokens":[["text","\/homepage"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"blog":{"tokens":[["variable","\/","[^\/]++","_locale"],["variable","\/","[^\/]++","slug"],["text","\/blog-post"]],"defaults":{"_locale":"en"},"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); } - public function testConfigCache() + public function testConfigCache(): void { $routes = new RouteCollection(); $routes->add('literal', new Route('/homepage')); @@ -106,10 +108,10 @@ public function testConfigCache() /** * @dataProvider dataProviderForTestGenerateWithCallback */ - public function testGenerateWithCallback($callback) + public function testGenerateWithCallback($callback): void { $controller = new Controller($this->getSerializer(), $this->getExtractor()); - $response = $controller->indexAction($this->getRequest('/', 'GET', array('callback' => $callback)), 'json'); + $response = $controller->indexAction($this->getRequest('/', 'GET', ['callback' => $callback]), 'json'); $this->assertEquals( sprintf('/**/%s({"base_url":"","routes":[],"prefix":"","host":"","port":null,"scheme":"","locale":"en"});', $callback), @@ -119,23 +121,23 @@ public function testGenerateWithCallback($callback) public static function dataProviderForTestGenerateWithCallback() { - return array( - array('fos.Router.data'), - array('foo'), - ); + return [ + ['fos.Router.data'], + ['foo'], + ]; } - public function testGenerateWithInvalidCallback() + public function testGenerateWithInvalidCallback(): void { $this->expectException(HttpException::class); $controller = new Controller($this->getSerializer(), $this->getExtractor()); - $controller->indexAction($this->getRequest('/', 'GET', array('callback' => '(function xss(x) {evil()})')), 'json'); + $controller->indexAction($this->getRequest('/', 'GET', ['callback' => '(function xss(x) {evil()})']), 'json'); } - public function testIndexActionWithoutRoutes() + public function testIndexActionWithoutRoutes(): void { - $controller = new Controller($this->getSerializer(), $this->getExtractor(), array(), sys_get_temp_dir()); - $response = $controller->indexAction($this->getRequest('/'), 'json'); + $controller = new Controller($this->getSerializer(), $this->getExtractor(), [], sys_get_temp_dir()); + $response = $controller->indexAction($this->getRequest('/'), 'json'); $this->assertEquals('{"base_url":"","routes":[],"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); $this->assertEquals(200, $response->getStatusCode()); @@ -147,19 +149,19 @@ public function testIndexActionWithoutRoutes() $this->assertFalse($response->headers->hasCacheControlDirective('s-maxage')); } - public function testCacheControl() + public function testCacheControl(): void { - $cacheControlConfig = array( + $cacheControlConfig = [ 'enabled' => true, - 'public' => true, + 'public' => true, 'expires' => '2013-10-04 23:59:59 UTC', - 'maxage' => 123, + 'maxage' => 123, 'smaxage' => 456, - 'vary' => array(), - ); + 'vary' => [], + ]; $controller = new Controller($this->getSerializer(), $this->getExtractor(), $cacheControlConfig, sys_get_temp_dir()); - $response = $controller->indexAction($this->getRequest('/'), 'json'); + $response = $controller->indexAction($this->getRequest('/'), 'json'); $this->assertTrue($response->headers->hasCacheControlDirective('public')); @@ -172,18 +174,18 @@ public function testCacheControl() $this->assertEquals(456, $response->headers->getCacheControlDirective('s-maxage')); } - public function testExposeDomain() + public function testExposeDomain(): void { $routes = new RouteCollection(); $routes->add('homepage', new Route('/')); - $routes->add('admin_index', new Route('/admin', array(), array(), - array('expose' => 'admin'))); - $routes->add('admin_pages', new Route('/admin/path', array(), array(), - array('expose' => 'admin'))); - $routes->add('blog_index', new Route('/blog', array(), array(), - array('expose' => 'blog'), 'localhost')); - $routes->add('blog_post', new Route('/blog/{slug}', array(), array(), - array('expose' => 'blog'), 'localhost')); + $routes->add('admin_index', new Route('/admin', [], [], + ['expose' => 'admin'])); + $routes->add('admin_pages', new Route('/admin/path', [], [], + ['expose' => 'admin'])); + $routes->add('blog_index', new Route('/blog', [], [], + ['expose' => 'blog'], 'localhost')); + $routes->add('blog_post', new Route('/blog/{slug}', [], [], + ['expose' => 'blog'], 'localhost')); $controller = new Controller( $this->getSerializer(), @@ -195,22 +197,22 @@ public function testExposeDomain() $this->assertEquals('{"base_url":"","routes":{"homepage":{"tokens":[["text","\/"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); $response = $controller->indexAction($this->getRequest('/', - 'GET', array('domain' => 'admin')), 'json'); + 'GET', ['domain' => 'admin']), 'json'); $this->assertEquals('{"base_url":"","routes":{"admin_index":{"tokens":[["text","\/admin"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"admin_pages":{"tokens":[["text","\/admin\/path"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); $response = $controller->indexAction($this->getRequest('/', - 'GET', array('domain' => 'blog')), 'json'); + 'GET', ['domain' => 'blog']), 'json'); $this->assertEquals('{"base_url":"","routes":{"blog_index":{"tokens":[["text","\/blog"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]},"blog_post":{"tokens":[["variable","\/","[^\/]++","slug"],["text","\/blog"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); $response = $controller->indexAction($this->getRequest('/', - 'GET', array('domain' => 'admin,blog')), 'json'); + 'GET', ['domain' => 'admin,blog']), 'json'); $this->assertEquals('{"base_url":"","routes":{"admin_index":{"tokens":[["text","\/admin"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"admin_pages":{"tokens":[["text","\/admin\/path"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"blog_index":{"tokens":[["text","\/blog"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]},"blog_post":{"tokens":[["variable","\/","[^\/]++","slug"],["text","\/blog"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); $response = $controller->indexAction($this->getRequest('/', - 'GET', array('domain' => 'default,admin,blog')), 'json'); + 'GET', ['domain' => 'default,admin,blog']), 'json'); $this->assertEquals('{"base_url":"","routes":{"homepage":{"tokens":[["text","\/"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"admin_index":{"tokens":[["text","\/admin"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"admin_pages":{"tokens":[["text","\/admin\/path"]],"defaults":[],"requirements":[],"hosttokens":[],"methods":[],"schemes":[]},"blog_index":{"tokens":[["text","\/blog"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]},"blog_post":{"tokens":[["variable","\/","[^\/]++","slug"],["text","\/blog"]],"defaults":[],"requirements":[],"hosttokens":[["text","localhost"]],"methods":[],"schemes":[]}},"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); } @@ -262,16 +264,16 @@ private function getSerializer() $this->markTestSkipped('The Serializer component is not available.'); } - return new Serializer(array( + return new Serializer([ new RoutesResponseNormalizer(new RouteCollectionNormalizer()), new RouteCollectionNormalizer(), new RouteCollectionDenormalizer(), - ), array( - 'json' => new JsonEncoder() - )); + ], [ + 'json' => new JsonEncoder(), + ]); } - private function getRequest($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null) + private function getRequest($uri, $method = 'GET', $parameters = [], $cookies = [], $files = [], $server = [], $content = null) { return Request::create($uri, $method, $parameters, $cookies, $files, $server, $content); } diff --git a/Tests/DependencyInjection/FOSJsRoutingExtensionTest.php b/Tests/DependencyInjection/FOSJsRoutingExtensionTest.php index d7dc45b9..94ee92aa 100644 --- a/Tests/DependencyInjection/FOSJsRoutingExtensionTest.php +++ b/Tests/DependencyInjection/FOSJsRoutingExtensionTest.php @@ -1,5 +1,7 @@ load(array()); + $container = $this->load([]); $this->assertTrue($container->hasAlias('fos_js_routing.router')); $alias = $container->getAlias('fos_js_routing.router'); @@ -35,9 +37,9 @@ public function testRouterAlias() $this->assertFalse($alias->isPublic()); } - public function testCustomRouterAlias() + public function testCustomRouterAlias(): void { - $container = $this->load(array(array('router' => 'demo_router'))); + $container = $this->load([['router' => 'demo_router']]); $this->assertTrue($container->hasAlias('fos_js_routing.router')); $alias = $container->getAlias('fos_js_routing.router'); @@ -46,12 +48,12 @@ public function testCustomRouterAlias() $this->assertFalse($alias->isPublic()); } - public function testLoadSetupsSerializerIfNotGiven() + public function testLoadSetupsSerializerIfNotGiven(): void { - $container = $this->load(array(array())); + $container = $this->load([[]]); $serializer = $container->get('fos_js_routing.serializer'); - $this->assertEquals('{"foo":"bar"}', $serializer->serialize(array('foo' => 'bar'), 'json')); + $this->assertEquals('{"foo":"bar"}', $serializer->serialize(['foo' => 'bar'], 'json')); } private function load(array $configs) diff --git a/Tests/Extractor/ExposedRoutesExtractorTest.php b/Tests/Extractor/ExposedRoutesExtractorTest.php index 06b270d8..3e3ea2a6 100644 --- a/Tests/Extractor/ExposedRoutesExtractorTest.php +++ b/Tests/Extractor/ExposedRoutesExtractorTest.php @@ -1,5 +1,7 @@ cacheDir = sys_get_temp_dir(); } - public function testGetRoutes() + public function testGetRoutes(): void { $expected = new RouteCollection(); $expected->add('literal', new Route('/literal')); @@ -43,58 +45,58 @@ public function testGetRoutes() $expected->add('list', new Route('/literal')); $router = $this->getRouter($expected); - $extractor = new ExposedRoutesExtractor($router, array('.*'), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, ['.*'], $this->cacheDir, []); - $expected->addOptions(array('expose' => 'default')); + $expected->addOptions(['expose' => 'default']); $this->assertEquals($expected, $extractor->getRoutes()); } - public function testGetRoutesWithPatterns() + public function testGetRoutesWithPatterns(): void { $expected = new RouteCollection(); - $expected->add('hello_you', new Route('/foo', array('_controller' => ''))); - $expected->add('hello_123', new Route('/foo', array('_controller' => ''))); - $expected->add('hello_world', new Route('/foo', array('_controller' => ''))); + $expected->add('hello_you', new Route('/foo', ['_controller' => ''])); + $expected->add('hello_123', new Route('/foo', ['_controller' => ''])); + $expected->add('hello_world', new Route('/foo', ['_controller' => ''])); $router = $this->getRouter($expected); - $extractor = new ExposedRoutesExtractor($router, array('hello_.*'), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, ['hello_.*'], $this->cacheDir, []); $this->assertCount(3, $extractor->getRoutes(), '3 routes match the pattern: "hello_.*"'); - $extractor = new ExposedRoutesExtractor($router, array('hello_[0-9]{3}'), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, ['hello_[0-9]{3}'], $this->cacheDir, []); $this->assertCount(1, $extractor->getRoutes(), '1 routes match the pattern: "hello_[0-9]{3}"'); - $extractor = new ExposedRoutesExtractor($router, array('hello_[0-9]{4}'), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, ['hello_[0-9]{4}'], $this->cacheDir, []); $this->assertCount(0, $extractor->getRoutes(), '1 routes match the pattern: "hello_[0-9]{4}"'); - $extractor = new ExposedRoutesExtractor($router, array('hello_.+o.+'), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, ['hello_.+o.+'], $this->cacheDir, []); $this->assertCount(2, $extractor->getRoutes(), '2 routes match the pattern: "hello_.+o.+"'); - $extractor = new ExposedRoutesExtractor($router, array('hello_.+o.+', 'hello_123'), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, ['hello_.+o.+', 'hello_123'], $this->cacheDir, []); $this->assertCount(3, $extractor->getRoutes(), '3 routes match patterns: "hello_.+o.+" and "hello_123"'); - $extractor = new ExposedRoutesExtractor($router, array('hello_.+o.+', 'hello_$'), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, ['hello_.+o.+', 'hello_$'], $this->cacheDir, []); $this->assertCount(2, $extractor->getRoutes(), '2 routes match patterns: "hello_.+o.+" and "hello_"'); - $extractor = new ExposedRoutesExtractor($router, array(), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, [], $this->cacheDir, []); $this->assertCount(0, $extractor->getRoutes(), 'No patterns so no matched routes'); } - public function testGetCachePath() + public function testGetCachePath(): void { $router = $this->getMockBuilder('Symfony\\Component\\Routing\\Router') ->disableOriginalConstructor() ->getMock(); - $extractor = new ExposedRoutesExtractor($router, array(), $this->cacheDir, array()); - $this->assertEquals($this->cacheDir . DIRECTORY_SEPARATOR . 'fosJsRouting' . DIRECTORY_SEPARATOR . 'data.json', $extractor->getCachePath('')); + $extractor = new ExposedRoutesExtractor($router, [], $this->cacheDir, []); + $this->assertEquals($this->cacheDir.DIRECTORY_SEPARATOR.'fosJsRouting'.DIRECTORY_SEPARATOR.'data.json', $extractor->getCachePath('')); } /** * @dataProvider provideTestGetHostOverHttp */ - public function testGetHostOverHttp($host, $httpPort, $expected) + public function testGetHostOverHttp($host, $httpPort, $expected): void { $requestContext = new RequestContext('/app_dev.php', 'GET', $host, 'http', $httpPort); @@ -105,7 +107,7 @@ public function testGetHostOverHttp($host, $httpPort, $expected) ->method('getContext') ->will($this->returnValue($requestContext)); - $extractor = new ExposedRoutesExtractor($router, array(), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, [], $this->cacheDir, []); $this->assertEquals($expected, $extractor->getHost()); } @@ -115,16 +117,16 @@ public function testGetHostOverHttp($host, $httpPort, $expected) */ public function provideTestGetHostOverHttp() { - return array( - 'HTTP Standard' => array('127.0.0.1', 80, '127.0.0.1'), - 'HTTP Non-Standard' => array('127.0.0.1', 8888, '127.0.0.1:8888'), - ); + return [ + 'HTTP Standard' => ['127.0.0.1', 80, '127.0.0.1'], + 'HTTP Non-Standard' => ['127.0.0.1', 8888, '127.0.0.1:8888'], + ]; } /** * @dataProvider provideTestGetHostOverHttps */ - public function testGetHostOverHttps($host, $httpsPort, $expected) + public function testGetHostOverHttps($host, $httpsPort, $expected): void { $requestContext = new RequestContext('/app_dev.php', 'GET', $host, 'https', 80, $httpsPort); @@ -135,12 +137,12 @@ public function testGetHostOverHttps($host, $httpsPort, $expected) ->method('getContext') ->will($this->returnValue($requestContext)); - $extractor = new ExposedRoutesExtractor($router, array(), $this->cacheDir, array()); + $extractor = new ExposedRoutesExtractor($router, [], $this->cacheDir, []); $this->assertEquals($expected, $extractor->getHost()); } - public function testExposeFalse() + public function testExposeFalse(): void { $expected = new RouteCollection(); $expected->add('user_public_1', new Route('/user/public/1')); @@ -152,18 +154,16 @@ public function testExposeFalse() $expected->add('user_secret_2', new Route('/user/secret/2', [], [], ['expose' => 'false'])); $router = $this->getRouter($expected); - $extractor = new ExposedRoutesExtractor($router, array('user_.+'), $this->cacheDir, []); + $extractor = new ExposedRoutesExtractor($router, ['user_.+'], $this->cacheDir, []); $this->assertCount(5, $extractor->getRoutes()); foreach ($expected->all() as $name => $route) { - if (in_array($name, ['user_secret_1', 'user_secret_2'])) { $this->assertFalse($extractor->isRouteExposed($route, $name)); } else { $this->assertTrue($extractor->isRouteExposed($route, $name)); } - } } @@ -172,14 +172,14 @@ public function testExposeFalse() */ public function provideTestGetHostOverHttps() { - return array( - 'HTTPS Standard' => array('127.0.0.1', 443, '127.0.0.1'), - 'HTTPS Non-Standard' => array('127.0.0.1', 9876, '127.0.0.1:9876'), - ); + return [ + 'HTTPS Standard' => ['127.0.0.1', 443, '127.0.0.1'], + 'HTTPS Non-Standard' => ['127.0.0.1', 9876, '127.0.0.1:9876'], + ]; } /** - * Get a mock object which represents a Router + * Get a mock object which represents a Router. * * @return \Symfony\Component\Routing\Router */ diff --git a/Tests/Serializer/Normalizer/RouteCollectionNormalizerTest.php b/Tests/Serializer/Normalizer/RouteCollectionNormalizerTest.php index ea7108d3..5400bf7a 100644 --- a/Tests/Serializer/Normalizer/RouteCollectionNormalizerTest.php +++ b/Tests/Serializer/Normalizer/RouteCollectionNormalizerTest.php @@ -1,5 +1,7 @@ assertTrue($normalizer->supportsNormalization(new RouteCollection())); } - public function testNormalize() + public function testNormalize(): void { $normalizer = new RouteCollectionNormalizer(); @@ -38,44 +40,44 @@ public function testNormalize() $routes->add('blog_post', new Route('/blog-post/{slug}')); $routes->add('list', new Route('/literal')); - $expected = array( - 'literal' => array( - 'path' => '/literal', - 'host' => '', - 'defaults' => array(), - 'requirements' => array(), - 'options' => array( - 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler' - ), - 'schemes' => array(), - 'methods' => array(), + $expected = [ + 'literal' => [ + 'path' => '/literal', + 'host' => '', + 'defaults' => [], + 'requirements' => [], + 'options' => [ + 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler', + ], + 'schemes' => [], + 'methods' => [], 'condition' => '', - ), - 'blog_post' => array( - 'path' => '/blog-post/{slug}', - 'host' => '', - 'defaults' => array(), - 'requirements' => array(), - 'options' => array( - 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler' - ), - 'schemes' => array(), - 'methods' => array(), + ], + 'blog_post' => [ + 'path' => '/blog-post/{slug}', + 'host' => '', + 'defaults' => [], + 'requirements' => [], + 'options' => [ + 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler', + ], + 'schemes' => [], + 'methods' => [], 'condition' => '', - ), - 'list' => array( - 'path' => '/literal', - 'host' => '', - 'defaults' => array(), - 'requirements' => array(), - 'options' => array( + ], + 'list' => [ + 'path' => '/literal', + 'host' => '', + 'defaults' => [], + 'requirements' => [], + 'options' => [ 'compiler_class' => 'Symfony\Component\Routing\RouteCompiler', - ), - 'schemes' => array(), - 'methods' => array(), + ], + 'schemes' => [], + 'methods' => [], 'condition' => '', - ), - ); + ], + ]; $this->assertSame($expected, $normalizer->normalize($routes)); } diff --git a/Tests/Serializer/Normalizer/RoutesResponseNormalizerTest.php b/Tests/Serializer/Normalizer/RoutesResponseNormalizerTest.php index c73c7b75..0daa830c 100644 --- a/Tests/Serializer/Normalizer/RoutesResponseNormalizerTest.php +++ b/Tests/Serializer/Normalizer/RoutesResponseNormalizerTest.php @@ -1,5 +1,7 @@ getMockBuilder('FOS\JsRoutingBundle\Response\RoutesResponse') + $response = $this->getMockBuilder('FOS\JsRoutingBundle\Response\RoutesResponse') ->disableOriginalConstructor() ->getMock(); @@ -28,16 +30,16 @@ public function testSupportsNormalization() $this->assertTrue($normalizer->supportsNormalization($response)); } - public function testNormalize() + public function testNormalize(): void { $normalizer = new RoutesResponseNormalizer(new RouteCollectionNormalizer()); - $response = $this->getMockBuilder('FOS\JsRoutingBundle\Response\RoutesResponse') + $response = $this->getMockBuilder('FOS\JsRoutingBundle\Response\RoutesResponse') ->disableOriginalConstructor() ->getMock(); $response->expects($this->once()) ->method('getRoutes') - ->will($this->returnValue(array())); + ->will($this->returnValue([])); $response->expects($this->once()) ->method('getBaseUrl') @@ -59,15 +61,15 @@ public function testNormalize() ->method('getLocale') ->will($this->returnValue('locale')); - $expected = array( + $expected = [ 'base_url' => 'baseUrl', - 'routes' => array(), - 'prefix' => 'prefix', - 'host' => 'host', - 'port' => null, - 'scheme' => 'scheme', - 'locale' => 'locale', - ); + 'routes' => [], + 'prefix' => 'prefix', + 'host' => 'host', + 'port' => null, + 'scheme' => 'scheme', + 'locale' => 'locale', + ]; $this->assertSame($expected, $normalizer->normalize($response)); } diff --git a/Util/CacheControlConfig.php b/Util/CacheControlConfig.php index 81a8bb96..14893f53 100644 --- a/Util/CacheControlConfig.php +++ b/Util/CacheControlConfig.php @@ -1,5 +1,7 @@ setSharedMaxAge($this->parameters['smaxage']); } - if ($this->parameters['expires'] !== null) { + if (null !== $this->parameters['expires']) { $response->setExpires(new \DateTime($this->parameters['expires'])); } From 2e5dd9b7811cf0baf845833730d6d9546ec598ff Mon Sep 17 00:00:00 2001 From: Ion Bazan Date: Tue, 1 Mar 2022 18:33:52 +0800 Subject: [PATCH 2/2] fix tests --- Extractor/ExposedRoutesExtractor.php | 2 +- Tests/Controller/ControllerTest.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Extractor/ExposedRoutesExtractor.php b/Extractor/ExposedRoutesExtractor.php index 1a1e1dc1..968f1029 100644 --- a/Extractor/ExposedRoutesExtractor.php +++ b/Extractor/ExposedRoutesExtractor.php @@ -126,7 +126,7 @@ public function getPort(): ?string $port = ''; if ($this->usesNonStandardPort()) { $method = sprintf('get%sPort', ucfirst($requestContext->getScheme())); - $port = $requestContext->$method(); + $port = (string) $requestContext->$method(); } return $port; diff --git a/Tests/Controller/ControllerTest.php b/Tests/Controller/ControllerTest.php index 11e251f3..41608d21 100644 --- a/Tests/Controller/ControllerTest.php +++ b/Tests/Controller/ControllerTest.php @@ -136,7 +136,7 @@ public function testGenerateWithInvalidCallback(): void public function testIndexActionWithoutRoutes(): void { - $controller = new Controller($this->getSerializer(), $this->getExtractor(), [], sys_get_temp_dir()); + $controller = new Controller($this->getSerializer(), $this->getExtractor()); $response = $controller->indexAction($this->getRequest('/'), 'json'); $this->assertEquals('{"base_url":"","routes":[],"prefix":"","host":"","port":null,"scheme":"","locale":"en"}', $response->getContent()); @@ -160,7 +160,7 @@ public function testCacheControl(): void 'vary' => [], ]; - $controller = new Controller($this->getSerializer(), $this->getExtractor(), $cacheControlConfig, sys_get_temp_dir()); + $controller = new Controller($this->getSerializer(), $this->getExtractor(), $cacheControlConfig); $response = $controller->indexAction($this->getRequest('/'), 'json'); $this->assertTrue($response->headers->hasCacheControlDirective('public'));