Turned return type annotations of private methods into php return types.

This commit is contained in:
Alexander M. Turek 2019-08-06 17:03:31 +02:00
parent d3a7be81b4
commit f54ca001fe
106 changed files with 189 additions and 538 deletions

View File

@ -443,11 +443,9 @@ abstract class AbstractDoctrineExtension extends Extension
/**
* Search for a manager that is declared as 'auto_mapping' = true.
*
* @return string|null The name of the manager. If no one manager is found, returns null
*
* @throws \LogicException
*/
private function validateAutoMapping(array $managerConfigs)
private function validateAutoMapping(array $managerConfigs): ?string
{
$autoMappedManager = null;
foreach ($managerConfigs as $name => $manager) {

View File

@ -127,10 +127,8 @@ class RegisterEventListenersAndSubscribersPass implements CompilerPassInterface
*
* @see https://bugs.php.net/bug.php?id=53710
* @see https://bugs.php.net/bug.php?id=60926
*
* @return array
*/
private function findAndSortTags(string $tagName, ContainerBuilder $container)
private function findAndSortTags(string $tagName, ContainerBuilder $container): array
{
$sortedTags = [];

View File

@ -191,12 +191,10 @@ abstract class RegisterMappingsPass implements CompilerPassInterface
/**
* Get the service name from the pattern and the configured manager name.
*
* @return string a service definition name
*
* @throws InvalidArgumentException if none of the managerParameters has a
* non-empty value
*/
private function getConfigurationServiceName(ContainerBuilder $container)
private function getConfigurationServiceName(ContainerBuilder $container): string
{
return sprintf($this->configurationPattern, $this->getManagerName($container));
}
@ -207,11 +205,9 @@ abstract class RegisterMappingsPass implements CompilerPassInterface
* The default implementation loops over the managerParameters and returns
* the first non-empty parameter.
*
* @return string The name of the active manager
*
* @throws InvalidArgumentException if none of the managerParameters is found in the container
*/
private function getManagerName(ContainerBuilder $container)
private function getManagerName(ContainerBuilder $container): string
{
foreach ($this->managerParameters as $param) {
if ($container->hasParameter($param)) {

View File

@ -86,10 +86,8 @@ class EntityType extends DoctrineType
/**
* Converts a query parameter to an array.
*
* @return array The array representation of the parameter
*/
private function parameterToArray(Parameter $parameter)
private function parameterToArray(Parameter $parameter): array
{
return [$parameter->getName(), $parameter->getType(), $parameter->getValue()];
}

View File

@ -47,10 +47,7 @@ final class TestRepositoryFactory implements RepositoryFactory
$this->repositoryList[$repositoryHash] = $repository;
}
/**
* @return ObjectRepository
*/
private function createRepository(EntityManagerInterface $entityManager, string $entityName)
private function createRepository(EntityManagerInterface $entityManager, string $entityName): ObjectRepository
{
/* @var $metadata ClassMetadata */
$metadata = $entityManager->getClassMetadata($entityName);

View File

@ -172,7 +172,7 @@ class ConsoleHandler extends AbstractProcessingHandler implements EventSubscribe
*
* @return bool Whether the handler is enabled and verbosity is not set to quiet
*/
private function updateLevel()
private function updateLevel(): bool
{
if (null === $this->output) {
return false;

View File

@ -97,10 +97,8 @@ class Logger extends BaseLogger implements DebugLoggerInterface, ResetInterface
/**
* Returns a DebugLoggerInterface instance if one is registered with this logger.
*
* @return DebugLoggerInterface|null A DebugLoggerInterface instance or null if none is registered
*/
private function getDebugLogger()
private function getDebugLogger(): ?DebugLoggerInterface
{
foreach ($this->processors as $processor) {
if ($processor instanceof DebugLoggerInterface) {

View File

@ -113,10 +113,7 @@ class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor
return -10;
}
/**
* @return bool
*/
private function isNamedArguments(Node $arguments)
private function isNamedArguments(Node $arguments): bool
{
foreach ($arguments as $name => $node) {
if (!\is_int($name)) {

View File

@ -66,10 +66,7 @@ class LintCommandTest extends TestCase
$this->assertRegExp('/ERROR in \S+ \(line /', trim($tester->getDisplay()));
}
/**
* @return CommandTester
*/
private function createCommandTester()
private function createCommandTester(): CommandTester
{
$command = new LintCommand(new Environment(new FilesystemLoader()));
@ -80,10 +77,7 @@ class LintCommandTest extends TestCase
return new CommandTester($command);
}
/**
* @return string Path to the new file
*/
private function createFile($content)
private function createFile($content): string
{
$filename = tempnam(sys_get_temp_dir(), 'sf-');
file_put_contents($filename, $content);

View File

@ -74,7 +74,7 @@ class SerializerCacheWarmer extends AbstractPhpFileCacheWarmer
*
* @return XmlFileLoader[]|YamlFileLoader[]
*/
private function extractSupportedLoaders(array $loaders)
private function extractSupportedLoaders(array $loaders): array
{
$supportedLoaders = [];

View File

@ -72,7 +72,7 @@ class TemplateFinder implements TemplateFinderInterface
*
* @return TemplateReferenceInterface[]
*/
private function findTemplatesInFolder(string $dir)
private function findTemplatesInFolder(string $dir): array
{
$templates = [];
@ -96,7 +96,7 @@ class TemplateFinder implements TemplateFinderInterface
*
* @return TemplateReferenceInterface[]
*/
private function findTemplatesInBundle(BundleInterface $bundle)
private function findTemplatesInBundle(BundleInterface $bundle): array
{
$name = $bundle->getName();
$templates = array_unique(array_merge(

View File

@ -89,7 +89,7 @@ class ValidatorCacheWarmer extends AbstractPhpFileCacheWarmer
*
* @return XmlFileLoader[]|YamlFileLoader[]
*/
private function extractSupportedLoaders(array $loaders)
private function extractSupportedLoaders(array $loaders): array
{
$supportedLoaders = [];

View File

@ -392,10 +392,7 @@ class MarkdownDescriptor extends Descriptor
throw new \InvalidArgumentException('Callable is not describable.');
}
/**
* @return string
*/
private function formatRouterConfig(array $array)
private function formatRouterConfig(array $array): string
{
if (!$array) {
return 'NONE';

View File

@ -390,7 +390,7 @@ class XmlDescriptor extends Descriptor
/**
* @return \DOMNode[]
*/
private function getArgumentNodes(array $arguments, \DOMDocument $dom)
private function getArgumentNodes(array $arguments, \DOMDocument $dom): array
{
$nodes = [];

View File

@ -41,10 +41,7 @@ class RouterMatchCommandTest extends TestCase
$this->assertStringContainsString('None of the routes match the path "/test"', $tester->getDisplay());
}
/**
* @return CommandTester
*/
private function createCommandTester()
private function createCommandTester(): CommandTester
{
$application = new Application($this->getKernel());
$application->add(new RouterMatchCommand($this->getRouter()));

View File

@ -140,10 +140,7 @@ class TranslationDebugCommandTest extends TestCase
$this->fs->remove($this->translationDir);
}
/**
* @return CommandTester
*/
private function createCommandTester($extractedMessages = [], $loadedMessages = [], $kernel = null, array $transPaths = [], array $viewsPaths = [])
private function createCommandTester($extractedMessages = [], $loadedMessages = [], $kernel = null, array $transPaths = [], array $viewsPaths = []): CommandTester
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()

View File

@ -118,10 +118,7 @@ class TranslationUpdateCommandTest extends TestCase
$this->fs->remove($this->translationDir);
}
/**
* @return CommandTester
*/
private function createCommandTester($extractedMessages = [], $loadedMessages = [], HttpKernel\KernelInterface $kernel = null, array $transPaths = [], array $viewsPaths = [])
private function createCommandTester($extractedMessages = [], $loadedMessages = [], HttpKernel\KernelInterface $kernel = null, array $transPaths = [], array $viewsPaths = []): CommandTester
{
$translator = $this->getMockBuilder('Symfony\Component\Translation\Translator')
->disableOriginalConstructor()

View File

@ -72,10 +72,7 @@ EOF;
$this->assertStringContainsString('[OK] All 0 XLIFF files contain valid syntax', trim($tester->getDisplay()));
}
/**
* @return CommandTester
*/
private function createCommandTester($application = null)
private function createCommandTester($application = null): CommandTester
{
if (!$application) {
$application = new BaseApplication();

View File

@ -109,10 +109,7 @@ EOF;
$this->assertStringContainsString('[OK] All 0 YAML files contain valid syntax', trim($tester->getDisplay()));
}
/**
* @return string Path to the new file
*/
private function createFile($content)
private function createFile($content): string
{
$filename = tempnam(sys_get_temp_dir().'/yml-lint-test', 'sf-');
file_put_contents($filename, $content);
@ -122,10 +119,7 @@ EOF;
return $filename;
}
/**
* @return CommandTester
*/
private function createCommandTester($application = null)
private function createCommandTester($application = null): CommandTester
{
if (!$application) {
$application = new BaseApplication();

View File

@ -98,12 +98,7 @@ abstract class ControllerTraitTest extends TestCase
$controller->getUser();
}
/**
* @param $token
*
* @return Container
*/
private function getContainerWithTokenStorage($token = null)
private function getContainerWithTokenStorage($token = null): Container
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage')->getMock();
$tokenStorage

View File

@ -74,10 +74,7 @@ class ConfigDebugCommandTest extends AbstractWebTestCase
$this->assertStringContainsString("cookie_httponly: '%env(bool:COOKIE_HTTPONLY)%'", $tester->getDisplay());
}
/**
* @return CommandTester
*/
private function createCommandTester()
private function createCommandTester(): CommandTester
{
$command = $this->application->find('debug:config');

View File

@ -73,10 +73,7 @@ EOL
$this->assertStringContainsString('[ERROR] The "path" option is only available for the "yaml" format.', $tester->getDisplay());
}
/**
* @return CommandTester
*/
private function createCommandTester()
private function createCommandTester(): CommandTester
{
$command = $this->application->find('config:dump-reference');

View File

@ -16,6 +16,7 @@ use Psr\Container\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\Config\ContainerParametersResource;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
@ -501,10 +502,7 @@ class RouterTest extends TestCase
return [[null], [false], [true], [new \stdClass()], [['foo', 'bar']], [[[]]]];
}
/**
* @return \Symfony\Component\DependencyInjection\Container
*/
private function getServiceContainer(RouteCollection $routes)
private function getServiceContainer(RouteCollection $routes): Container
{
$loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock();

View File

@ -15,6 +15,11 @@ use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables;
use Symfony\Bundle\FrameworkBundle\Templating\TimedPhpEngine;
use Symfony\Bundle\FrameworkBundle\Tests\TestCase;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\Stopwatch\Stopwatch;
use Symfony\Component\Stopwatch\StopwatchEvent;
use Symfony\Component\Templating\Loader\Loader;
use Symfony\Component\Templating\Storage\StringStorage;
use Symfony\Component\Templating\TemplateNameParserInterface;
/**
* @group legacy
@ -42,18 +47,12 @@ class TimedPhpEngineTest extends TestCase
$engine->render('index.php');
}
/**
* @return Container
*/
private function getContainer()
private function getContainer(): Container
{
return $this->getMockBuilder('Symfony\Component\DependencyInjection\Container')->getMock();
}
/**
* @return \Symfony\Component\Templating\TemplateNameParserInterface
*/
private function getTemplateNameParser()
private function getTemplateNameParser(): TemplateNameParserInterface
{
$templateReference = $this->getMockBuilder('Symfony\Component\Templating\TemplateReferenceInterface')->getMock();
$templateNameParser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock();
@ -64,20 +63,14 @@ class TimedPhpEngineTest extends TestCase
return $templateNameParser;
}
/**
* @return GlobalVariables
*/
private function getGlobalVariables()
private function getGlobalVariables(): GlobalVariables
{
return $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables')
->disableOriginalConstructor()
->getMock();
}
/**
* @return \Symfony\Component\Templating\Storage\StringStorage
*/
private function getStorage()
private function getStorage(): StringStorage
{
return $this->getMockBuilder('Symfony\Component\Templating\Storage\StringStorage')
->disableOriginalConstructor()
@ -85,11 +78,9 @@ class TimedPhpEngineTest extends TestCase
}
/**
* @param \Symfony\Component\Templating\Storage\StringStorage $storage
*
* @return \Symfony\Component\Templating\Loader\Loader
* @param StringStorage $storage
*/
private function getLoader($storage)
private function getLoader($storage): Loader
{
$loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader');
$loader->expects($this->once())
@ -99,20 +90,14 @@ class TimedPhpEngineTest extends TestCase
return $loader;
}
/**
* @return \Symfony\Component\Stopwatch\StopwatchEvent
*/
private function getStopwatchEvent()
private function getStopwatchEvent(): StopwatchEvent
{
return $this->getMockBuilder('Symfony\Component\Stopwatch\StopwatchEvent')
->disableOriginalConstructor()
->getMock();
}
/**
* @return \Symfony\Component\Stopwatch\Stopwatch
*/
private function getStopwatch()
private function getStopwatch(): Stopwatch
{
return $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')->getMock();
}

View File

@ -60,10 +60,7 @@ class FirewallMap implements FirewallMapInterface
return $context->getConfig();
}
/**
* @return FirewallContext|null
*/
private function getFirewallContext(Request $request)
private function getFirewallContext(Request $request): ?FirewallContext
{
if ($request->attributes->has('_firewall_context')) {
$storedContextId = $request->attributes->get('_firewall_context');

View File

@ -102,10 +102,8 @@ class TemplateCacheCacheWarmer implements CacheWarmerInterface, ServiceSubscribe
/**
* Find templates in the given directory.
*
* @return array An array of templates
*/
private function findTemplatesInFolder(?string $namespace, string $dir)
private function findTemplatesInFolder(?string $namespace, string $dir): array
{
if (!is_dir($dir)) {
return [];

View File

@ -113,10 +113,8 @@ class ContentSecurityPolicyHandler
/**
* Updates Content-Security-Policy headers in a response.
*
* @return array
*/
private function updateCspHeaders(Response $response, array $nonces = [])
private function updateCspHeaders(Response $response, array $nonces = []): array
{
$nonces = array_replace([
'csp_script_nonce' => $this->generateNonce(),
@ -161,22 +159,16 @@ class ContentSecurityPolicyHandler
/**
* Generates a valid Content-Security-Policy nonce.
*
* @return string
*/
private function generateNonce()
private function generateNonce(): string
{
return $this->nonceGenerator->generate();
}
/**
* Converts a directive set array into Content-Security-Policy header.
*
* @param array $directives The directive set
*
* @return string The Content-Security-Policy header
*/
private function generateCspHeader(array $directives)
private function generateCspHeader(array $directives): string
{
return array_reduce(array_keys($directives), function ($res, $name) use ($directives) {
return ('' !== $res ? $res.'; ' : '').sprintf('%s %s', $name, implode(' ', $directives[$name]));
@ -185,10 +177,8 @@ class ContentSecurityPolicyHandler
/**
* Converts a Content-Security-Policy header value into a directive set array.
*
* @return array The directive set
*/
private function parseDirectives(string $header)
private function parseDirectives(string $header): array
{
$directives = [];
@ -206,13 +196,8 @@ class ContentSecurityPolicyHandler
/**
* Detects if the 'unsafe-inline' is prevented for a directive within the directive set.
*
* @param array $directivesSet The directive set
* @param string $type The name of the directive to check
*
* @return bool
*/
private function authorizesInline(array $directivesSet, string $type)
private function authorizesInline(array $directivesSet, string $type): bool
{
if (isset($directivesSet[$type])) {
$directives = $directivesSet[$type];
@ -225,7 +210,7 @@ class ContentSecurityPolicyHandler
return \in_array('\'unsafe-inline\'', $directives, true) && !$this->hasHashOrNonce($directives);
}
private function hasHashOrNonce(array $directives)
private function hasHashOrNonce(array $directives): bool
{
foreach ($directives as $directive) {
if ('\'' !== substr($directive, -1)) {
@ -245,10 +230,8 @@ class ContentSecurityPolicyHandler
/**
* Retrieves the Content-Security-Policy headers (either X-Content-Security-Policy or Content-Security-Policy) from
* a response.
*
* @return array An associative array of headers
*/
private function getCspHeaders(Response $response)
private function getCspHeaders(Response $response): array
{
$headers = [];

View File

@ -187,12 +187,13 @@ class ProfilerControllerTest extends TestCase
];
}
private function createController($profiler, $twig, $withCSP)
private function createController($profiler, $twig, $withCSP): ProfilerController
{
$urlGenerator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock();
if ($withCSP) {
$nonceGenerator = $this->getMockBuilder('Symfony\Bundle\WebProfilerBundle\Csp\NonceGenerator')->getMock();
$nonceGenerator->method('generate')->willReturn('dummy_nonce');
return new ProfilerController($urlGenerator, $profiler, $twig, [], new ContentSecurityPolicyHandler($nonceGenerator));
}

View File

@ -149,10 +149,7 @@ class WebServer
return false;
}
/**
* @return Process The process
*/
private function createServerProcess(WebServerConfig $config)
private function createServerProcess(WebServerConfig $config): Process
{
$finder = new PhpExecutableFinder();
if (false === $binary = $finder->find(false)) {

View File

@ -306,10 +306,7 @@ trait MemcachedTrait
throw new CacheException(sprintf('MemcachedAdapter client error: %s.', strtolower($this->client->getResultMessage())));
}
/**
* @return \Memcached
*/
private function getClient()
private function getClient(): \Memcached
{
if ($this->client) {
return $this->client;

View File

@ -76,12 +76,8 @@ class FileLocator implements FileLocatorInterface
/**
* Returns whether the file path is an absolute path.
*
* @param string $file A file path
*
* @return bool
*/
private function isAbsolutePath(string $file)
private function isAbsolutePath(string $file): bool
{
if ('/' === $file[0] || '\\' === $file[0]
|| (\strlen($file) > 3 && ctype_alpha($file[0])

View File

@ -144,10 +144,8 @@ class ResourceCheckerConfigCache implements ConfigCacheInterface
/**
* Gets the meta file path.
*
* @return string The meta file path
*/
private function getMetaFile()
private function getMetaFile(): string
{
return $this->file.'.meta';
}

View File

@ -1030,10 +1030,8 @@ class Application implements ResetInterface
/**
* Returns abbreviated suggestions in string format.
*
* @return string A formatted string of abbreviated suggestions
*/
private function getAbbreviationSuggestions(array $abbrevs)
private function getAbbreviationSuggestions(array $abbrevs): string
{
return ' '.implode("\n ", $abbrevs);
}
@ -1062,7 +1060,7 @@ class Application implements ResetInterface
*
* @return string[] A sorted array of similar string
*/
private function findAlternatives(string $name, iterable $collection)
private function findAlternatives(string $name, iterable $collection): array
{
$threshold = 1e3;
$alternatives = [];
@ -1175,7 +1173,7 @@ class Application implements ResetInterface
*
* @return string[] The namespaces of the command
*/
private function extractAllNamespaces(string $name)
private function extractAllNamespaces(string $name): array
{
// -1 as third argument is needed to skip the command short name when exploding
$parts = explode(':', $name, -1);

View File

@ -29,10 +29,8 @@ trait LockableTrait
/**
* Locks a command.
*
* @return bool
*/
private function lock(string $name = null, bool $blocking = false)
private function lock(string $name = null, bool $blocking = false): bool
{
if (!class_exists(SemaphoreStore::class)) {
throw new LogicException('To enable the locking feature you must install the symfony/lock component.');

View File

@ -100,10 +100,7 @@ class JsonDescriptor extends Descriptor
$this->write(json_encode($data, $flags));
}
/**
* @return array
*/
private function getInputArgumentData(InputArgument $argument)
private function getInputArgumentData(InputArgument $argument): array
{
return [
'name' => $argument->getName(),
@ -114,10 +111,7 @@ class JsonDescriptor extends Descriptor
];
}
/**
* @return array
*/
private function getInputOptionData(InputOption $option)
private function getInputOptionData(InputOption $option): array
{
return [
'name' => '--'.$option->getName(),
@ -130,10 +124,7 @@ class JsonDescriptor extends Descriptor
];
}
/**
* @return array
*/
private function getInputDefinitionData(InputDefinition $definition)
private function getInputDefinitionData(InputDefinition $definition): array
{
$inputArguments = [];
foreach ($definition->getArguments() as $name => $argument) {
@ -148,10 +139,7 @@ class JsonDescriptor extends Descriptor
return ['arguments' => $inputArguments, 'options' => $inputOptions];
}
/**
* @return array
*/
private function getCommandData(Command $command)
private function getCommandData(Command $command): array
{
$command->getSynopsis();
$command->mergeApplicationDefinition(false);

View File

@ -107,10 +107,7 @@ class DebugFormatterHelper extends Helper
return $message;
}
/**
* @return string
*/
private function getBorder(string $id)
private function getBorder(string $id): string
{
return sprintf('<bg=%s> </>', $this->colors[$this->started[$id]['border']]);
}

View File

@ -40,11 +40,9 @@ class StringInput extends ArgvInput
/**
* Tokenizes a string.
*
* @return array An array of tokens
*
* @throws InvalidArgumentException When unable to parse input (should never happen)
*/
private function tokenize(string $input)
private function tokenize(string $input): array
{
$tokens = [];
$length = \strlen($input);

View File

@ -125,10 +125,8 @@ class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
/**
* Checks if current executing environment is IBM iSeries (OS400), which
* doesn't properly convert character-encodings between ASCII to EBCDIC.
*
* @return bool
*/
private function isRunningOS400()
private function isRunningOS400(): bool
{
$checks = [
\function_exists('php_uname') ? php_uname('s') : '',

View File

@ -35,10 +35,8 @@ class ConfirmationQuestion extends Question
/**
* Returns the default answer normalizer.
*
* @return callable
*/
private function getDefaultNormalizer()
private function getDefaultNormalizer(): callable
{
$default = $this->getDefault();
$regex = $this->trueAnswerRegex;

View File

@ -85,7 +85,7 @@ class Terminal
*
* @return int[]|null An array composed of the width and the height or null if it could not be parsed
*/
private static function getConsoleMode()
private static function getConsoleMode(): ?array
{
$info = self::readFromProcess('mode CON');
@ -98,20 +98,13 @@ class Terminal
/**
* Runs and parses stty -a if it's available, suppressing any error output.
*
* @return string|null
*/
private static function getSttyColumns()
private static function getSttyColumns(): ?string
{
return self::readFromProcess('stty -a | grep columns');
}
/**
* @param string $command
*
* @return string|null
*/
private static function readFromProcess($command)
private static function readFromProcess(string $command): ?string
{
if (!\function_exists('proc_open')) {
return null;

View File

@ -505,7 +505,7 @@ class DebugClassLoader
*
* @return string[]
*/
private function getOwnInterfaces(string $class, ?string $parent)
private function getOwnInterfaces(string $class, ?string $parent): array
{
$ownInterfaces = class_implements($class, false);

View File

@ -417,12 +417,8 @@ EOF;
/**
* Formats an array as a string.
*
* @param array $args The argument array
*
* @return string
*/
private function formatArgs(array $args)
private function formatArgs(array $args): string
{
$result = [];
foreach ($args as $key => $item) {

View File

@ -281,9 +281,9 @@ class AutowirePass extends AbstractRecursivePass
}
/**
* @return TypedReference|null A reference to the service matching the given type, if any
* Returns a reference to the service matching the given type, if any.
*/
private function getAutowiredReference(TypedReference $reference)
private function getAutowiredReference(TypedReference $reference): ?TypedReference
{
$this->lastFailure = null;
$type = $reference->getType();

View File

@ -166,10 +166,8 @@ class InlineServiceDefinitionsPass extends AbstractRecursivePass implements Repe
/**
* Checks if the definition is inlineable.
*
* @return bool If the definition is inlineable
*/
private function isInlineableDefinition(string $id, Definition $definition)
private function isInlineableDefinition(string $id, Definition $definition): bool
{
if ($definition->hasErrors() || $definition->isDeprecated() || $definition->isLazy() || $definition->isSynthetic()) {
return false;

View File

@ -256,7 +256,7 @@ class PassConfig
*
* @return CompilerPassInterface[]
*/
private function sortPasses(array $passes)
private function sortPasses(array $passes): array
{
if (0 === \count($passes)) {
return [];

View File

@ -35,11 +35,10 @@ trait PriorityTaggedServiceTrait
* @see https://bugs.php.net/bug.php?id=60926
*
* @param string|TaggedIteratorArgument $tagName
* @param ContainerBuilder $container
*
* @return Reference[]
*/
private function findAndSortTaggedServices($tagName, ContainerBuilder $container)
private function findAndSortTaggedServices($tagName, ContainerBuilder $container): array
{
$indexAttribute = $defaultIndexMethod = $needsIndexes = null;

View File

@ -52,11 +52,9 @@ class ResolveChildDefinitionsPass extends AbstractRecursivePass
/**
* Resolves the definition.
*
* @return Definition
*
* @throws RuntimeException When the definition is invalid
*/
private function resolveDefinition(ChildDefinition $definition)
private function resolveDefinition(ChildDefinition $definition): Definition
{
try {
return $this->doResolveDefinition($definition);
@ -71,7 +69,7 @@ class ResolveChildDefinitionsPass extends AbstractRecursivePass
}
}
private function doResolveDefinition(ChildDefinition $definition)
private function doResolveDefinition(ChildDefinition $definition): Definition
{
if (!$this->container->has($parent = $definition->getParent())) {
throw new RuntimeException(sprintf('Parent definition "%s" does not exist.', $parent));

View File

@ -316,10 +316,8 @@ class XmlDumper extends Dumper
/**
* Escapes arguments.
*
* @return array
*/
private function escape(array $arguments)
private function escape(array $arguments): array
{
$args = [];
foreach ($arguments as $k => $v) {

View File

@ -146,10 +146,8 @@ class XmlFileLoader extends FileLoader
/**
* Get service defaults.
*
* @return array
*/
private function getServiceDefaults(\DOMDocument $xml, string $file)
private function getServiceDefaults(\DOMDocument $xml, string $file): array
{
$xpath = new \DOMXPath($xml);
$xpath->registerNamespace('container', self::NS);
@ -189,10 +187,8 @@ class XmlFileLoader extends FileLoader
/**
* Parses an individual Definition.
*
* @return Definition|null
*/
private function parseDefinition(\DOMElement $service, string $file, array $defaults)
private function parseDefinition(\DOMElement $service, string $file, array $defaults): ?Definition
{
if ($alias = $service->getAttribute('alias')) {
$this->validateAlias($service, $file);
@ -377,11 +373,9 @@ class XmlFileLoader extends FileLoader
/**
* Parses a XML file to a \DOMDocument.
*
* @return \DOMDocument
*
* @throws InvalidArgumentException When loading of XML file returns error
*/
private function parseFileToDOM(string $file)
private function parseFileToDOM(string $file): \DOMDocument
{
try {
$dom = XmlUtils::loadFile($file, [$this, 'validateSchema']);
@ -549,7 +543,7 @@ class XmlFileLoader extends FileLoader
*
* @return \DOMElement[]
*/
private function getChildren(\DOMNode $node, string $name)
private function getChildren(\DOMNode $node, string $name): array
{
$children = [];
foreach ($node->childNodes as $child) {

View File

@ -653,11 +653,9 @@ class YamlFileLoader extends FileLoader
/**
* Validates a YAML file.
*
* @return array
*
* @throws InvalidArgumentException When service file is not valid
*/
private function validate($content, string $file)
private function validate($content, string $file): ?array
{
if (null === $content) {
return $content;

View File

@ -162,10 +162,8 @@ class FormFieldRegistry
/**
* Transforms a PHP array in a list of fully qualified name / value.
*
* @return array The list of fields as [string] Fully qualified name => (mixed) value)
*/
private function walk(array $array, ?string $base = '', array &$output = [])
private function walk(array $array, ?string $base = '', array &$output = []): array
{
foreach ($array as $k => $v) {
$path = empty($base) ? $k : sprintf('%s[%s]', $base, $k);
@ -186,7 +184,7 @@ class FormFieldRegistry
*
* @return string[] The list of segments
*/
private function getSegments(string $name)
private function getSegments(string $name): array
{
if (preg_match('/^(?P<base>[^[]+)(?P<extra>(\[.*)|$)/', $name, $m)) {
$segments = [$m['base']];

View File

@ -294,11 +294,9 @@ class Filesystem
/**
* Tells whether a file exists and is readable.
*
* @return bool
*
* @throws IOException When windows path is longer than 258 characters
*/
private function isReadable(string $filename)
private function isReadable(string $filename): bool
{
$maxPathLength = PHP_MAXPATHLEN - 2;

View File

@ -793,10 +793,8 @@ class Finder implements \IteratorAggregate, \Countable
* Normalizes given directory names by removing trailing slashes.
*
* Excluding: (s)ftp:// wrapper
*
* @return string
*/
private function normalizeDir(string $dir)
private function normalizeDir(string $dir): string
{
$dir = rtrim($dir, '/'.\DIRECTORY_SEPARATOR);

View File

@ -126,10 +126,8 @@ abstract class AbstractRendererEngine implements FormRendererEngineInterface
* Loads the cache with the resource for a specific level of a block hierarchy.
*
* @see getResourceForBlockHierarchy()
*
* @return bool True if the resource could be loaded, false otherwise
*/
private function loadResourceForBlockNameHierarchy(string $cacheKey, FormView $view, array $blockNameHierarchy, $hierarchyLevel)
private function loadResourceForBlockNameHierarchy(string $cacheKey, FormView $view, array $blockNameHierarchy, $hierarchyLevel): bool
{
$blockName = $blockNameHierarchy[$hierarchyLevel];

View File

@ -209,14 +209,8 @@ class ArrayChoiceList implements ChoiceListInterface
* generating duplicates.
* This method is responsible for preventing conflict between scalar values
* and the empty value.
*
* @param array $choices The choices
* @param array|null $cache The cache for previously checked entries. Internal
*
* @return bool returns true if the choices can be cast to strings and
* false otherwise
*/
private function castableToString(array $choices, array &$cache = [])
private function castableToString(array $choices, array &$cache = []): bool
{
foreach ($choices as $choice) {
if (\is_array($choice)) {

View File

@ -178,10 +178,8 @@ class FileType extends AbstractType
* Returns the maximum size of an uploaded file as configured in php.ini.
*
* This method should be kept in sync with Symfony\Component\HttpFoundation\File\UploadedFile::getMaxFilesize().
*
* @return int The maximum size of an uploaded file in bytes
*/
private static function getMaxFilesize()
private static function getMaxFilesize(): int
{
$iniMax = strtolower(ini_get('upload_max_filesize'));

View File

@ -154,10 +154,8 @@ class FormDataExtractor implements FormDataExtractorInterface
/**
* Recursively builds an HTML ID for a form.
*
* @return string The HTML ID
*/
private function buildId(FormInterface $form)
private function buildId(FormInterface $form): string
{
$id = $form->getName();

View File

@ -140,13 +140,8 @@ class ViolationMapper implements ViolationMapperInterface
*
* If a matching child is found, it is returned. Otherwise
* null is returned.
*
* @param FormInterface $form The form to search
* @param PropertyPathIteratorInterface $it The iterator at its current position
*
* @return FormInterface|null The found match or null
*/
private function matchChild(FormInterface $form, PropertyPathIteratorInterface $it)
private function matchChild(FormInterface $form, PropertyPathIteratorInterface $it): ?FormInterface
{
$target = null;
$chunk = '';
@ -211,13 +206,8 @@ class ViolationMapper implements ViolationMapperInterface
/**
* Reconstructs a property path from a violation path and a form tree.
*
* @param ViolationPath $violationPath The violation path
* @param FormInterface $origin The root form of the tree
*
* @return RelativePath The reconstructed path
*/
private function reconstructPath(ViolationPath $violationPath, FormInterface $origin)
private function reconstructPath(ViolationPath $violationPath, FormInterface $origin): ?RelativePath
{
$propertyPathBuilder = new PropertyPathBuilder($violationPath);
$it = $violationPath->getIterator();
@ -268,10 +258,7 @@ class ViolationMapper implements ViolationMapperInterface
return null !== $finalPath ? new RelativePath($origin, $finalPath) : null;
}
/**
* @return bool
*/
private function acceptsErrors(FormInterface $form)
private function acceptsErrors(FormInterface $form): bool
{
return $this->allowNonSynchronized || $form->isSynchronized();
}

View File

@ -272,12 +272,8 @@ class FormErrorIterator implements \RecursiveIterator, \SeekableIterator, \Array
/**
* Utility function for indenting multi-line strings.
*
* @param string $string The string
*
* @return string The indented string
*/
private static function indent($string)
private static function indent(string $string): string
{
return rtrim(self::INDENTATION.str_replace("\n", "\n".self::INDENTATION, $string), ' ');
}

View File

@ -99,14 +99,9 @@ class FormRegistry implements FormRegistryInterface
}
/**
* Wraps a type into a ResolvedFormTypeInterface implementation and connects
* it with its parent type.
*
* @param FormTypeInterface $type The type to resolve
*
* @return ResolvedFormTypeInterface The resolved type
* Wraps a type into a ResolvedFormTypeInterface implementation and connects it with its parent type.
*/
private function resolveType(FormTypeInterface $type)
private function resolveType(FormTypeInterface $type): ResolvedFormTypeInterface
{
$typeExtensions = [];
$parentType = $type->getParent();

View File

@ -84,10 +84,8 @@ class FormTypeGuesserChain implements FormTypeGuesserInterface
*
* @param \Closure $closure The closure to execute. Accepts a guesser
* as argument and should return a Guess instance
*
* @return Guess|null The guess with the highest confidence
*/
private function guess(\Closure $closure)
private function guess(\Closure $closure): ?Guess
{
$guesses = [];

View File

@ -161,10 +161,8 @@ class NativeRequestHandler implements RequestHandlerInterface
/**
* Returns the method used to submit the request to the server.
*
* @return string The request method
*/
private static function getRequestMethod()
private static function getRequestMethod(): string
{
$method = isset($_SERVER['REQUEST_METHOD'])
? strtoupper($_SERVER['REQUEST_METHOD'])

View File

@ -17,6 +17,7 @@ use Symfony\Component\Form\FormRegistry;
use Symfony\Component\Form\FormTypeGuesserChain;
use Symfony\Component\Form\ResolvedFormType;
use Symfony\Component\Form\ResolvedFormTypeFactoryInterface;
use Symfony\Component\Form\ResolvedFormTypeInterface;
use Symfony\Component\Form\Tests\Fixtures\FooSubType;
use Symfony\Component\Form\Tests\Fixtures\FooType;
use Symfony\Component\Form\Tests\Fixtures\FooTypeBarExtension;
@ -206,6 +207,11 @@ class FormRegistryTest extends TestCase
public function testHasTypeIfFQCN()
{
$this->resolvedTypeFactory
->expects($this->any())
->method('createResolvedType')
->will($this->returnValue($this->createMock(ResolvedFormTypeInterface::class)));
$this->assertTrue($this->registry->hasType('Symfony\Component\Form\Tests\Fixtures\FooType'));
}

View File

@ -384,26 +384,17 @@ class ResolvedFormTypeTest extends TestCase
];
}
/**
* @return MockObject
*/
private function getMockFormType($typeClass = 'Symfony\Component\Form\AbstractType')
private function getMockFormType($typeClass = 'Symfony\Component\Form\AbstractType'): MockObject
{
return $this->getMockBuilder($typeClass)->setMethods(['getBlockPrefix', 'configureOptions', 'finishView', 'buildView', 'buildForm'])->getMock();
}
/**
* @return MockObject
*/
private function getMockFormTypeExtension()
private function getMockFormTypeExtension(): MockObject
{
return $this->getMockBuilder('Symfony\Component\Form\AbstractTypeExtension')->setMethods(['getExtendedType', 'configureOptions', 'finishView', 'buildView', 'buildForm'])->getMock();
}
/**
* @return MockObject
*/
private function getMockFormFactory()
private function getMockFormFactory(): MockObject
{
return $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock();
}

View File

@ -251,10 +251,8 @@ class UploadedFile extends File
/**
* Returns the given size from an ini value in bytes.
*
* @return int The given size in bytes
*/
private static function parseFilesize($size)
private static function parseFilesize($size): int
{
if ('' === $size) {
return 0;

View File

@ -267,10 +267,8 @@ class Session implements SessionInterface, \IteratorAggregate, \Countable
* Gets the attributebag interface.
*
* Note that this method was added to help with IDE autocompletion.
*
* @return AttributeBagInterface
*/
private function getAttributeBag()
private function getAttributeBag(): AttributeBagInterface
{
return $this->getBag($this->attributeName);
}

View File

@ -171,10 +171,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
return $dbData[$this->options['data_field']]->getData();
}
/**
* @return \MongoDB\Collection
*/
private function getCollection()
private function getCollection(): \MongoDB\Collection
{
if (null === $this->collection) {
$this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']);

View File

@ -434,11 +434,9 @@ class PdoSessionHandler extends AbstractSessionHandler
/**
* Builds a PDO DSN from a URL-like connection string.
*
* @return string
*
* @todo implement missing support for oci DSN (which look totally different from other PDO ones)
*/
private function buildDsnFromUrl(string $dsnOrUrl)
private function buildDsnFromUrl(string $dsnOrUrl): string
{
// (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
$url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl);
@ -672,7 +670,7 @@ class PdoSessionHandler extends AbstractSessionHandler
* - for oci using DBMS_LOCK.REQUEST
* - for sqlsrv using sp_getapplock with LockOwner = Session
*/
private function doAdvisoryLock(string $sessionId)
private function doAdvisoryLock(string $sessionId): \PDOStatement
{
switch ($this->driver) {
case 'mysql':
@ -770,10 +768,8 @@ class PdoSessionHandler extends AbstractSessionHandler
/**
* Returns an insert statement supported by the database for writing session data.
*
* @return \PDOStatement The insert statement
*/
private function getInsertStatement(string $sessionId, string $sessionData, int $maxlifetime)
private function getInsertStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
{
switch ($this->driver) {
case 'oci':
@ -799,10 +795,8 @@ class PdoSessionHandler extends AbstractSessionHandler
/**
* Returns an update statement supported by the database for writing session data.
*
* @return \PDOStatement The update statement
*/
private function getUpdateStatement(string $sessionId, string $sessionData, int $maxlifetime)
private function getUpdateStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
{
switch ($this->driver) {
case 'oci':

View File

@ -131,10 +131,8 @@ class MockFileSessionStorage extends MockArraySessionStorage
/**
* Calculate path to file.
*
* @return string File path
*/
private function getFilePath()
private function getFilePath(): string
{
return $this->savePath.'/'.$this->id.'.mocksess';
}

View File

@ -336,7 +336,7 @@ class ConfigDataCollector extends DataCollector implements LateDataCollectorInte
*
* @return string One of: dev, stable, eom, eol
*/
private function determineSymfonyState()
private function determineSymfonyState(): string
{
$now = new \DateTime();
$eom = \DateTime::createFromFormat('m/Y', Kernel::END_OF_MAINTENANCE)->modify('last day of this month');

View File

@ -54,10 +54,8 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
*
* @param array $patterns The class patterns to expand
* @param array $classes The existing classes to match against the patterns
*
* @return array A list of classes derived from the patterns
*/
private function expandClasses(array $patterns, array $classes)
private function expandClasses(array $patterns, array $classes): array
{
$expanded = [];

View File

@ -635,10 +635,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface
/**
* Checks if the Request includes authorization or other sensitive information
* that should cause the Response to be considered private by default.
*
* @return bool true if the Request is private, false otherwise
*/
private function isPrivateRequest(Request $request)
private function isPrivateRequest(Request $request): bool
{
foreach ($this->options['private_headers'] as $key) {
$key = strtolower(str_replace('HTTP_', '', $key));

View File

@ -156,10 +156,8 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface
* RFC2616, Section 13.4.
*
* @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.4
*
* @return bool
*/
private function willMakeFinalResponseUncacheable(Response $response)
private function willMakeFinalResponseUncacheable(Response $response): bool
{
// RFC2616: A response received with a status code of 200, 203, 300, 301 or 410
// MAY be stored by a cache […] unless a cache-control directive prohibits caching.

View File

@ -259,10 +259,8 @@ class Store implements StoreInterface
* @param string $vary A Response vary header
* @param array $env1 A Request HTTP header array
* @param array $env2 A Request HTTP header array
*
* @return bool true if the two environments match, false otherwise
*/
private function requestsMatch(?string $vary, array $env1, array $env2)
private function requestsMatch(?string $vary, array $env1, array $env2): bool
{
if (empty($vary)) {
return true;
@ -284,10 +282,8 @@ class Store implements StoreInterface
* Gets all data associated with the given key.
*
* Use this method only if you know what you are doing.
*
* @return array An array of data associated with the key
*/
private function getMetadata(string $key)
private function getMetadata(string $key): array
{
if (!$entries = $this->load($key)) {
return [];
@ -318,10 +314,8 @@ class Store implements StoreInterface
/**
* Purges data for the given URL.
*
* @return bool true if the URL exists and has been purged, false otherwise
*/
private function doPurge(string $url)
private function doPurge(string $url): bool
{
$key = $this->getCacheKey(Request::create($url));
if (isset($this->locks[$key])) {
@ -341,10 +335,8 @@ class Store implements StoreInterface
/**
* Loads data for the given key.
*
* @return string|null The data associated with the key
*/
private function load(string $key)
private function load(string $key): ?string
{
$path = $this->getPath($key);
@ -353,10 +345,8 @@ class Store implements StoreInterface
/**
* Save data for the given key.
*
* @return bool
*/
private function save(string $key, string $data)
private function save(string $key, string $data): bool
{
$path = $this->getPath($key);
@ -426,10 +416,8 @@ class Store implements StoreInterface
/**
* Returns a cache key for the given Request.
*
* @return string A key for the given Request
*/
private function getCacheKey(Request $request)
private function getCacheKey(Request $request): string
{
if (isset($this->keyCache[$request])) {
return $this->keyCache[$request];
@ -440,20 +428,16 @@ class Store implements StoreInterface
/**
* Persists the Request HTTP headers.
*
* @return array An array of HTTP headers
*/
private function persistRequest(Request $request)
private function persistRequest(Request $request): array
{
return $request->headers->all();
}
/**
* Persists the Response HTTP headers.
*
* @return array An array of HTTP headers
*/
private function persistResponse(Response $response)
private function persistResponse(Response $response): array
{
$headers = $response->headers->all();
$headers['X-Status'] = [$response->getStatusCode()];
@ -463,10 +447,8 @@ class Store implements StoreInterface
/**
* Restores a Response from the HTTP headers and body.
*
* @return Response
*/
private function restoreResponse(array $headers, string $body = null)
private function restoreResponse(array $headers, string $body = null): Response
{
$status = $headers['X-Status'][0];
unset($headers['X-Status']);

View File

@ -177,11 +177,9 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface
* @param Request $request An error message in case the response is not a Response object
* @param int $type The type of the request (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
*
* @return Response The filtered Response instance
*
* @throws \RuntimeException if the passed object is not a Response instance
*/
private function filterResponse(Response $response, Request $request, int $type)
private function filterResponse(Response $response, Request $request, int $type): Response
{
$event = new ResponseEvent($this, $request, $type, $response);

View File

@ -130,10 +130,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
return $data;
}
/**
* @return array
*/
private function generateSymbolNamePairs(ArrayAccessibleResourceBundle $rootBundle)
private function generateSymbolNamePairs(ArrayAccessibleResourceBundle $rootBundle): array
{
$symbolNamePairs = iterator_to_array($rootBundle['Currencies']);
@ -143,14 +140,14 @@ class CurrencyDataGenerator extends AbstractDataGenerator
return $symbolNamePairs;
}
private function generateCurrencyMeta(ArrayAccessibleResourceBundle $supplementalDataBundle)
private function generateCurrencyMeta(ArrayAccessibleResourceBundle $supplementalDataBundle): array
{
// The metadata is already de-duplicated. It contains one key "DEFAULT"
// which is used for currencies that don't have dedicated entries.
return iterator_to_array($supplementalDataBundle['CurrencyMeta']);
}
private function generateAlpha3ToNumericMapping(ArrayAccessibleResourceBundle $numericCodesBundle, array $currencyCodes)
private function generateAlpha3ToNumericMapping(ArrayAccessibleResourceBundle $numericCodesBundle, array $currencyCodes): array
{
$alpha3ToNumericMapping = iterator_to_array($numericCodesBundle['codeMap']);
@ -162,7 +159,7 @@ class CurrencyDataGenerator extends AbstractDataGenerator
return $alpha3ToNumericMapping;
}
private function generateNumericToAlpha3Mapping(array $alpha3ToNumericMapping)
private function generateNumericToAlpha3Mapping(array $alpha3ToNumericMapping): array
{
$numericToAlpha3Mapping = [];

View File

@ -148,10 +148,7 @@ class LocaleDataGenerator extends AbstractDataGenerator
];
}
/**
* @return string
*/
private function generateLocaleName(BundleEntryReaderInterface $reader, string $tempDir, string $locale, string $displayLocale, string $pattern, string $separator)
private function generateLocaleName(BundleEntryReaderInterface $reader, string $tempDir, string $locale, string $displayLocale, string $pattern, string $separator): string
{
// Apply generic notation using square brackets as described per http://cldr.unicode.org/translation/language-names
$name = str_replace(['(', ')'], ['[', ']'], $reader->readEntry($tempDir.'/lang', $displayLocale, ['Languages', \Locale::getPrimaryLanguage($locale)]));

View File

@ -327,10 +327,8 @@ class FullTransformer
/**
* Add sensible default values for missing items in the extracted date/time options array. The values
* are base in the beginning of the Unix era.
*
* @return array
*/
private function getDefaultValueForOptions(array $options)
private function getDefaultValueForOptions(array $options): array
{
return [
'year' => isset($options['year']) ? $options['year'] : 1970,

View File

@ -271,10 +271,8 @@ final class Intl
/**
* Returns the cached bundle entry reader.
*
* @return BundleEntryReaderInterface The bundle entry reader
*/
private static function getEntryReader()
private static function getEntryReader(): BundleEntryReaderInterface
{
if (null === self::$entryReader) {
self::$entryReader = new BundleEntryReader(new BufferedBundleReader(

View File

@ -672,12 +672,10 @@ class NumberFormatter
*
* The only actual rounding data as of this writing, is CHF.
*
* @return float The rounded numeric currency value
*
* @see http://en.wikipedia.org/wiki/Swedish_rounding
* @see http://www.docjar.com/html/api/com/ibm/icu/util/Currency.java.html#1007
*/
private function roundCurrency(float $value, string $currency)
private function roundCurrency(float $value, string $currency): float
{
$fractionDigits = Currencies::getFractionDigits($currency);
$roundingIncrement = Currencies::getRoundingIncrement($currency);
@ -738,10 +736,8 @@ class NumberFormatter
* Formats a number.
*
* @param int|float $value The numeric value to format
*
* @return string The formatted number
*/
private function formatNumber($value, int $precision)
private function formatNumber($value, int $precision): string
{
$precision = $this->getUninitializedPrecision($value, $precision);
@ -752,10 +748,8 @@ class NumberFormatter
* Returns the precision value if the DECIMAL style is being used and the FRACTION_DIGITS attribute is uninitialized.
*
* @param int|float $value The value to get the precision from if the FRACTION_DIGITS attribute is uninitialized
*
* @return int The precision value
*/
private function getUninitializedPrecision($value, int $precision)
private function getUninitializedPrecision($value, int $precision): int
{
if (self::CURRENCY == $this->style) {
return $precision;
@ -773,10 +767,8 @@ class NumberFormatter
/**
* Check if the attribute is initialized (value set by client code).
*
* @return bool true if the value was set by client, false otherwise
*/
private function isInitializedAttribute(string $attr)
private function isInitializedAttribute(string $attr): bool
{
return isset($this->initializedAttributes[$attr]);
}
@ -835,10 +827,8 @@ class NumberFormatter
/**
* Check if the rounding mode is invalid.
*
* @return bool true if the rounding mode is invalid, false otherwise
*/
private function isInvalidRoundingMode(int $value)
private function isInvalidRoundingMode(int $value): bool
{
if (\in_array($value, self::$roundingModes, true)) {
return false;
@ -850,20 +840,16 @@ class NumberFormatter
/**
* Returns the normalized value for the GROUPING_USED attribute. Any value that can be converted to int will be
* cast to Boolean and then to int again. This way, negative values are converted to 1 and string values to 0.
*
* @return int The normalized value for the attribute (0 or 1)
*/
private function normalizeGroupingUsedValue($value)
private function normalizeGroupingUsedValue($value): int
{
return (int) (bool) (int) $value;
}
/**
* Returns the normalized value for the FRACTION_DIGITS attribute.
*
* @return int The normalized value for the attribute
*/
private function normalizeFractionDigitsValue($value)
private function normalizeFractionDigitsValue($value): int
{
return (int) $value;
}

View File

@ -207,10 +207,8 @@ class IntlDateFormatterTest extends AbstractIntlDateFormatterTest
* Also in intl, format like 'ss E' for '10 2' (2nd day of year
* + 10 seconds) are added, then we have 86,400 seconds (24h * 60min * 60s)
* + 10 seconds
*
* @return array
*/
private function notImplemented(array $dataSets)
private function notImplemented(array $dataSets): array
{
return array_map(function (array $row) {
return [$row[0], $row[1], 0];

View File

@ -264,12 +264,10 @@ class PropertyAccessor implements PropertyAccessorInterface
/**
* Reads the path from an object up to a given path index.
*
* @return array The values read in the path
*
* @throws UnexpectedTypeException if a value within the path is neither object nor array
* @throws NoSuchIndexException If a non-existing index is accessed
*/
private function readPropertiesUntil(array $zval, PropertyPathInterface $propertyPath, int $lastIndex, bool $ignoreInvalidIndices = true)
private function readPropertiesUntil(array $zval, PropertyPathInterface $propertyPath, int $lastIndex, bool $ignoreInvalidIndices = true): array
{
if (!\is_object($zval[self::VALUE]) && !\is_array($zval[self::VALUE])) {
throw new UnexpectedTypeException($zval[self::VALUE], $propertyPath, 0);
@ -339,11 +337,9 @@ class PropertyAccessor implements PropertyAccessorInterface
*
* @param string|int $index The key to read
*
* @return array The array containing the value of the key
*
* @throws NoSuchIndexException If the array does not implement \ArrayAccess or it is not an array
*/
private function readIndex(array $zval, $index)
private function readIndex(array $zval, $index): array
{
if (!$zval[self::VALUE] instanceof \ArrayAccess && !\is_array($zval[self::VALUE])) {
throw new NoSuchIndexException(sprintf('Cannot read index "%s" from object of type "%s" because it doesn\'t implement \ArrayAccess.', $index, \get_class($zval[self::VALUE])));
@ -369,11 +365,9 @@ class PropertyAccessor implements PropertyAccessorInterface
/**
* Reads the a property from an object.
*
* @return array The array containing the value of the property
*
* @throws NoSuchPropertyException If $ignoreInvalidProperty is false and the property does not exist or is not public
*/
private function readProperty(array $zval, string $property, bool $ignoreInvalidProperty = false)
private function readProperty(array $zval, string $property, bool $ignoreInvalidProperty = false): array
{
if (!\is_object($zval[self::VALUE])) {
throw new NoSuchPropertyException(sprintf('Cannot read property "%s" from an array. Maybe you intended to write the property path as "[%1$s]" instead.', $property));
@ -419,10 +413,8 @@ class PropertyAccessor implements PropertyAccessorInterface
/**
* Guesses how to read the property value.
*
* @return array
*/
private function getReadAccessInfo(string $class, string $property)
private function getReadAccessInfo(string $class, string $property): array
{
$key = str_replace('\\', '.', $class).'..'.$property;
@ -770,13 +762,8 @@ class PropertyAccessor implements PropertyAccessorInterface
/**
* Searches for add and remove methods.
*
* @param \ReflectionClass $reflClass The reflection class for the given object
* @param array $singulars The singular form of the property name or null
*
* @return array|null An array containing the adder and remover when found, null otherwise
*/
private function findAdderAndRemover(\ReflectionClass $reflClass, array $singulars)
private function findAdderAndRemover(\ReflectionClass $reflClass, array $singulars): iterable
{
foreach ($singulars as $singular) {
$addMethod = 'add'.$singular;

View File

@ -79,10 +79,8 @@ EOF;
/**
* Generates PHP code representing an array of defined routes
* together with the routes properties (e.g. requirements).
*
* @return string PHP code
*/
private function generateDeclaredRoutes()
private function generateDeclaredRoutes(): string
{
$routes = "[\n";
foreach ($this->getRoutes()->all() as $name => $route) {
@ -105,10 +103,8 @@ EOF;
/**
* Generates PHP code representing the `generate` method that implements the UrlGeneratorInterface.
*
* @return string PHP code
*/
private function generateGenerateMethod()
private function generateGenerateMethod(): string
{
return <<<'EOF'
public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)

View File

@ -253,11 +253,9 @@ class XmlFileLoader extends FileLoader
/**
* Parses the config elements (default, requirement, option).
*
* @return array An array with the defaults as first item, requirements as second and options as third
*
* @throws \InvalidArgumentException When the XML is invalid
*/
private function parseConfigs(\DOMElement $node, string $path)
private function parseConfigs(\DOMElement $node, string $path): array
{
$defaults = [];
$requirements = [];

View File

@ -405,10 +405,8 @@ class Router implements RouterInterface, RequestMatcherInterface
/**
* Provides the ConfigCache factory implementation, falling back to a
* default implementation if necessary.
*
* @return ConfigCacheFactoryInterface
*/
private function getConfigCacheFactory()
private function getConfigCacheFactory(): ConfigCacheFactoryInterface
{
if (null === $this->configCacheFactory) {
$this->configCacheFactory = new ConfigCacheFactory($this->options['debug']);

View File

@ -109,10 +109,8 @@ abstract class UserAuthenticationProvider implements AuthenticationProviderInter
/**
* Retrieves roles from user and appends SwitchUserRole if original token contained one.
*
* @return array The user roles
*/
private function getRoles(UserInterface $user, TokenInterface $token)
private function getRoles(UserInterface $user, TokenInterface $token): array
{
$roles = $user->getRoles();

View File

@ -65,7 +65,7 @@ class EncoderFactory implements EncoderFactoryInterface
*
* @throws \InvalidArgumentException
*/
private function createEncoder(array $config)
private function createEncoder(array $config): PasswordEncoderInterface
{
if (isset($config['algorithm'])) {
$config = $this->getEncoderConfigFromAlgorithm($config);

View File

@ -93,11 +93,9 @@ class InMemoryUserProvider implements UserProviderInterface
/**
* Returns the user by given username.
*
* @return User
*
* @throws UsernameNotFoundException if user whose given username does not exist
*/
private function getUser(string $username)
private function getUser(string $username): User
{
if (!isset($this->users[strtolower($username)])) {
$ex = new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));

View File

@ -112,14 +112,12 @@ class SwitchUserListener implements ListenerInterface
}
/**
* Attempts to switch to another user.
*
* @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise
* Attempts to switch to another user and returns the new token if successfully switched.
*
* @throws \LogicException
* @throws AccessDeniedException
*/
private function attemptSwitchUser(Request $request, string $username)
private function attemptSwitchUser(Request $request, string $username): ?TokenInterface
{
$token = $this->tokenStorage->getToken();
$originalToken = $this->getOriginalToken($token);
@ -163,13 +161,11 @@ class SwitchUserListener implements ListenerInterface
}
/**
* Attempts to exit from an already switched user.
*
* @return TokenInterface The original TokenInterface instance
* Attempts to exit from an already switched user and returns the original token.
*
* @throws AuthenticationCredentialsNotFoundException
*/
private function attemptExitUser(Request $request)
private function attemptExitUser(Request $request): TokenInterface
{
if (null === ($currentToken = $this->tokenStorage->getToken()) || null === $original = $this->getOriginalToken($currentToken)) {
throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');

View File

@ -91,7 +91,7 @@ class LogoutUrlGenerator
*
* @return string The logout URL
*/
private function generateLogoutUrl(?string $key, int $referenceType)
private function generateLogoutUrl(?string $key, int $referenceType): string
{
list($logoutPath, $csrfTokenId, $csrfParameter, $csrfTokenManager) = $this->getListener($key);
@ -125,11 +125,9 @@ class LogoutUrlGenerator
}
/**
* @return array The logout listener found
*
* @throws \InvalidArgumentException if no LogoutListener is registered for the key or could not be found automatically
*/
private function getListener(?string $key)
private function getListener(?string $key): array
{
if (null !== $key) {
if (isset($this->listeners[$key])) {

View File

@ -30,10 +30,8 @@ trait TargetPathTrait
/**
* Returns the URL (if any) the user visited that forced them to login.
*
* @return string|null
*/
private function getTargetPath(SessionInterface $session, string $providerKey)
private function getTargetPath(SessionInterface $session, string $providerKey): ?string
{
return $session->get('_security.'.$providerKey.'.target_path');
}

View File

@ -245,7 +245,7 @@ class CsvEncoder implements EncoderInterface, DecoderInterface
/**
* @return string[]
*/
private function extractHeaders(array $data)
private function extractHeaders(array $data): array
{
$headers = [];
$flippedHeaders = [];

View File

@ -25,11 +25,9 @@ trait ClassResolverTrait
/**
* Gets a class name for a given class or instance.
*
* @return string
*
* @throws InvalidArgumentException If the class does not exists
*/
private function getClass($value)
private function getClass($value): string
{
if (\is_string($value)) {
if (!class_exists($value) && !interface_exists($value, false)) {

View File

@ -108,11 +108,9 @@ class XmlFileLoader extends FileLoader
/**
* Parses a XML File.
*
* @return \SimpleXMLElement
*
* @throws MappingException
*/
private function parseFile(string $file)
private function parseFile(string $file): \SimpleXMLElement
{
try {
$dom = XmlUtils::loadFile($file, __DIR__.'/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd');
@ -123,7 +121,7 @@ class XmlFileLoader extends FileLoader
return simplexml_import_dom($dom);
}
private function getClassesFromXml()
private function getClassesFromXml(): array
{
$xml = $this->parseFile($this->file);
$classes = [];

View File

@ -468,7 +468,7 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
/**
* @return Type[]|null
*/
private function getTypes(string $currentClass, string $attribute)
private function getTypes(string $currentClass, string $attribute): ?array
{
if (null === $this->propertyTypeExtractor) {
return null;

View File

@ -143,12 +143,8 @@ class DataUriNormalizer implements NormalizerInterface, DenormalizerInterface, C
/**
* Gets the mime type of the object. Defaults to application/octet-stream.
*
* @param \SplFileInfo $object
*
* @return string
*/
private function getMimeType(\SplFileInfo $object)
private function getMimeType(\SplFileInfo $object): string
{
if ($object instanceof File) {
return $object->getMimeType();
@ -167,12 +163,8 @@ class DataUriNormalizer implements NormalizerInterface, DenormalizerInterface, C
/**
* Returns the \SplFileObject instance associated with the given \SplFileInfo instance.
*
* @param \SplFileInfo $object
*
* @return \SplFileObject
*/
private function extractSplFileObject(\SplFileInfo $object)
private function extractSplFileObject(\SplFileInfo $object): \SplFileObject
{
if ($object instanceof \SplFileObject) {
return $object;

View File

@ -143,7 +143,7 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,
*
* @return string[]
*/
private function formatDateTimeErrors(array $errors)
private function formatDateTimeErrors(array $errors): array
{
$formattedErrors = [];

View File

@ -216,10 +216,8 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
* @param mixed $data Data to get the serializer for
* @param string $format Format name, present to give the option to normalizers to act differently based on formats
* @param array $context Options available to the normalizer
*
* @return NormalizerInterface|null
*/
private function getNormalizer($data, ?string $format, array $context)
private function getNormalizer($data, ?string $format, array $context): ?NormalizerInterface
{
if ($this->cachedNormalizers !== $this->normalizers) {
$this->cachedNormalizers = $this->normalizers;
@ -261,10 +259,8 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
* @param string $class The expected class to instantiate
* @param string $format Format name, present to give the option to normalizers to act differently based on formats
* @param array $context Options available to the denormalizer
*
* @return DenormalizerInterface|null
*/
private function getDenormalizer($data, string $class, ?string $format, array $context)
private function getDenormalizer($data, string $class, ?string $format, array $context): ?DenormalizerInterface
{
if ($this->cachedNormalizers !== $this->normalizers) {
$this->cachedNormalizers = $this->normalizers;

View File

@ -867,10 +867,7 @@ XML;
$this->assertEquals($expected, $encoder->encode($data, 'xml'));
}
/**
* @return XmlEncoder
*/
private function createXmlEncoderWithDateTimeNormalizer()
private function createXmlEncoderWithDateTimeNormalizer(): XmlEncoder
{
$encoder = new XmlEncoder();
$serializer = new Serializer([$this->createMockDateTimeNormalizer()], ['xml' => new XmlEncoder()]);
@ -901,20 +898,14 @@ XML;
return $mock;
}
/**
* @return string
*/
private function createXmlWithDateTime()
private function createXmlWithDateTime(): string
{
return sprintf('<?xml version="1.0"?>
<response><dateTime>%s</dateTime></response>
', $this->exampleDateTimeString);
}
/**
* @return string
*/
private function createXmlWithDateTimeField()
private function createXmlWithDateTimeField(): string
{
return sprintf('<?xml version="1.0"?>
<response><foo dateTime="%s"/></response>

View File

@ -39,10 +39,8 @@ class JsonFileLoader extends FileLoader
/**
* Translates JSON_ERROR_* constant into meaningful message.
*
* @return string Message string
*/
private function getJSONErrorMessage(int $errorCode)
private function getJSONErrorMessage(int $errorCode): string
{
switch ($errorCode) {
case JSON_ERROR_DEPTH:

Some files were not shown because too many files have changed in this diff Show More