Add types to constructors and private/final/internal methods (Batch II)

This commit is contained in:
Alexander M. Turek 2019-09-25 12:08:54 +02:00 committed by Tobias Schultze
parent 2b71c6f221
commit 9378eb4858
79 changed files with 127 additions and 129 deletions

View File

@ -126,7 +126,7 @@ class Translator extends BaseTranslator implements WarmableInterface
/** /**
* @internal * @internal
*/ */
protected function doLoadCatalogue($locale): void protected function doLoadCatalogue(string $locale): void
{ {
parent::doLoadCatalogue($locale); parent::doLoadCatalogue($locale);

View File

@ -50,7 +50,7 @@
"symfony/security-http": "^3.4|^4.0|^5.0", "symfony/security-http": "^3.4|^4.0|^5.0",
"symfony/serializer": "^4.3|^5.0", "symfony/serializer": "^4.3|^5.0",
"symfony/stopwatch": "^3.4|^4.0|^5.0", "symfony/stopwatch": "^3.4|^4.0|^5.0",
"symfony/translation": "^4.3|^5.0", "symfony/translation": "^4.4|^5.0",
"symfony/templating": "^3.4|^4.0|^5.0", "symfony/templating": "^3.4|^4.0|^5.0",
"symfony/twig-bundle": "^4.4|^5.0", "symfony/twig-bundle": "^4.4|^5.0",
"symfony/validator": "^4.4|^5.0", "symfony/validator": "^4.4|^5.0",
@ -80,7 +80,7 @@
"symfony/property-info": "<3.4", "symfony/property-info": "<3.4",
"symfony/serializer": "<4.2", "symfony/serializer": "<4.2",
"symfony/stopwatch": "<3.4", "symfony/stopwatch": "<3.4",
"symfony/translation": "<4.3", "symfony/translation": "<4.4",
"symfony/twig-bridge": "<4.1.1", "symfony/twig-bridge": "<4.1.1",
"symfony/twig-bundle": "<4.4", "symfony/twig-bundle": "<4.4",
"symfony/validator": "<4.4", "symfony/validator": "<4.4",

View File

@ -182,7 +182,7 @@ class ArrayChoiceList implements ChoiceListInterface
* *
* @internal * @internal
*/ */
protected function flatten(array $choices, $value, &$choicesByValues, &$keysByValues, &$structuredValues) protected function flatten(array $choices, callable $value, ?array &$choicesByValues, ?array &$keysByValues, ?array &$structuredValues)
{ {
if (null === $choicesByValues) { if (null === $choicesByValues) {
$choicesByValues = []; $choicesByValues = [];

View File

@ -154,7 +154,7 @@ EOF
$helper->describe($io, $object, $options); $helper->describe($io, $object, $options);
} }
private function getFqcnTypeClass(InputInterface $input, SymfonyStyle $io, string $shortClassName) private function getFqcnTypeClass(InputInterface $input, SymfonyStyle $io, string $shortClassName): string
{ {
$classes = []; $classes = [];
sort($this->namespaces); sort($this->namespaces);
@ -195,7 +195,7 @@ EOF
return $io->choice(sprintf("The type \"%s\" is ambiguous.\n\nSelect one of the following form types to display its information:", $shortClassName), $classes, $classes[0]); return $io->choice(sprintf("The type \"%s\" is ambiguous.\n\nSelect one of the following form types to display its information:", $shortClassName), $classes, $classes[0]);
} }
private function getCoreTypes() private function getCoreTypes(): array
{ {
$coreExtension = new CoreExtension(); $coreExtension = new CoreExtension();
$loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes'); $loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes');
@ -223,7 +223,7 @@ EOF
return $typesWithDeprecatedOptions; return $typesWithDeprecatedOptions;
} }
private function findAlternatives(string $name, array $collection) private function findAlternatives(string $name, array $collection): array
{ {
$alternatives = []; $alternatives = [];
foreach ($collection as $item) { foreach ($collection as $item) {

View File

@ -167,7 +167,7 @@ abstract class Descriptor implements DescriptorInterface
$this->extensionOptions = $filterByDeprecated($this->extensionOptions); $this->extensionOptions = $filterByDeprecated($this->extensionOptions);
} }
private function getParentOptionsResolver(ResolvedFormTypeInterface $type) private function getParentOptionsResolver(ResolvedFormTypeInterface $type): OptionsResolver
{ {
$this->parents[$class = \get_class($type->getInnerType())] = []; $this->parents[$class = \get_class($type->getInnerType())] = [];

View File

@ -155,7 +155,7 @@ class TextDescriptor extends Descriptor
return $tableRows; return $tableRows;
} }
private function normalizeAndSortOptionsColumns(array $options) private function normalizeAndSortOptionsColumns(array $options): array
{ {
foreach ($options as $group => $opts) { foreach ($options as $group => $opts) {
$sorted = false; $sorted = false;

View File

@ -11,6 +11,7 @@
namespace Symfony\Component\Form\DependencyInjection; namespace Symfony\Component\Form\DependencyInjection;
use Symfony\Component\DependencyInjection\Argument\ArgumentInterface;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument; use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait; use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
@ -60,7 +61,7 @@ class FormPass implements CompilerPassInterface
$definition->replaceArgument(2, $this->processFormTypeGuessers($container)); $definition->replaceArgument(2, $this->processFormTypeGuessers($container));
} }
private function processFormTypes(ContainerBuilder $container) private function processFormTypes(ContainerBuilder $container): Reference
{ {
// Get service locator argument // Get service locator argument
$servicesMap = []; $servicesMap = [];
@ -83,7 +84,7 @@ class FormPass implements CompilerPassInterface
return ServiceLocatorTagPass::register($container, $servicesMap); return ServiceLocatorTagPass::register($container, $servicesMap);
} }
private function processFormTypeExtensions(ContainerBuilder $container) private function processFormTypeExtensions(ContainerBuilder $container): array
{ {
$typeExtensions = []; $typeExtensions = [];
$typeExtensionsClasses = []; $typeExtensionsClasses = [];
@ -130,7 +131,7 @@ class FormPass implements CompilerPassInterface
return $typeExtensions; return $typeExtensions;
} }
private function processFormTypeGuessers(ContainerBuilder $container) private function processFormTypeGuessers(ContainerBuilder $container): ArgumentInterface
{ {
$guessers = []; $guessers = [];
$guessersClasses = []; $guessersClasses = [];

View File

@ -94,7 +94,7 @@ class DateIntervalToStringTransformer implements DataTransformerInterface
return $dateInterval; return $dateInterval;
} }
private function isISO8601(string $string) private function isISO8601(string $string): bool
{ {
return preg_match('/^P(?=\w*(?:\d|%\w))(?:\d+Y|%[yY]Y)?(?:\d+M|%[mM]M)?(?:(?:\d+D|%[dD]D)|(?:\d+W|%[wW]W))?(?:T(?:\d+H|[hH]H)?(?:\d+M|[iI]M)?(?:\d+S|[sS]S)?)?$/', $string); return preg_match('/^P(?=\w*(?:\d|%\w))(?:\d+Y|%[yY]Y)?(?:\d+M|%[mM]M)?(?:(?:\d+D|%[dD]D)|(?:\d+W|%[wW]W))?(?:T(?:\d+H|[hH]H)?(?:\d+M|[iI]M)?(?:\d+S|[sS]S)?)?$/', $string);
} }

View File

@ -188,7 +188,7 @@ class FormValidator extends ConstraintValidator
* *
* @param string|GroupSequence|(string|GroupSequence)[]|callable $groups The validation groups * @param string|GroupSequence|(string|GroupSequence)[]|callable $groups The validation groups
* *
* @return (string|GroupSequence)[] The validation groups * @return GroupSequence|(string|GroupSequence)[] The validation groups
*/ */
private static function resolveValidationGroups($groups, FormInterface $form) private static function resolveValidationGroups($groups, FormInterface $form)
{ {

View File

@ -290,7 +290,7 @@ class FormRenderer implements FormRendererInterface
/** /**
* @internal * @internal
*/ */
public function encodeCurrency(Environment $environment, $text, $widget = '') public function encodeCurrency(Environment $environment, string $text, string $widget = ''): string
{ {
if ('UTF-8' === $charset = $environment->getCharset()) { if ('UTF-8' === $charset = $environment->getCharset()) {
$text = htmlspecialchars($text, ENT_QUOTES | (\defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0), 'UTF-8'); $text = htmlspecialchars($text, ENT_QUOTES | (\defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0), 'UTF-8');

View File

@ -164,7 +164,7 @@ class HttpClientDataCollectorTest extends TestCase
$this->assertEquals(0, $sut->getRequestCount()); $this->assertEquals(0, $sut->getRequestCount());
} }
private function httpClientThatHasTracedRequests($tracedRequests) private function httpClientThatHasTracedRequests($tracedRequests): TraceableHttpClient
{ {
$httpClient = new TraceableHttpClient(new NativeHttpClient()); $httpClient = new TraceableHttpClient(new NativeHttpClient());

View File

@ -20,7 +20,7 @@ use Symfony\Contracts\HttpClient\ResponseInterface;
*/ */
class HttpExceptionTraitTest extends TestCase class HttpExceptionTraitTest extends TestCase
{ {
public function provideParseError() public function provideParseError(): iterable
{ {
yield ['application/ld+json', '{"hydra:title": "An error occurred", "hydra:description": "Some details"}']; yield ['application/ld+json', '{"hydra:title": "An error occurred", "hydra:description": "Some details"}'];
yield ['application/problem+json', '{"title": "An error occurred", "detail": "Some details"}']; yield ['application/problem+json', '{"title": "An error occurred", "detail": "Some details"}'];

View File

@ -24,7 +24,7 @@ class HttpClientTraitTest extends TestCase
/** /**
* @dataProvider providePrepareRequestUrl * @dataProvider providePrepareRequestUrl
*/ */
public function testPrepareRequestUrl($expected, $url, $query = []) public function testPrepareRequestUrl(string $expected, string $url, array $query = [])
{ {
$defaults = [ $defaults = [
'base_uri' => 'http://example.com?c=c', 'base_uri' => 'http://example.com?c=c',
@ -36,7 +36,7 @@ class HttpClientTraitTest extends TestCase
$this->assertSame($expected, implode('', $url)); $this->assertSame($expected, implode('', $url));
} }
public function providePrepareRequestUrl() public function providePrepareRequestUrl(): iterable
{ {
yield ['http://example.com/', 'http://example.com/']; yield ['http://example.com/', 'http://example.com/'];
yield ['http://example.com/?a=1&b=b', '.']; yield ['http://example.com/?a=1&b=b', '.'];
@ -48,7 +48,7 @@ class HttpClientTraitTest extends TestCase
/** /**
* @dataProvider provideResolveUrl * @dataProvider provideResolveUrl
*/ */
public function testResolveUrl($base, $url, $expected) public function testResolveUrl(string $base, string $url, string $expected)
{ {
$this->assertSame($expected, implode('', self::resolveUrl(self::parseUrl($url), self::parseUrl($base)))); $this->assertSame($expected, implode('', self::resolveUrl(self::parseUrl($url), self::parseUrl($base))));
} }
@ -56,7 +56,7 @@ class HttpClientTraitTest extends TestCase
/** /**
* From https://github.com/guzzle/psr7/blob/master/tests/UriResoverTest.php. * From https://github.com/guzzle/psr7/blob/master/tests/UriResoverTest.php.
*/ */
public function provideResolveUrl() public function provideResolveUrl(): array
{ {
return [ return [
[self::RFC3986_BASE, 'http:h', 'http:h'], [self::RFC3986_BASE, 'http:h', 'http:h'],
@ -123,14 +123,14 @@ class HttpClientTraitTest extends TestCase
/** /**
* @dataProvider provideParseUrl * @dataProvider provideParseUrl
*/ */
public function testParseUrl($expected, $url, $query = []) public function testParseUrl(array $expected, string $url, array $query = [])
{ {
$expected = array_combine(['scheme', 'authority', 'path', 'query', 'fragment'], $expected); $expected = array_combine(['scheme', 'authority', 'path', 'query', 'fragment'], $expected);
$this->assertSame($expected, self::parseUrl($url, $query)); $this->assertSame($expected, self::parseUrl($url, $query));
} }
public function provideParseUrl() public function provideParseUrl(): iterable
{ {
yield [['http:', '//example.com', null, null, null], 'http://Example.coM:80']; yield [['http:', '//example.com', null, null, null], 'http://Example.coM:80'];
yield [['https:', '//xn--dj-kia8a.example.com:8000', '/', null, null], 'https://DÉjà.Example.com:8000/']; yield [['https:', '//xn--dj-kia8a.example.com:8000', '/', null, null], 'https://DÉjà.Example.com:8000/'];

View File

@ -19,7 +19,7 @@ use Symfony\Component\HttpClient\HttpOptions;
*/ */
class HttpOptionsTest extends TestCase class HttpOptionsTest extends TestCase
{ {
public function provideSetAuthBasic() public function provideSetAuthBasic(): iterable
{ {
yield ['user:password', 'user', 'password']; yield ['user:password', 'user', 'password'];
yield ['user:password', 'user:password']; yield ['user:password', 'user:password'];

View File

@ -151,7 +151,7 @@ class ControllerResolver implements ControllerResolverInterface
return new $class(); return new $class();
} }
private function getControllerError($callable) private function getControllerError($callable): string
{ {
if (\is_string($callable)) { if (\is_string($callable)) {
if (false !== strpos($callable, '::')) { if (false !== strpos($callable, '::')) {
@ -213,7 +213,7 @@ class ControllerResolver implements ControllerResolverInterface
return $message; return $message;
} }
private function getClassMethodsWithoutMagicMethods($classOrObject) private function getClassMethodsWithoutMagicMethods($classOrObject): array
{ {
$methods = get_class_methods($classOrObject); $methods = get_class_methods($classOrObject);

View File

@ -118,7 +118,7 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
return 'logger'; return 'logger';
} }
private function getContainerDeprecationLogs() private function getContainerDeprecationLogs(): array
{ {
if (null === $this->containerPathPrefix || !file_exists($file = $this->containerPathPrefix.'Deprecations.log')) { if (null === $this->containerPathPrefix || !file_exists($file = $this->containerPathPrefix.'Deprecations.log')) {
return []; return [];
@ -212,7 +212,7 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
return array_values($sanitizedLogs); return array_values($sanitizedLogs);
} }
private function isSilencedOrDeprecationErrorLog(array $log) private function isSilencedOrDeprecationErrorLog(array $log): bool
{ {
if (!isset($log['context']['exception'])) { if (!isset($log['context']['exception'])) {
return false; return false;
@ -231,7 +231,7 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte
return false; return false;
} }
private function computeErrorsCount(array $containerDeprecationLogs) private function computeErrorsCount(array $containerDeprecationLogs): array
{ {
$silencedLogs = []; $silencedLogs = [];
$count = [ $count = [

View File

@ -89,7 +89,7 @@ class MemoryDataCollector extends DataCollector implements LateDataCollectorInte
return 'memory'; return 'memory';
} }
private function convertToBytes(string $memoryLimit) private function convertToBytes(string $memoryLimit): int
{ {
if ('-1' === $memoryLimit) { if ('-1' === $memoryLimit) {
return -1; return -1;

View File

@ -82,7 +82,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
return array_unique($expanded); return array_unique($expanded);
} }
private function getClassesInComposerClassMaps() private function getClassesInComposerClassMaps(): array
{ {
$classes = []; $classes = [];
@ -103,7 +103,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
return array_keys($classes); return array_keys($classes);
} }
private function patternsToRegexps(array $patterns) private function patternsToRegexps(array $patterns): array
{ {
$regexps = []; $regexps = [];
@ -125,7 +125,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
return $regexps; return $regexps;
} }
private function matchAnyRegexps(string $class, array $regexps) private function matchAnyRegexps(string $class, array $regexps): bool
{ {
$blacklisted = false !== strpos($class, 'Test'); $blacklisted = false !== strpos($class, 'Test');

View File

@ -161,7 +161,7 @@ class RouterListener implements EventSubscriberInterface
]; ];
} }
private function createWelcomeResponse() private function createWelcomeResponse(): Response
{ {
$version = Kernel::VERSION; $version = Kernel::VERSION;
$projectDir = realpath($this->projectDir).\DIRECTORY_SEPARATOR; $projectDir = realpath($this->projectDir).\DIRECTORY_SEPARATOR;

View File

@ -82,12 +82,12 @@ class UriSigner
return $this->computeHash($this->buildUrl($url, $params)) === $hash; return $this->computeHash($this->buildUrl($url, $params)) === $hash;
} }
private function computeHash(string $uri) private function computeHash(string $uri): string
{ {
return base64_encode(hash_hmac('sha256', $uri, $this->secret, true)); return base64_encode(hash_hmac('sha256', $uri, $this->secret, true));
} }
private function buildUrl(array $url, array $params = []) private function buildUrl(array $url, array $params = []): string
{ {
ksort($params, SORT_STRING); ksort($params, SORT_STRING);
$url['query'] = http_build_query($params, '', '&'); $url['query'] = http_build_query($params, '', '&');

View File

@ -205,7 +205,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
return array_keys($alpha3Codes); return array_keys($alpha3Codes);
} }
private function generateAlpha2ToAlpha3Mapping(ArrayAccessibleResourceBundle $metadataBundle) private function generateAlpha2ToAlpha3Mapping(ArrayAccessibleResourceBundle $metadataBundle): array
{ {
$aliases = iterator_to_array($metadataBundle['alias']['language']); $aliases = iterator_to_array($metadataBundle['alias']['language']);
$alpha2ToAlpha3 = []; $alpha2ToAlpha3 = [];

View File

@ -65,7 +65,7 @@ final class Locale extends \Locale
* @return string|null The ICU locale code of the fallback locale, or null * @return string|null The ICU locale code of the fallback locale, or null
* if no fallback exists * if no fallback exists
*/ */
public static function getFallback($locale): ?string public static function getFallback(string $locale): ?string
{ {
if (\function_exists('locale_parse')) { if (\function_exists('locale_parse')) {
$localeSubTags = locale_parse($locale); $localeSubTags = locale_parse($locale);

View File

@ -44,32 +44,32 @@ final class GitRepository
return new self(realpath($targetDir)); return new self(realpath($targetDir));
} }
public function getPath() public function getPath(): string
{ {
return $this->path; return $this->path;
} }
public function getUrl() public function getUrl(): string
{ {
return $this->getLastLine($this->execInPath('git config --get remote.origin.url')); return $this->getLastLine($this->execInPath('git config --get remote.origin.url'));
} }
public function getLastCommitHash() public function getLastCommitHash(): string
{ {
return $this->getLastLine($this->execInPath('git log -1 --format="%H"')); return $this->getLastLine($this->execInPath('git log -1 --format="%H"'));
} }
public function getLastAuthor() public function getLastAuthor(): string
{ {
return $this->getLastLine($this->execInPath('git log -1 --format="%an"')); return $this->getLastLine($this->execInPath('git log -1 --format="%an"'));
} }
public function getLastAuthoredDate() public function getLastAuthoredDate(): \DateTime
{ {
return new \DateTime($this->getLastLine($this->execInPath('git log -1 --format="%ai"'))); return new \DateTime($this->getLastLine($this->execInPath('git log -1 --format="%ai"')));
} }
public function getLastTag(callable $filter = null) public function getLastTag(callable $filter = null): string
{ {
$tags = $this->execInPath('git tag -l --sort=v:refname'); $tags = $this->execInPath('git tag -l --sort=v:refname');
@ -80,17 +80,17 @@ final class GitRepository
return $this->getLastLine($tags); return $this->getLastLine($tags);
} }
public function checkout($branch) public function checkout(string $branch)
{ {
$this->execInPath(sprintf('git checkout %s', escapeshellarg($branch))); $this->execInPath(sprintf('git checkout %s', escapeshellarg($branch)));
} }
private function execInPath(string $command) private function execInPath(string $command): array
{ {
return self::exec(sprintf('cd %s && %s', escapeshellarg($this->path), $command)); return self::exec(sprintf('cd %s && %s', escapeshellarg($this->path), $command));
} }
private static function exec($command, $customErrorMessage = null) private static function exec(string $command, string $customErrorMessage = null): array
{ {
exec(sprintf('%s 2>&1', $command), $output, $result); exec(sprintf('%s 2>&1', $command), $output, $result);
@ -101,7 +101,7 @@ final class GitRepository
return $output; return $output;
} }
private function getLastLine(array $output) private function getLastLine(array $output): string
{ {
return array_pop($output); return array_pop($output);
} }

View File

@ -118,7 +118,7 @@ class Collection implements CollectionInterface
unset($this->entries[$offset]); unset($this->entries[$offset]);
} }
private function getSingleEntry($con, $current) private function getSingleEntry($con, $current): Entry
{ {
$attributes = ldap_get_attributes($con, $current); $attributes = ldap_get_attributes($con, $current);
@ -137,7 +137,7 @@ class Collection implements CollectionInterface
return new Entry($dn, $attributes); return new Entry($dn, $attributes);
} }
private function cleanupAttributes(array $entry) private function cleanupAttributes(array $entry): array
{ {
$attributes = array_diff_key($entry, array_flip(range(0, $entry['count'] - 1)) + [ $attributes = array_diff_key($entry, array_flip(range(0, $entry['count'] - 1)) + [
'count' => null, 'count' => null,

View File

@ -62,7 +62,7 @@ final class ConnectionOptions
const X_KEEPALIVE_PROBES = 0x6301; const X_KEEPALIVE_PROBES = 0x6301;
const X_KEEPALIVE_INTERVAL = 0x6302; const X_KEEPALIVE_INTERVAL = 0x6302;
public static function getOptionName($name) public static function getOptionName(string $name): string
{ {
return sprintf('%s::%s', self::class, strtoupper($name)); return sprintf('%s::%s', self::class, strtoupper($name));
} }
@ -71,11 +71,9 @@ final class ConnectionOptions
* Fetches an option's corresponding constant value from an option name. * Fetches an option's corresponding constant value from an option name.
* The option name can either be in snake or camel case. * The option name can either be in snake or camel case.
* *
* @param string $name
*
* @throws LdapException * @throws LdapException
*/ */
public static function getOption($name): int public static function getOption(string $name): int
{ {
// Convert // Convert
$constantName = self::getOptionName($name); $constantName = self::getOptionName($name);
@ -87,7 +85,7 @@ final class ConnectionOptions
return \constant($constantName); return \constant($constantName);
} }
public static function isOption($name) public static function isOption(string $name): bool
{ {
return \defined(self::getOptionName($name)); return \defined(self::getOptionName($name));
} }

View File

@ -156,7 +156,7 @@ class EntryManager implements EntryManagerInterface
} }
} }
private function parseRdnFromEntry(Entry $entry) private function parseRdnFromEntry(Entry $entry): string
{ {
if (!preg_match('/^([^,]+),/', $entry->getDn(), $matches)) { if (!preg_match('/^([^,]+),/', $entry->getDn(), $matches)) {
throw new LdapException(sprintf('Entry "%s" malformed, could not parse RDN.', $entry->getDn())); throw new LdapException(sprintf('Entry "%s" malformed, could not parse RDN.', $entry->getDn()));

View File

@ -60,7 +60,7 @@ final class Key
/** /**
* @param float $ttl the expiration delay of locks in seconds * @param float $ttl the expiration delay of locks in seconds
*/ */
public function reduceLifetime($ttl) public function reduceLifetime(float $ttl)
{ {
$newTime = microtime(true) + $ttl; $newTime = microtime(true) + $ttl;

View File

@ -161,7 +161,7 @@ class MemcachedStore implements StoreInterface
return $key->getState(__CLASS__); return $key->getState(__CLASS__);
} }
private function getValueAndCas(Key $key) private function getValueAndCas(Key $key): array
{ {
if (null === $this->useExtendedReturn) { if (null === $this->useExtendedReturn) {
$this->useExtendedReturn = version_compare(phpversion('memcached'), '2.9.9', '>'); $this->useExtendedReturn = version_compare(phpversion('memcached'), '2.9.9', '>');

View File

@ -39,7 +39,7 @@ abstract class AbstractFailedMessagesCommand extends Command
parent::__construct(); parent::__construct();
} }
protected function getReceiverName() protected function getReceiverName(): string
{ {
return $this->receiverName; return $this->receiverName;
} }

View File

@ -49,7 +49,7 @@ final class HandlerDescriptor
return $this->options[$option] ?? null; return $this->options[$option] ?? null;
} }
private function callableName(callable $handler) private function callableName(callable $handler): string
{ {
if (\is_array($handler)) { if (\is_array($handler)) {
if (\is_object($handler[0])) { if (\is_object($handler[0])) {

View File

@ -74,7 +74,7 @@ class HandlersLocator implements HandlersLocatorInterface
+ ['*' => '*']; + ['*' => '*'];
} }
private function shouldHandle(Envelope $envelope, HandlerDescriptor $handlerDescriptor) private function shouldHandle(Envelope $envelope, HandlerDescriptor $handlerDescriptor): bool
{ {
if (null === $received = $envelope->last(ReceivedStamp::class)) { if (null === $received = $envelope->last(ReceivedStamp::class)) {
return true; return true;

View File

@ -18,7 +18,7 @@ class HandleDescriptorTest extends TestCase
$this->assertStringMatchesFormat($expectedHandlerString, $descriptor->getName()); $this->assertStringMatchesFormat($expectedHandlerString, $descriptor->getName());
} }
public function provideHandlers() public function provideHandlers(): iterable
{ {
yield [function () {}, 'Closure']; yield [function () {}, 'Closure'];
yield ['var_dump', 'var_dump']; yield ['var_dump', 'var_dump'];

View File

@ -148,7 +148,7 @@ class MessageBusTest extends TestCase
$this->assertCount(2, $finalEnvelope->all()); $this->assertCount(2, $finalEnvelope->all());
} }
public function provideConstructorDataStucture() public function provideConstructorDataStucture(): iterable
{ {
yield 'iterator' => [new \ArrayObject([ yield 'iterator' => [new \ArrayObject([
new SimpleMiddleware(), new SimpleMiddleware(),
@ -167,7 +167,7 @@ class MessageBusTest extends TestCase
} }
/** @dataProvider provideConstructorDataStucture */ /** @dataProvider provideConstructorDataStucture */
public function testConstructDataStructure($dataStructure) public function testConstructDataStructure(iterable $dataStructure)
{ {
$bus = new MessageBus($dataStructure); $bus = new MessageBus($dataStructure);
$envelope = new Envelope(new DummyMessage('Hello')); $envelope = new Envelope(new DummyMessage('Hello'));

View File

@ -60,7 +60,7 @@ class HandleMessageMiddlewareTest extends MiddlewareTestCase
$this->assertEquals($expectedStamps, $envelope->all(HandledStamp::class)); $this->assertEquals($expectedStamps, $envelope->all(HandledStamp::class));
} }
public function itAddsHandledStampsProvider() public function itAddsHandledStampsProvider(): iterable
{ {
$first = $this->createPartialMock(HandleMessageMiddlewareTestCallable::class, ['__invoke']); $first = $this->createPartialMock(HandleMessageMiddlewareTestCallable::class, ['__invoke']);
$first->method('__invoke')->willReturn('first result'); $first->method('__invoke')->willReturn('first result');

View File

@ -241,7 +241,7 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase
$middleware->handle($envelope, $this->getStackMock(false)); $middleware->handle($envelope, $this->getStackMock(false));
} }
private function createSendersLocator(array $sendersMap, array $senders) private function createSendersLocator(array $sendersMap, array $senders): SendersLocator
{ {
$container = $this->createMock(ContainerInterface::class); $container = $this->createMock(ContainerInterface::class);
$container->expects($this->any()) $container->expects($this->any())

View File

@ -70,7 +70,7 @@ class MultiplierRetryStrategyTest extends TestCase
$this->assertSame($expectedDelay, $strategy->getWaitingTime($envelope)); $this->assertSame($expectedDelay, $strategy->getWaitingTime($envelope));
} }
public function getWaitTimeTests() public function getWaitTimeTests(): iterable
{ {
// delay, multiplier, maxDelay, retries, expectedDelay // delay, multiplier, maxDelay, retries, expectedDelay
yield [1000, 1, 5000, 0, 1000]; yield [1000, 1, 5000, 0, 1000];

View File

@ -73,7 +73,7 @@ class AmqpReceiverTest extends TestCase
$receiver->reject(new Envelope(new \stdClass(), [new AmqpReceivedStamp($amqpEnvelope, 'queueName')])); $receiver->reject(new Envelope(new \stdClass(), [new AmqpReceivedStamp($amqpEnvelope, 'queueName')]));
} }
private function createAMQPEnvelope() private function createAMQPEnvelope(): \AMQPEnvelope
{ {
$envelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock(); $envelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock();
$envelope->method('getBody')->willReturn('{"message": "Hi"}'); $envelope->method('getBody')->willReturn('{"message": "Hi"}');

View File

@ -52,7 +52,7 @@ class AmqpTransportTest extends TestCase
$this->assertSame($decodedMessage, $envelopes[0]->getMessage()); $this->assertSame($decodedMessage, $envelopes[0]->getMessage());
} }
private function getTransport(SerializerInterface $serializer = null, Connection $connection = null) private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): AmqpTransport
{ {
$serializer = $serializer ?: $this->getMockBuilder(SerializerInterface::class)->getMock(); $serializer = $serializer ?: $this->getMockBuilder(SerializerInterface::class)->getMock();
$connection = $connection ?: $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); $connection = $connection ?: $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();

View File

@ -135,7 +135,7 @@ class ConnectionTest extends TestCase
return $queryBuilder; return $queryBuilder;
} }
private function getStatementMock($expectedResult) private function getStatementMock($expectedResult): Statement
{ {
$stmt = $this->createMock(Statement::class); $stmt = $this->createMock(Statement::class);
$stmt->expects($this->once()) $stmt->expects($this->once())
@ -145,7 +145,7 @@ class ConnectionTest extends TestCase
return $stmt; return $stmt;
} }
private function getSchemaSynchronizerMock() private function getSchemaSynchronizerMock(): SchemaSynchronizer
{ {
return $this->createMock(SchemaSynchronizer::class); return $this->createMock(SchemaSynchronizer::class);
} }
@ -153,7 +153,7 @@ class ConnectionTest extends TestCase
/** /**
* @dataProvider buildConfigurationProvider * @dataProvider buildConfigurationProvider
*/ */
public function testBuildConfiguration($dsn, $options, $expectedConnection, $expectedTableName, $expectedRedeliverTimeout, $expectedQueue, $expectedAutoSetup) public function testBuildConfiguration(string $dsn, array $options, string $expectedConnection, string $expectedTableName, int $expectedRedeliverTimeout, string $expectedQueue, bool $expectedAutoSetup)
{ {
$config = Connection::buildConfiguration($dsn, $options); $config = Connection::buildConfiguration($dsn, $options);
$this->assertEquals($expectedConnection, $config['connection']); $this->assertEquals($expectedConnection, $config['connection']);
@ -163,7 +163,7 @@ class ConnectionTest extends TestCase
$this->assertEquals($expectedAutoSetup, $config['auto_setup']); $this->assertEquals($expectedAutoSetup, $config['auto_setup']);
} }
public function buildConfigurationProvider() public function buildConfigurationProvider(): iterable
{ {
yield 'no options' => [ yield 'no options' => [
'dsn' => 'doctrine://default', 'dsn' => 'doctrine://default',

View File

@ -119,7 +119,7 @@ class DoctrineReceiverTest extends TestCase
$this->assertEquals(new DummyMessage('Hi'), $actualEnvelope->getMessage()); $this->assertEquals(new DummyMessage('Hi'), $actualEnvelope->getMessage());
} }
private function createDoctrineEnvelope() private function createDoctrineEnvelope(): array
{ {
return [ return [
'id' => 1, 'id' => 1,

View File

@ -50,7 +50,7 @@ class DoctrineTransportTest extends TestCase
$this->assertSame($decodedMessage, $envelopes[0]->getMessage()); $this->assertSame($decodedMessage, $envelopes[0]->getMessage());
} }
private function getTransport(SerializerInterface $serializer = null, Connection $connection = null) private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): DoctrineTransport
{ {
$serializer = $serializer ?: $this->createMock(SerializerInterface::class); $serializer = $serializer ?: $this->createMock(SerializerInterface::class);
$connection = $connection ?: $this->createMock(Connection::class); $connection = $connection ?: $this->createMock(Connection::class);

View File

@ -54,7 +54,7 @@ class RedisReceiverTest extends TestCase
$receiver->get(); $receiver->get();
} }
private function createRedisEnvelope() private function createRedisEnvelope(): array
{ {
return [ return [
'id' => 1, 'id' => 1,

View File

@ -50,7 +50,7 @@ class RedisTransportTest extends TestCase
$this->assertSame($decodedMessage, $envelopes[0]->getMessage()); $this->assertSame($decodedMessage, $envelopes[0]->getMessage());
} }
private function getTransport(SerializerInterface $serializer = null, Connection $connection = null) private function getTransport(SerializerInterface $serializer = null, Connection $connection = null): RedisTransport
{ {
$serializer = $serializer ?: $this->getMockBuilder(SerializerInterface::class)->getMock(); $serializer = $serializer ?: $this->getMockBuilder(SerializerInterface::class)->getMock();
$connection = $connection ?: $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock(); $connection = $connection ?: $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();

View File

@ -90,7 +90,7 @@ class SendersLocatorTest extends TestCase
$this->assertSame(['dummy' => $sender], iterator_to_array($locator->getSenders(new Envelope(new DummyMessage('a'))))); $this->assertSame(['dummy' => $sender], iterator_to_array($locator->getSenders(new Envelope(new DummyMessage('a')))));
} }
private function createContainer(array $senders) private function createContainer(array $senders): ContainerInterface
{ {
$container = $this->createMock(ContainerInterface::class); $container = $this->createMock(ContainerInterface::class);
$container->expects($this->any()) $container->expects($this->any())

View File

@ -166,7 +166,7 @@ class SerializerTest extends TestCase
$serializer->decode($data); $serializer->decode($data);
} }
public function getMissingKeyTests() public function getMissingKeyTests(): iterable
{ {
yield 'no_body' => [ yield 'no_body' => [
['headers' => ['type' => 'bar']], ['headers' => ['type' => 'bar']],

View File

@ -44,7 +44,7 @@ class StopWhenMemoryUsageIsExceededWorkerTest extends TestCase
$this->assertSame($shouldStop, $decoratedWorker->isStopped()); $this->assertSame($shouldStop, $decoratedWorker->isStopped());
} }
public function memoryProvider() public function memoryProvider(): iterable
{ {
yield [2048, 1024, true]; yield [2048, 1024, true];
yield [1024, 1024, false]; yield [1024, 1024, false];

View File

@ -23,7 +23,7 @@ class StopWhenMessageCountIsExceededWorkerTest extends TestCase
/** /**
* @dataProvider countProvider * @dataProvider countProvider
*/ */
public function testWorkerStopsWhenMaximumCountExceeded($max, $shouldStop) public function testWorkerStopsWhenMaximumCountExceeded(int $max, bool $shouldStop)
{ {
$handlerCalledTimes = 0; $handlerCalledTimes = 0;
$handledCallback = function () use (&$handlerCalledTimes) { $handledCallback = function () use (&$handlerCalledTimes) {
@ -44,7 +44,7 @@ class StopWhenMessageCountIsExceededWorkerTest extends TestCase
$this->assertSame($shouldStop, $decoratedWorker->isStopped()); $this->assertSame($shouldStop, $decoratedWorker->isStopped());
} }
public function countProvider() public function countProvider(): iterable
{ {
yield [1, true]; yield [1, true];
yield [2, true]; yield [2, true];

View File

@ -266,7 +266,7 @@ class Connection
* which is the original exchange, resulting on it being put back into * which is the original exchange, resulting on it being put back into
* the original queue. * the original queue.
*/ */
private function createDelayQueue(int $delay, ?string $routingKey) private function createDelayQueue(int $delay, ?string $routingKey): \AMQPQueue
{ {
$queue = $this->amqpFactory->createQueue($this->channel()); $queue = $this->amqpFactory->createQueue($this->channel());
$queue->setName(str_replace( $queue->setName(str_replace(

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Messenger\Transport\Doctrine;
use Doctrine\DBAL\Connection as DBALConnection; use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\DBAL\DBALException; use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\Exception\TableNotFoundException; use Doctrine\DBAL\Exception\TableNotFoundException;
use Doctrine\DBAL\Query\QueryBuilder; use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\Schema\Schema; use Doctrine\DBAL\Schema\Schema;
@ -63,7 +64,7 @@ class Connection
return $this->configuration; return $this->configuration;
} }
public static function buildConfiguration($dsn, array $options = []) public static function buildConfiguration(string $dsn, array $options = []): array
{ {
if (false === $components = parse_url($dsn)) { if (false === $components = parse_url($dsn)) {
throw new InvalidArgumentException(sprintf('The given Doctrine Messenger DSN "%s" is invalid.', $dsn)); throw new InvalidArgumentException(sprintf('The given Doctrine Messenger DSN "%s" is invalid.', $dsn));
@ -279,7 +280,7 @@ class Connection
->from($this->configuration['table_name'], 'm'); ->from($this->configuration['table_name'], 'm');
} }
private function executeQuery(string $sql, array $parameters = []) private function executeQuery(string $sql, array $parameters = []): Statement
{ {
$stmt = null; $stmt = null;
try { try {
@ -327,7 +328,7 @@ class Connection
return $schema; return $schema;
} }
public static function formatDateTime(\DateTimeInterface $dateTime) public static function formatDateTime(\DateTimeInterface $dateTime): string
{ {
return $dateTime->format('Y-m-d\TH:i:s'); return $dateTime->format('Y-m-d\TH:i:s');
} }

View File

@ -248,7 +248,7 @@ class Process implements \IteratorAggregate
* *
* @final * @final
*/ */
public function mustRun(callable $callback = null, array $env = []) public function mustRun(callable $callback = null, array $env = []): self
{ {
if (0 !== $this->run($callback, $env)) { if (0 !== $this->run($callback, $env)) {
throw new ProcessFailedException($this); throw new ProcessFailedException($this);
@ -370,7 +370,7 @@ class Process implements \IteratorAggregate
* *
* @final * @final
*/ */
public function restart(callable $callback = null, array $env = []) public function restart(callable $callback = null, array $env = []): self
{ {
if ($this->isRunning()) { if ($this->isRunning()) {
throw new RuntimeException('Process is already running'); throw new RuntimeException('Process is already running');
@ -1549,7 +1549,7 @@ class Process implements \IteratorAggregate
return true; return true;
} }
private function prepareWindowsCommandLine(string $cmd, array &$env) private function prepareWindowsCommandLine(string $cmd, array &$env): string
{ {
$uid = uniqid('', true); $uid = uniqid('', true);
$varCount = 0; $varCount = 0;
@ -1652,7 +1652,7 @@ class Process implements \IteratorAggregate
}, $commandline); }, $commandline);
} }
private function getDefaultEnv() private function getDefaultEnv(): array
{ {
$env = []; $env = [];

View File

@ -294,7 +294,7 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp
return null; return null;
} }
private function extractFromDefaultValue(string $class, string $property) private function extractFromDefaultValue(string $class, string $property): ?array
{ {
try { try {
$reflectionClass = new \ReflectionClass($class); $reflectionClass = new \ReflectionClass($class);

View File

@ -48,7 +48,7 @@ class CollectionConfigurator
/** /**
* Creates a sub-collection. * Creates a sub-collection.
*/ */
final public function collection($name = ''): self final public function collection(string $name = ''): self
{ {
return new self($this->collection, $this->name.$name, $this, $this->prefixes); return new self($this->collection, $this->name.$name, $this, $this->prefixes);
} }

View File

@ -409,7 +409,7 @@ class XmlFileLoader extends FileLoader
} }
} }
private function isElementValueNull(\DOMElement $element) private function isElementValueNull(\DOMElement $element): bool
{ {
$namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance'; $namespaceUri = 'http://www.w3.org/2001/XMLSchema-instance';

View File

@ -443,7 +443,7 @@ EOF;
]; ];
} }
private function getExpressionLanguage() private function getExpressionLanguage(): ExpressionLanguage
{ {
if (null === $this->expressionLanguage) { if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) { if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
@ -455,7 +455,7 @@ EOF;
return $this->expressionLanguage; return $this->expressionLanguage;
} }
private function indent(string $code, int $level = 1) private function indent(string $code, int $level = 1): string
{ {
return preg_replace('/^./m', str_repeat(' ', $level).'$0', $code); return preg_replace('/^./m', str_repeat(' ', $level).'$0', $code);
} }

View File

@ -32,7 +32,7 @@ trait CompiledUrlMatcherTrait
private $dynamicRoutes = []; private $dynamicRoutes = [];
private $checkCondition; private $checkCondition;
public function match($pathinfo) public function match($pathinfo): array
{ {
$allow = $allowSchemes = []; $allow = $allowSchemes = [];
if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) { if ($ret = $this->doMatch($pathinfo, $allow, $allowSchemes)) {

View File

@ -276,7 +276,7 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
/** /**
* @internal * @internal
*/ */
protected function createRequest($pathinfo) protected function createRequest(string $pathinfo): ?Request
{ {
if (!class_exists('Symfony\Component\HttpFoundation\Request')) { if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
return null; return null;

View File

@ -92,7 +92,7 @@ class RouteCompiler implements RouteCompilerInterface
); );
} }
private static function compilePattern(Route $route, $pattern, $isHost) private static function compilePattern(Route $route, string $pattern, bool $isHost): array
{ {
$tokens = []; $tokens = [];
$variables = []; $variables = [];

View File

@ -299,7 +299,7 @@ abstract class AbstractToken implements TokenInterface
return sprintf('%s(user="%s", authenticated=%s, roles="%s")', $class, $this->getUsername(), json_encode($this->authenticated), implode(', ', $roles)); return sprintf('%s(user="%s", authenticated=%s, roles="%s")', $class, $this->getUsername(), json_encode($this->authenticated), implode(', ', $roles));
} }
private function hasUserChanged(UserInterface $user) private function hasUserChanged(UserInterface $user): bool
{ {
if (!($this->user instanceof UserInterface)) { if (!($this->user instanceof UserInterface)) {
throw new \BadMethodCallException('Method "hasUserChanged" should be called when current user class is instance of "UserInterface".'); throw new \BadMethodCallException('Method "hasUserChanged" should be called when current user class is instance of "UserInterface".');

View File

@ -93,7 +93,7 @@ class ExpressionVoter implements VoterInterface
return $result; return $result;
} }
private function getVariables(TokenInterface $token, $subject) private function getVariables(TokenInterface $token, $subject): array
{ {
if (method_exists($token, 'getRoleNames')) { if (method_exists($token, 'getRoleNames')) {
$roleNames = $token->getRoleNames(); $roleNames = $token->getRoleNames();

View File

@ -102,12 +102,12 @@ class Argon2iPasswordEncoder extends BasePasswordEncoder implements SelfSaltingE
throw new \LogicException('Argon2i algorithm is not supported. Please install the libsodium extension or upgrade to PHP 7.2+.'); throw new \LogicException('Argon2i algorithm is not supported. Please install the libsodium extension or upgrade to PHP 7.2+.');
} }
private function encodePasswordNative(string $raw) private function encodePasswordNative(string $raw): string
{ {
return password_hash($raw, \PASSWORD_ARGON2I, $this->config); return password_hash($raw, \PASSWORD_ARGON2I, $this->config);
} }
private function encodePasswordSodiumFunction(string $raw) private function encodePasswordSodiumFunction(string $raw): string
{ {
$hash = sodium_crypto_pwhash_str( $hash = sodium_crypto_pwhash_str(
$raw, $raw,
@ -119,7 +119,7 @@ class Argon2iPasswordEncoder extends BasePasswordEncoder implements SelfSaltingE
return $hash; return $hash;
} }
private function encodePasswordSodiumExtension(string $raw) private function encodePasswordSodiumExtension(string $raw): string
{ {
$hash = \Sodium\crypto_pwhash_str( $hash = \Sodium\crypto_pwhash_str(
$raw, $raw,

View File

@ -80,7 +80,7 @@ class EncoderFactory implements EncoderFactoryInterface
return $reflection->newInstanceArgs($config['arguments']); return $reflection->newInstanceArgs($config['arguments']);
} }
private function getEncoderConfigFromAlgorithm(array $config) private function getEncoderConfigFromAlgorithm(array $config): array
{ {
if ('auto' === $config['algorithm']) { if ('auto' === $config['algorithm']) {
$encoderChain = []; $encoderChain = [];

View File

@ -53,7 +53,7 @@ final class User implements UserInterface, EquatableInterface, AdvancedUserInter
/** /**
* {@inheritdoc} * {@inheritdoc}
*/ */
public function getRoles() public function getRoles(): array
{ {
return $this->roles; return $this->roles;
} }

View File

@ -114,7 +114,7 @@ class CsrfTokenManager implements CsrfTokenManagerInterface
return hash_equals($this->storage->getToken($namespacedId), $token->getValue()); return hash_equals($this->storage->getToken($namespacedId), $token->getValue());
} }
private function getNamespace() private function getNamespace(): string
{ {
return \is_callable($ns = $this->namespace) ? $ns() : $ns; return \is_callable($ns = $this->namespace) ? $ns() : $ns;
} }

View File

@ -202,7 +202,7 @@ class CsrfTokenManagerTest extends TestCase
return $data; return $data;
} }
private function getGeneratorAndStorage() private function getGeneratorAndStorage(): array
{ {
return [ return [
$this->getMockBuilder('Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface')->getMock(), $this->getMockBuilder('Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface')->getMock(),

View File

@ -99,7 +99,7 @@ class GuardAuthenticationProvider implements AuthenticationProviderInterface
return $this->authenticateViaGuard($guardAuthenticator, $token); return $this->authenticateViaGuard($guardAuthenticator, $token);
} }
private function authenticateViaGuard(AuthenticatorInterface $guardAuthenticator, PreAuthenticationGuardToken $token) private function authenticateViaGuard(AuthenticatorInterface $guardAuthenticator, PreAuthenticationGuardToken $token): GuardTokenInterface
{ {
// get the user from the GuardAuthenticator // get the user from the GuardAuthenticator
$user = $guardAuthenticator->getUser($token->getCredentials(), $this->userProvider); $user = $guardAuthenticator->getUser($token->getCredentials(), $this->userProvider);
@ -134,7 +134,7 @@ class GuardAuthenticationProvider implements AuthenticationProviderInterface
return $authenticatedToken; return $authenticatedToken;
} }
private function findOriginatingAuthenticator(PreAuthenticationGuardToken $token) private function findOriginatingAuthenticator(PreAuthenticationGuardToken $token): ?AuthenticatorInterface
{ {
// find the *one* GuardAuthenticator that this token originated from // find the *one* GuardAuthenticator that this token originated from
foreach ($this->guardAuthenticators as $key => $guardAuthenticator) { foreach ($this->guardAuthenticators as $key => $guardAuthenticator) {

View File

@ -171,7 +171,7 @@ abstract class AbstractAuthenticationListener implements ListenerInterface
*/ */
abstract protected function attemptAuthentication(Request $request); abstract protected function attemptAuthentication(Request $request);
private function onFailure(Request $request, AuthenticationException $failed) private function onFailure(Request $request, AuthenticationException $failed): Response
{ {
if (null !== $this->logger) { if (null !== $this->logger) {
$this->logger->error('Authentication request failed.', ['exception' => $failed]); $this->logger->error('Authentication request failed.', ['exception' => $failed]);
@ -191,7 +191,7 @@ abstract class AbstractAuthenticationListener implements ListenerInterface
return $response; return $response;
} }
private function onSuccess(Request $request, TokenInterface $token) private function onSuccess(Request $request, TokenInterface $token): Response
{ {
if (null !== $this->logger) { if (null !== $this->logger) {
$this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]); $this->logger->info('User has been authenticated successfully.', ['username' => $token->getUsername()]);

View File

@ -168,7 +168,7 @@ class UsernamePasswordJsonAuthenticationListener implements ListenerInterface
return $response; return $response;
} }
private function onFailure(Request $request, AuthenticationException $failed) private function onFailure(Request $request, AuthenticationException $failed): Response
{ {
if (null !== $this->logger) { if (null !== $this->logger) {
$this->logger->info('Authentication request failed.', ['exception' => $failed]); $this->logger->info('Authentication request failed.', ['exception' => $failed]);

View File

@ -128,7 +128,7 @@ class YamlFileLoader extends FileLoader
return array_keys($this->classes); return array_keys($this->classes);
} }
private function getClassesFromYaml() private function getClassesFromYaml(): array
{ {
if (!stream_is_local($this->file)) { if (!stream_is_local($this->file)) {
throw new MappingException(sprintf('This is not a local file "%s".', $this->file)); throw new MappingException(sprintf('This is not a local file "%s".', $this->file));

View File

@ -69,7 +69,7 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface
return self::$denormalizeCache[$class][$propertyName] ?? $this->denormalizeFallback($propertyName, $class, $format, $context); return self::$denormalizeCache[$class][$propertyName] ?? $this->denormalizeFallback($propertyName, $class, $format, $context);
} }
private function getCacheValueForNormalization(string $propertyName, string $class) private function getCacheValueForNormalization(string $propertyName, string $class): ?string
{ {
if (!$this->metadataFactory->hasMetadataFor($class)) { if (!$this->metadataFactory->hasMetadataFor($class)) {
return null; return null;
@ -83,12 +83,12 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface
return $attributesMetadata[$propertyName]->getSerializedName() ?? null; return $attributesMetadata[$propertyName]->getSerializedName() ?? null;
} }
private function normalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = []) private function normalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = []): string
{ {
return $this->fallbackNameConverter ? $this->fallbackNameConverter->normalize($propertyName, $class, $format, $context) : $propertyName; return $this->fallbackNameConverter ? $this->fallbackNameConverter->normalize($propertyName, $class, $format, $context) : $propertyName;
} }
private function getCacheValueForDenormalization(string $propertyName, string $class) private function getCacheValueForDenormalization(string $propertyName, string $class): ?string
{ {
if (!isset(self::$attributesMetadataCache[$class])) { if (!isset(self::$attributesMetadataCache[$class])) {
self::$attributesMetadataCache[$class] = $this->getCacheValueForAttributesMetadata($class); self::$attributesMetadataCache[$class] = $this->getCacheValueForAttributesMetadata($class);
@ -97,7 +97,7 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface
return self::$attributesMetadataCache[$class][$propertyName] ?? null; return self::$attributesMetadataCache[$class][$propertyName] ?? null;
} }
private function denormalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = []) private function denormalizeFallback(string $propertyName, string $class = null, string $format = null, array $context = []): string
{ {
return $this->fallbackNameConverter ? $this->fallbackNameConverter->denormalize($propertyName, $class, $format, $context) : $propertyName; return $this->fallbackNameConverter ? $this->fallbackNameConverter->denormalize($propertyName, $class, $format, $context) : $propertyName;
} }

View File

@ -132,7 +132,7 @@ class DateIntervalNormalizer implements NormalizerInterface, DenormalizerInterfa
return \DateInterval::class === $type; return \DateInterval::class === $type;
} }
private function isISO8601(string $string) private function isISO8601(string $string): bool
{ {
return preg_match('/^[\-+]?P(?=\w*(?:\d|%\w))(?:\d+Y|%[yY]Y)?(?:\d+M|%[mM]M)?(?:(?:\d+D|%[dD]D)|(?:\d+W|%[wW]W))?(?:T(?:\d+H|[hH]H)?(?:\d+M|[iI]M)?(?:\d+S|[sS]S)?)?$/', $string); return preg_match('/^[\-+]?P(?=\w*(?:\d|%\w))(?:\d+Y|%[yY]Y)?(?:\d+M|%[mM]M)?(?:(?:\d+D|%[dD]D)|(?:\d+W|%[wW]W))?(?:T(?:\d+H|[hH]H)?(?:\d+M|[iI]M)?(?:\d+S|[sS]S)?)?$/', $string);
} }

View File

@ -154,7 +154,7 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,
return $formattedErrors; return $formattedErrors;
} }
private function getTimezone(array $context) private function getTimezone(array $context): ?\DateTimeZone
{ {
$dateTimeZone = $context[self::TIMEZONE_KEY] ?? $this->defaultContext[self::TIMEZONE_KEY]; $dateTimeZone = $context[self::TIMEZONE_KEY] ?? $this->defaultContext[self::TIMEZONE_KEY];

View File

@ -225,7 +225,7 @@ class StopwatchEvent
* *
* @throws \InvalidArgumentException When the raw time is not valid * @throws \InvalidArgumentException When the raw time is not valid
*/ */
private function formatTime(float $time) private function formatTime(float $time): float
{ {
return round($time, 1); return round($time, 1);
} }

View File

@ -82,7 +82,7 @@ class IcuResFileDumper extends FileDumper
return $header.$root.$data; return $header.$root.$data;
} }
private function writePadding(string $data) private function writePadding(string $data): ?string
{ {
$padding = \strlen($data) % 4; $padding = \strlen($data) % 4;

View File

@ -75,7 +75,7 @@ class MoFileDumper extends FileDumper
return 'mo'; return 'mo';
} }
private function writeLong($str) private function writeLong($str): string
{ {
return pack('V*', $str); return pack('V*', $str);
} }

View File

@ -119,7 +119,7 @@ EOF;
return 'po'; return 'po';
} }
private function escape(string $str) private function escape(string $str): string
{ {
return addcslashes($str, "\0..\37\42\134"); return addcslashes($str, "\0..\37\42\134");
} }

View File

@ -106,7 +106,7 @@ class PhpStringTokenParser
); );
} }
private static function parseCallback($matches) private static function parseCallback(array $matches): string
{ {
$str = $matches[1]; $str = $matches[1];

View File

@ -99,7 +99,7 @@ class Interval
EOF; EOF;
} }
private static function convertNumber($number) private static function convertNumber(string $number): float
{ {
if ('-Inf' === $number) { if ('-Inf' === $number) {
return log(0); return log(0);

View File

@ -72,8 +72,6 @@ class XliffFileLoader implements LoaderInterface
/** /**
* Extract messages and metadata from DOMDocument into a MessageCatalogue. * Extract messages and metadata from DOMDocument into a MessageCatalogue.
*
* @param string $domain The domain
*/ */
private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain) private function extractXliff1(\DOMDocument $dom, MessageCatalogue $catalogue, string $domain)
{ {

View File

@ -410,7 +410,7 @@ EOF
return $fallbackContent; return $fallbackContent;
} }
private function getCatalogueCachePath(string $locale) private function getCatalogueCachePath(string $locale): string
{ {
return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('sha256', serialize($this->fallbackLocales), true)), 0, 7), '/', '_').'.php'; return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('sha256', serialize($this->fallbackLocales), true)), 0, 7), '/', '_').'.php';
} }
@ -418,7 +418,7 @@ EOF
/** /**
* @internal * @internal
*/ */
protected function doLoadCatalogue($locale): void protected function doLoadCatalogue(string $locale): void
{ {
$this->catalogues[$locale] = new MessageCatalogue($locale); $this->catalogues[$locale] = new MessageCatalogue($locale);