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
*/
protected function doLoadCatalogue($locale): void
protected function doLoadCatalogue(string $locale): void
{
parent::doLoadCatalogue($locale);

View File

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

View File

@ -182,7 +182,7 @@ class ArrayChoiceList implements ChoiceListInterface
*
* @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) {
$choicesByValues = [];

View File

@ -154,7 +154,7 @@ EOF
$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 = [];
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]);
}
private function getCoreTypes()
private function getCoreTypes(): array
{
$coreExtension = new CoreExtension();
$loadTypesRefMethod = (new \ReflectionObject($coreExtension))->getMethod('loadTypes');
@ -223,7 +223,7 @@ EOF
return $typesWithDeprecatedOptions;
}
private function findAlternatives(string $name, array $collection)
private function findAlternatives(string $name, array $collection): array
{
$alternatives = [];
foreach ($collection as $item) {

View File

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

View File

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

View File

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

View File

@ -94,7 +94,7 @@ class DateIntervalToStringTransformer implements DataTransformerInterface
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);
}

View File

@ -188,7 +188,7 @@ class FormValidator extends ConstraintValidator
*
* @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)
{

View File

@ -290,7 +290,7 @@ class FormRenderer implements FormRendererInterface
/**
* @internal
*/
public function encodeCurrency(Environment $environment, $text, $widget = '')
public function encodeCurrency(Environment $environment, string $text, string $widget = ''): string
{
if ('UTF-8' === $charset = $environment->getCharset()) {
$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());
}
private function httpClientThatHasTracedRequests($tracedRequests)
private function httpClientThatHasTracedRequests($tracedRequests): TraceableHttpClient
{
$httpClient = new TraceableHttpClient(new NativeHttpClient());

View File

@ -20,7 +20,7 @@ use Symfony\Contracts\HttpClient\ResponseInterface;
*/
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/problem+json', '{"title": "An error occurred", "detail": "Some details"}'];

View File

@ -24,7 +24,7 @@ class HttpClientTraitTest extends TestCase
/**
* @dataProvider providePrepareRequestUrl
*/
public function testPrepareRequestUrl($expected, $url, $query = [])
public function testPrepareRequestUrl(string $expected, string $url, array $query = [])
{
$defaults = [
'base_uri' => 'http://example.com?c=c',
@ -36,7 +36,7 @@ class HttpClientTraitTest extends TestCase
$this->assertSame($expected, implode('', $url));
}
public function providePrepareRequestUrl()
public function providePrepareRequestUrl(): iterable
{
yield ['http://example.com/', 'http://example.com/'];
yield ['http://example.com/?a=1&b=b', '.'];
@ -48,7 +48,7 @@ class HttpClientTraitTest extends TestCase
/**
* @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))));
}
@ -56,7 +56,7 @@ class HttpClientTraitTest extends TestCase
/**
* From https://github.com/guzzle/psr7/blob/master/tests/UriResoverTest.php.
*/
public function provideResolveUrl()
public function provideResolveUrl(): array
{
return [
[self::RFC3986_BASE, 'http:h', 'http:h'],
@ -123,14 +123,14 @@ class HttpClientTraitTest extends TestCase
/**
* @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);
$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 [['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
{
public function provideSetAuthBasic()
public function provideSetAuthBasic(): iterable
{
yield ['user:password', 'user', 'password'];
yield ['user:password', 'user:password'];

View File

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

View File

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

View File

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

View File

@ -82,7 +82,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
return array_unique($expanded);
}
private function getClassesInComposerClassMaps()
private function getClassesInComposerClassMaps(): array
{
$classes = [];
@ -103,7 +103,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
return array_keys($classes);
}
private function patternsToRegexps(array $patterns)
private function patternsToRegexps(array $patterns): array
{
$regexps = [];
@ -125,7 +125,7 @@ class AddAnnotatedClassesToCachePass implements CompilerPassInterface
return $regexps;
}
private function matchAnyRegexps(string $class, array $regexps)
private function matchAnyRegexps(string $class, array $regexps): bool
{
$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;
$projectDir = realpath($this->projectDir).\DIRECTORY_SEPARATOR;

View File

@ -82,12 +82,12 @@ class UriSigner
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));
}
private function buildUrl(array $url, array $params = [])
private function buildUrl(array $url, array $params = []): string
{
ksort($params, SORT_STRING);
$url['query'] = http_build_query($params, '', '&');

View File

@ -205,7 +205,7 @@ class LanguageDataGenerator extends AbstractDataGenerator
return array_keys($alpha3Codes);
}
private function generateAlpha2ToAlpha3Mapping(ArrayAccessibleResourceBundle $metadataBundle)
private function generateAlpha2ToAlpha3Mapping(ArrayAccessibleResourceBundle $metadataBundle): array
{
$aliases = iterator_to_array($metadataBundle['alias']['language']);
$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
* if no fallback exists
*/
public static function getFallback($locale): ?string
public static function getFallback(string $locale): ?string
{
if (\function_exists('locale_parse')) {
$localeSubTags = locale_parse($locale);

View File

@ -44,32 +44,32 @@ final class GitRepository
return new self(realpath($targetDir));
}
public function getPath()
public function getPath(): string
{
return $this->path;
}
public function getUrl()
public function getUrl(): string
{
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"'));
}
public function getLastAuthor()
public function getLastAuthor(): string
{
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"')));
}
public function getLastTag(callable $filter = null)
public function getLastTag(callable $filter = null): string
{
$tags = $this->execInPath('git tag -l --sort=v:refname');
@ -80,17 +80,17 @@ final class GitRepository
return $this->getLastLine($tags);
}
public function checkout($branch)
public function checkout(string $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));
}
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);
@ -101,7 +101,7 @@ final class GitRepository
return $output;
}
private function getLastLine(array $output)
private function getLastLine(array $output): string
{
return array_pop($output);
}

View File

@ -118,7 +118,7 @@ class Collection implements CollectionInterface
unset($this->entries[$offset]);
}
private function getSingleEntry($con, $current)
private function getSingleEntry($con, $current): Entry
{
$attributes = ldap_get_attributes($con, $current);
@ -137,7 +137,7 @@ class Collection implements CollectionInterface
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)) + [
'count' => null,

View File

@ -62,7 +62,7 @@ final class ConnectionOptions
const X_KEEPALIVE_PROBES = 0x6301;
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));
}
@ -71,11 +71,9 @@ final class ConnectionOptions
* Fetches an option's corresponding constant value from an option name.
* The option name can either be in snake or camel case.
*
* @param string $name
*
* @throws LdapException
*/
public static function getOption($name): int
public static function getOption(string $name): int
{
// Convert
$constantName = self::getOptionName($name);
@ -87,7 +85,7 @@ final class ConnectionOptions
return \constant($constantName);
}
public static function isOption($name)
public static function isOption(string $name): bool
{
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)) {
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
*/
public function reduceLifetime($ttl)
public function reduceLifetime(float $ttl)
{
$newTime = microtime(true) + $ttl;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -241,7 +241,7 @@ class SendMessageMiddlewareTest extends MiddlewareTestCase
$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->expects($this->any())

View File

@ -70,7 +70,7 @@ class MultiplierRetryStrategyTest extends TestCase
$this->assertSame($expectedDelay, $strategy->getWaitingTime($envelope));
}
public function getWaitTimeTests()
public function getWaitTimeTests(): iterable
{
// delay, multiplier, maxDelay, retries, expectedDelay
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')]));
}
private function createAMQPEnvelope()
private function createAMQPEnvelope(): \AMQPEnvelope
{
$envelope = $this->getMockBuilder(\AMQPEnvelope::class)->getMock();
$envelope->method('getBody')->willReturn('{"message": "Hi"}');

View File

@ -52,7 +52,7 @@ class AmqpTransportTest extends TestCase
$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();
$connection = $connection ?: $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();

View File

@ -135,7 +135,7 @@ class ConnectionTest extends TestCase
return $queryBuilder;
}
private function getStatementMock($expectedResult)
private function getStatementMock($expectedResult): Statement
{
$stmt = $this->createMock(Statement::class);
$stmt->expects($this->once())
@ -145,7 +145,7 @@ class ConnectionTest extends TestCase
return $stmt;
}
private function getSchemaSynchronizerMock()
private function getSchemaSynchronizerMock(): SchemaSynchronizer
{
return $this->createMock(SchemaSynchronizer::class);
}
@ -153,7 +153,7 @@ class ConnectionTest extends TestCase
/**
* @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);
$this->assertEquals($expectedConnection, $config['connection']);
@ -163,7 +163,7 @@ class ConnectionTest extends TestCase
$this->assertEquals($expectedAutoSetup, $config['auto_setup']);
}
public function buildConfigurationProvider()
public function buildConfigurationProvider(): iterable
{
yield 'no options' => [
'dsn' => 'doctrine://default',

View File

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

View File

@ -50,7 +50,7 @@ class DoctrineTransportTest extends TestCase
$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);
$connection = $connection ?: $this->createMock(Connection::class);

View File

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

View File

@ -50,7 +50,7 @@ class RedisTransportTest extends TestCase
$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();
$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')))));
}
private function createContainer(array $senders)
private function createContainer(array $senders): ContainerInterface
{
$container = $this->createMock(ContainerInterface::class);
$container->expects($this->any())

View File

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

View File

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

View File

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

View File

@ -266,7 +266,7 @@ class Connection
* which is the original exchange, resulting on it being put back into
* 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->setName(str_replace(

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Messenger\Transport\Doctrine;
use Doctrine\DBAL\Connection as DBALConnection;
use Doctrine\DBAL\DBALException;
use Doctrine\DBAL\Driver\Statement;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Doctrine\DBAL\Query\QueryBuilder;
use Doctrine\DBAL\Schema\Schema;
@ -63,7 +64,7 @@ class Connection
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)) {
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');
}
private function executeQuery(string $sql, array $parameters = [])
private function executeQuery(string $sql, array $parameters = []): Statement
{
$stmt = null;
try {
@ -327,7 +328,7 @@ class Connection
return $schema;
}
public static function formatDateTime(\DateTimeInterface $dateTime)
public static function formatDateTime(\DateTimeInterface $dateTime): string
{
return $dateTime->format('Y-m-d\TH:i:s');
}

View File

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

View File

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

View File

@ -48,7 +48,7 @@ class CollectionConfigurator
/**
* 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);
}

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';

View File

@ -443,7 +443,7 @@ EOF;
];
}
private function getExpressionLanguage()
private function getExpressionLanguage(): ExpressionLanguage
{
if (null === $this->expressionLanguage) {
if (!class_exists('Symfony\Component\ExpressionLanguage\ExpressionLanguage')) {
@ -455,7 +455,7 @@ EOF;
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);
}

View File

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

View File

@ -276,7 +276,7 @@ class UrlMatcher implements UrlMatcherInterface, RequestMatcherInterface
/**
* @internal
*/
protected function createRequest($pathinfo)
protected function createRequest(string $pathinfo): ?Request
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
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 = [];
$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));
}
private function hasUserChanged(UserInterface $user)
private function hasUserChanged(UserInterface $user): bool
{
if (!($this->user instanceof 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;
}
private function getVariables(TokenInterface $token, $subject)
private function getVariables(TokenInterface $token, $subject): array
{
if (method_exists($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+.');
}
private function encodePasswordNative(string $raw)
private function encodePasswordNative(string $raw): string
{
return password_hash($raw, \PASSWORD_ARGON2I, $this->config);
}
private function encodePasswordSodiumFunction(string $raw)
private function encodePasswordSodiumFunction(string $raw): string
{
$hash = sodium_crypto_pwhash_str(
$raw,
@ -119,7 +119,7 @@ class Argon2iPasswordEncoder extends BasePasswordEncoder implements SelfSaltingE
return $hash;
}
private function encodePasswordSodiumExtension(string $raw)
private function encodePasswordSodiumExtension(string $raw): string
{
$hash = \Sodium\crypto_pwhash_str(
$raw,

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -128,7 +128,7 @@ class YamlFileLoader extends FileLoader
return array_keys($this->classes);
}
private function getClassesFromYaml()
private function getClassesFromYaml(): array
{
if (!stream_is_local($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);
}
private function getCacheValueForNormalization(string $propertyName, string $class)
private function getCacheValueForNormalization(string $propertyName, string $class): ?string
{
if (!$this->metadataFactory->hasMetadataFor($class)) {
return null;
@ -83,12 +83,12 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface
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;
}
private function getCacheValueForDenormalization(string $propertyName, string $class)
private function getCacheValueForDenormalization(string $propertyName, string $class): ?string
{
if (!isset(self::$attributesMetadataCache[$class])) {
self::$attributesMetadataCache[$class] = $this->getCacheValueForAttributesMetadata($class);
@ -97,7 +97,7 @@ final class MetadataAwareNameConverter implements AdvancedNameConverterInterface
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;
}

View File

@ -132,7 +132,7 @@ class DateIntervalNormalizer implements NormalizerInterface, DenormalizerInterfa
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);
}

View File

@ -154,7 +154,7 @@ class DateTimeNormalizer implements NormalizerInterface, DenormalizerInterface,
return $formattedErrors;
}
private function getTimezone(array $context)
private function getTimezone(array $context): ?\DateTimeZone
{
$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
*/
private function formatTime(float $time)
private function formatTime(float $time): float
{
return round($time, 1);
}

View File

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

View File

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

View File

@ -119,7 +119,7 @@ EOF;
return 'po';
}
private function escape(string $str)
private function escape(string $str): string
{
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];

View File

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

View File

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

View File

@ -410,7 +410,7 @@ EOF
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';
}
@ -418,7 +418,7 @@ EOF
/**
* @internal
*/
protected function doLoadCatalogue($locale): void
protected function doLoadCatalogue(string $locale): void
{
$this->catalogues[$locale] = new MessageCatalogue($locale);