minor #33519 Add types to constructors and private/final/internal methods (Batch I) (derrabus)

This PR was squashed before being merged into the 4.4 branch (closes #33519).

Discussion
----------

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

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | no
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #32179, #33228
| License       | MIT
| Doc PR        | N/A

As promised, now a larger batch with the following components:
* Asset
* BrowserKit
* Config
* Console
* ~~CssSelector~~
* Debug
* ~~DomCrawler~~
* DotEnv
* ErrorHandler
* ErrorRenderer
* ExpressionLanguage
* ~~Filesystem~~
* ~~Finder~~

Commits
-------

4039b95d22 Add types to constructors and private/final/internal methods (Batch I)
This commit is contained in:
Fabien Potencier 2019-09-27 07:43:13 +02:00
commit b1f6d0dbce
34 changed files with 69 additions and 66 deletions

View File

@ -68,6 +68,9 @@ class Package implements PackageInterface
return $this->versionStrategy; return $this->versionStrategy;
} }
/**
* @return bool
*/
protected function isAbsoluteUrl($url) protected function isAbsoluteUrl($url)
{ {
return false !== strpos($url, '://') || '//' === substr($url, 0, 2); return false !== strpos($url, '://') || '//' === substr($url, 0, 2);

View File

@ -50,7 +50,7 @@ class JsonManifestVersionStrategy implements VersionStrategyInterface
return $this->getManifestPath($path) ?: $path; return $this->getManifestPath($path) ?: $path;
} }
private function getManifestPath(string $path) private function getManifestPath(string $path): ?string
{ {
if (null === $this->manifestData) { if (null === $this->manifestData) {
if (!file_exists($this->manifestPath)) { if (!file_exists($this->manifestPath)) {

View File

@ -710,7 +710,7 @@ abstract class Client
return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory); return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
} }
private function updateServerFromUri(array $server, string $uri) private function updateServerFromUri(array $server, string $uri): array
{ {
$server['HTTP_HOST'] = $this->extractHost($uri); $server['HTTP_HOST'] = $this->extractHost($uri);
$scheme = parse_url($uri, PHP_URL_SCHEME); $scheme = parse_url($uri, PHP_URL_SCHEME);
@ -720,7 +720,7 @@ abstract class Client
return $server; return $server;
} }
private function extractHost(string $uri) private function extractHost(string $uri): ?string
{ {
$host = parse_url($uri, PHP_URL_HOST); $host = parse_url($uri, PHP_URL_HOST);

View File

@ -174,7 +174,7 @@ class GlobResource implements \IteratorAggregate, SelfCheckingResourceInterface
} }
} }
private function computeHash() private function computeHash(): string
{ {
$hash = hash_init('md5'); $hash = hash_init('md5');

View File

@ -98,7 +98,7 @@ class ReflectionClassResource implements SelfCheckingResourceInterface
} while ($class = $class->getParentClass()); } while ($class = $class->getParentClass());
} }
private function computeHash() private function computeHash(): string
{ {
if (null === $this->classReflector) { if (null === $this->classReflector) {
try { try {
@ -117,7 +117,7 @@ class ReflectionClassResource implements SelfCheckingResourceInterface
return hash_final($hash); return hash_final($hash);
} }
private function generateSignature(\ReflectionClass $class) private function generateSignature(\ReflectionClass $class): iterable
{ {
yield $class->getDocComment(); yield $class->getDocComment();
yield (int) $class->isFinal(); yield (int) $class->isFinal();

View File

@ -1125,12 +1125,12 @@ class Application implements ResetInterface
/** /**
* @internal * @internal
*/ */
public function isSingleCommand() public function isSingleCommand(): bool
{ {
return $this->singleCommand; return $this->singleCommand;
} }
private function splitStringByWidth(string $string, int $width) private function splitStringByWidth(string $string, int $width): array
{ {
// str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly. // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
// additionally, array_slice() is not enough as some character has doubled width. // additionally, array_slice() is not enough as some character has doubled width.

View File

@ -76,10 +76,7 @@ EOF
]); ]);
} }
/** private function createDefinition(): InputDefinition
* {@inheritdoc}
*/
private function createDefinition()
{ {
return new InputDefinition([ return new InputDefinition([
new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'), new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'),

View File

@ -167,7 +167,7 @@ class MarkdownDescriptor extends Descriptor
} }
} }
private function getApplicationTitle(Application $application) private function getApplicationTitle(Application $application): string
{ {
if ('UNKNOWN' !== $application->getName()) { if ('UNKNOWN' !== $application->getName()) {
if ('UNKNOWN' !== $application->getVersion()) { if ('UNKNOWN' !== $application->getVersion()) {

View File

@ -77,7 +77,7 @@ class ErrorListener implements EventSubscriberInterface
]; ];
} }
private static function getInputString(ConsoleEvent $event) private static function getInputString(ConsoleEvent $event): ?string
{ {
$commandName = $event->getCommand() ? $event->getCommand()->getName() : null; $commandName = $event->getCommand() ? $event->getCommand()->getName() : null;
$input = $event->getInput(); $input = $event->getInput();

View File

@ -135,7 +135,7 @@ class ProcessHelper extends Helper
}; };
} }
private function escapeString(string $str) private function escapeString(string $str): string
{ {
return str_replace('<', '\\<', $str); return str_replace('<', '\\<', $str);
} }

View File

@ -200,7 +200,7 @@ class ProgressIndicator
}, $this->format)); }, $this->format));
} }
private function determineBestFormat() private function determineBestFormat(): string
{ {
switch ($this->output->getVerbosity()) { switch ($this->output->getVerbosity()) {
// OutputInterface::VERBOSITY_QUIET: display is disabled anyway // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
@ -227,12 +227,12 @@ class ProgressIndicator
} }
} }
private function getCurrentTimeInMilliseconds() private function getCurrentTimeInMilliseconds(): float
{ {
return round(microtime(true) * 1000); return round(microtime(true) * 1000);
} }
private static function initPlaceholderFormatters() private static function initPlaceholderFormatters(): array
{ {
return [ return [
'indicator' => function (self $indicator) { 'indicator' => function (self $indicator) {
@ -250,7 +250,7 @@ class ProgressIndicator
]; ];
} }
private static function initFormats() private static function initFormats(): array
{ {
return [ return [
'normal' => ' %indicator% %message%', 'normal' => ' %indicator% %message%',

View File

@ -336,7 +336,7 @@ class QuestionHelper extends Helper
return $fullChoice; return $fullChoice;
} }
private function mostRecentlyEnteredValue(string $entered) private function mostRecentlyEnteredValue(string $entered): string
{ {
// Determine the most recent value that the user entered // Determine the most recent value that the user entered
if (false === strpos($entered, ',')) { if (false === strpos($entered, ',')) {

View File

@ -468,7 +468,7 @@ class Table
/** /**
* Renders vertical column separator. * Renders vertical column separator.
*/ */
private function renderColumnSeparator(int $type = self::BORDER_OUTSIDE) private function renderColumnSeparator(int $type = self::BORDER_OUTSIDE): string
{ {
$borders = $this->style->getBorderChars(); $borders = $this->style->getBorderChars();
@ -501,7 +501,7 @@ class Table
/** /**
* Renders table cell with padding. * Renders table cell with padding.
*/ */
private function renderCell(array $row, int $column, string $cellFormat) private function renderCell(array $row, int $column, string $cellFormat): string
{ {
$cell = isset($row[$column]) ? $row[$column] : ''; $cell = isset($row[$column]) ? $row[$column] : '';
$width = $this->effectiveColumnWidths[$column]; $width = $this->effectiveColumnWidths[$column];
@ -546,7 +546,7 @@ class Table
$this->numberOfColumns = max($columns); $this->numberOfColumns = max($columns);
} }
private function buildTableRows(array $rows) private function buildTableRows(array $rows): TableRows
{ {
/** @var WrappableOutputFormatterInterface $formatter */ /** @var WrappableOutputFormatterInterface $formatter */
$formatter = $this->output->getFormatter(); $formatter = $this->output->getFormatter();
@ -580,7 +580,7 @@ class Table
} }
} }
return new TableRows(function () use ($rows, $unmergedRows) { return new TableRows(function () use ($rows, $unmergedRows): \Traversable {
foreach ($rows as $rowKey => $row) { foreach ($rows as $rowKey => $row) {
yield $this->fillCells($row); yield $this->fillCells($row);
@ -784,7 +784,7 @@ class Table
$this->numberOfColumns = null; $this->numberOfColumns = null;
} }
private static function initStyles() private static function initStyles(): array
{ {
$borderless = new TableStyle(); $borderless = new TableStyle();
$borderless $borderless
@ -831,7 +831,7 @@ class Table
]; ];
} }
private function resolveStyle($name) private function resolveStyle($name): TableStyle
{ {
if ($name instanceof TableStyle) { if ($name instanceof TableStyle) {
return $name; return $name;

View File

@ -192,7 +192,7 @@ class TableStyle
* *
* @internal * @internal
*/ */
public function getBorderChars() public function getBorderChars(): array
{ {
return [ return [
$this->horizontalOutsideBorderChar, $this->horizontalOutsideBorderChar,

View File

@ -454,7 +454,7 @@ class SymfonyStyle extends OutputStyle
$this->bufferedOutput->write(substr($message, -4), $newLine, $type); $this->bufferedOutput->write(substr($message, -4), $newLine, $type);
} }
private function createBlock(iterable $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = false) private function createBlock(iterable $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = false): array
{ {
$indentLength = 0; $indentLength = 0;
$prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix); $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);

View File

@ -162,6 +162,9 @@ trait TesterTrait
} }
} }
/**
* @return resource
*/
private static function createStream(array $inputs) private static function createStream(array $inputs)
{ {
$stream = fopen('php://memory', 'r+', false); $stream = fopen('php://memory', 'r+', false);

View File

@ -444,7 +444,7 @@ class DebugClassLoader
/** /**
* `realpath` on MacOSX doesn't normalize the case of characters. * `realpath` on MacOSX doesn't normalize the case of characters.
*/ */
private function darwinRealpath(string $real) private function darwinRealpath(string $real): string
{ {
$i = 1 + strrpos($real, '/'); $i = 1 + strrpos($real, '/');
$file = substr($real, $i); $file = substr($real, $i);

View File

@ -691,7 +691,7 @@ class ErrorHandler
/** /**
* Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader. * Cleans the trace by removing function arguments and the frames added by the error handler and DebugClassLoader.
*/ */
private function cleanTrace(array $backtrace, int $type, string $file, int $line, bool $throw) private function cleanTrace(array $backtrace, int $type, string $file, int $line, bool $throw): array
{ {
$lightTrace = $backtrace; $lightTrace = $backtrace;

View File

@ -289,7 +289,7 @@ class FlattenException
return $this; return $this;
} }
private function flattenArgs(array $args, int $level = 0, int &$count = 0) private function flattenArgs(array $args, int $level = 0, int &$count = 0): array
{ {
$result = []; $result = [];
foreach ($args as $key => $value) { foreach ($args as $key => $value) {
@ -325,7 +325,7 @@ class FlattenException
return $result; return $result;
} }
private function getClassNameFromIncomplete(\__PHP_Incomplete_Class $value) private function getClassNameFromIncomplete(\__PHP_Incomplete_Class $value): string
{ {
$array = new \ArrayObject($value); $array = new \ArrayObject($value);

File diff suppressed because one or more lines are too long

View File

@ -216,7 +216,7 @@ final class Dotenv
} }
} }
private function lexVarname() private function lexVarname(): string
{ {
// var name + optional export // var name + optional export
if (!preg_match('/(export[ \t]++)?('.self::VARNAME_REGEX.')/A', $this->data, $matches, 0, $this->cursor)) { if (!preg_match('/(export[ \t]++)?('.self::VARNAME_REGEX.')/A', $this->data, $matches, 0, $this->cursor)) {
@ -244,7 +244,7 @@ final class Dotenv
return $matches[2]; return $matches[2];
} }
private function lexValue() private function lexValue(): string
{ {
if (preg_match('/[ \t]*+(?:#.*)?$/Am', $this->data, $matches, 0, $this->cursor)) { if (preg_match('/[ \t]*+(?:#.*)?$/Am', $this->data, $matches, 0, $this->cursor)) {
$this->moveCursor($matches[0]); $this->moveCursor($matches[0]);
@ -339,7 +339,7 @@ final class Dotenv
return $v; return $v;
} }
private function lexNestedExpression() private function lexNestedExpression(): string
{ {
++$this->cursor; ++$this->cursor;
$value = ''; $value = '';
@ -372,7 +372,7 @@ final class Dotenv
} }
} }
private function resolveCommands(string $value) private function resolveCommands(string $value): string
{ {
if (false === strpos($value, '$')) { if (false === strpos($value, '$')) {
return $value; return $value;
@ -419,7 +419,7 @@ final class Dotenv
}, $value); }, $value);
} }
private function resolveVariables(string $value) private function resolveVariables(string $value): string
{ {
if (false === strpos($value, '$')) { if (false === strpos($value, '$')) {
return $value; return $value;
@ -487,7 +487,7 @@ final class Dotenv
$this->lineno += substr_count($text, "\n"); $this->lineno += substr_count($text, "\n");
} }
private function createFormatException(string $message) private function createFormatException(string $message): FormatException
{ {
return new FormatException($message, new FormatExceptionContext($this->data, $this->path, $this->lineno, $this->cursor)); return new FormatException($message, new FormatExceptionContext($this->data, $this->path, $this->lineno, $this->cursor));
} }

View File

@ -27,7 +27,7 @@ final class FormatException extends \LogicException implements ExceptionInterfac
parent::__construct(sprintf("%s in \"%s\" at line %d.\n%s", $message, $context->getPath(), $context->getLineno(), $context->getDetails()), $code, $previous); parent::__construct(sprintf("%s in \"%s\" at line %d.\n%s", $message, $context->getPath(), $context->getLineno(), $context->getDetails()), $code, $previous);
} }
public function getContext() public function getContext(): FormatExceptionContext
{ {
return $this->context; return $this->context;
} }

View File

@ -29,17 +29,17 @@ final class FormatExceptionContext
$this->cursor = $cursor; $this->cursor = $cursor;
} }
public function getPath() public function getPath(): string
{ {
return $this->path; return $this->path;
} }
public function getLineno() public function getLineno(): int
{ {
return $this->lineno; return $this->lineno;
} }
public function getDetails() public function getDetails(): string
{ {
$before = str_replace("\n", '\n', substr($this->data, max(0, $this->cursor - 20), min(20, $this->cursor))); $before = str_replace("\n", '\n', substr($this->data, max(0, $this->cursor - 20), min(20, $this->cursor)));
$after = str_replace("\n", '\n', substr($this->data, $this->cursor, 20)); $after = str_replace("\n", '\n', substr($this->data, $this->cursor, 20));

View File

@ -118,7 +118,7 @@ class DebugClassLoaderTest extends TestCase
/** /**
* @dataProvider provideDeprecatedSuper * @dataProvider provideDeprecatedSuper
*/ */
public function testDeprecatedSuper($class, $super, $type) public function testDeprecatedSuper(string $class, string $super, string $type)
{ {
set_error_handler(function () { return false; }); set_error_handler(function () { return false; });
$e = error_reporting(0); $e = error_reporting(0);
@ -140,7 +140,7 @@ class DebugClassLoaderTest extends TestCase
$this->assertSame($xError, $lastError); $this->assertSame($xError, $lastError);
} }
public function provideDeprecatedSuper() public function provideDeprecatedSuper(): array
{ {
return [ return [
['DeprecatedInterfaceClass', 'DeprecatedInterface', 'implements'], ['DeprecatedInterfaceClass', 'DeprecatedInterface', 'implements'],

View File

@ -572,7 +572,7 @@ class ErrorHandlerTest extends TestCase
/** /**
* @dataProvider errorHandlerWhenLoggingProvider * @dataProvider errorHandlerWhenLoggingProvider
*/ */
public function testErrorHandlerWhenLogging($previousHandlerWasDefined, $loggerSetsAnotherHandler, $nextHandlerIsDefined) public function testErrorHandlerWhenLogging(bool $previousHandlerWasDefined, bool $loggerSetsAnotherHandler, bool $nextHandlerIsDefined)
{ {
try { try {
if ($previousHandlerWasDefined) { if ($previousHandlerWasDefined) {
@ -612,7 +612,7 @@ class ErrorHandlerTest extends TestCase
} }
} }
public function errorHandlerWhenLoggingProvider() public function errorHandlerWhenLoggingProvider(): iterable
{ {
foreach ([false, true] as $previousHandlerWasDefined) { foreach ([false, true] as $previousHandlerWasDefined) {
foreach ([false, true] as $loggerSetsAnotherHandler) { foreach ([false, true] as $loggerSetsAnotherHandler) {

View File

@ -41,7 +41,7 @@ class ClassNotFoundFatalErrorHandlerTest extends TestCase
/** /**
* @dataProvider provideClassNotFoundData * @dataProvider provideClassNotFoundData
*/ */
public function testHandleClassNotFound($error, $translatedMessage, $autoloader = null) public function testHandleClassNotFound(array $error, string $translatedMessage, callable $autoloader = null)
{ {
if ($autoloader) { if ($autoloader) {
// Unregister all autoloaders to ensure the custom provided // Unregister all autoloaders to ensure the custom provided
@ -67,7 +67,7 @@ class ClassNotFoundFatalErrorHandlerTest extends TestCase
$this->assertSame($error['line'], $exception->getLine()); $this->assertSame($error['line'], $exception->getLine());
} }
public function provideClassNotFoundData() public function provideClassNotFoundData(): array
{ {
$autoloader = new ComposerClassLoader(); $autoloader = new ComposerClassLoader();
$autoloader->add('Symfony\Component\ErrorHandler\Exception\\', realpath(__DIR__.'/../../Exception')); $autoloader->add('Symfony\Component\ErrorHandler\Exception\\', realpath(__DIR__.'/../../Exception'));

View File

@ -20,7 +20,7 @@ class UndefinedFunctionFatalErrorHandlerTest extends TestCase
/** /**
* @dataProvider provideUndefinedFunctionData * @dataProvider provideUndefinedFunctionData
*/ */
public function testUndefinedFunction($error, $translatedMessage) public function testUndefinedFunction(array $error, string $translatedMessage)
{ {
$handler = new UndefinedFunctionFatalErrorHandler(); $handler = new UndefinedFunctionFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line'])); $exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
@ -33,7 +33,7 @@ class UndefinedFunctionFatalErrorHandlerTest extends TestCase
$this->assertSame($error['line'], $exception->getLine()); $this->assertSame($error['line'], $exception->getLine());
} }
public function provideUndefinedFunctionData() public function provideUndefinedFunctionData(): array
{ {
return [ return [
[ [

View File

@ -20,7 +20,7 @@ class UndefinedMethodFatalErrorHandlerTest extends TestCase
/** /**
* @dataProvider provideUndefinedMethodData * @dataProvider provideUndefinedMethodData
*/ */
public function testUndefinedMethod($error, $translatedMessage) public function testUndefinedMethod(array $error, string $translatedMessage)
{ {
$handler = new UndefinedMethodFatalErrorHandler(); $handler = new UndefinedMethodFatalErrorHandler();
$exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line'])); $exception = $handler->handleError($error, new FatalErrorException('', 0, $error['type'], $error['file'], $error['line']));
@ -32,7 +32,7 @@ class UndefinedMethodFatalErrorHandlerTest extends TestCase
$this->assertSame($error['line'], $exception->getLine()); $this->assertSame($error['line'], $exception->getLine());
} }
public function provideUndefinedMethodData() public function provideUndefinedMethodData(): array
{ {
return [ return [
[ [

View File

@ -302,7 +302,7 @@ class FlattenException
return $this; return $this;
} }
private function flattenArgs(array $args, int $level = 0, int &$count = 0) private function flattenArgs(array $args, int $level = 0, int &$count = 0): array
{ {
$result = []; $result = [];
foreach ($args as $key => $value) { foreach ($args as $key => $value) {
@ -338,7 +338,7 @@ class FlattenException
return $result; return $result;
} }
private function getClassNameFromIncomplete(\__PHP_Incomplete_Class $value) private function getClassNameFromIncomplete(\__PHP_Incomplete_Class $value): string
{ {
$array = new \ArrayObject($value); $array = new \ArrayObject($value);

View File

@ -26,7 +26,7 @@ class HtmlErrorRendererTest extends TestCase
$this->assertStringMatchesFormat($expected, $errorRenderer->render($exception)); $this->assertStringMatchesFormat($expected, $errorRenderer->render($exception));
} }
public function getRenderData() public function getRenderData(): iterable
{ {
$expectedDebug = <<<HTML $expectedDebug = <<<HTML
<!-- Foo (500 Internal Server Error) --> <!-- Foo (500 Internal Server Error) -->

View File

@ -26,7 +26,7 @@ class JsonErrorRendererTest extends TestCase
$this->assertStringMatchesFormat($expected, $errorRenderer->render($exception)); $this->assertStringMatchesFormat($expected, $errorRenderer->render($exception));
} }
public function getRenderData() public function getRenderData(): iterable
{ {
$expectedDebug = <<<JSON $expectedDebug = <<<JSON
{ {

View File

@ -26,7 +26,7 @@ class TxtErrorRendererTest extends TestCase
$this->assertStringMatchesFormat($expected, $errorRenderer->render($exception)); $this->assertStringMatchesFormat($expected, $errorRenderer->render($exception));
} }
public function getRenderData() public function getRenderData(): iterable
{ {
$expectedDebug = <<<TXT $expectedDebug = <<<TXT
[title] Internal Server Error [title] Internal Server Error

View File

@ -26,7 +26,7 @@ class XmlErrorRendererTest extends TestCase
$this->assertStringMatchesFormat($expected, $errorRenderer->render($exception)); $this->assertStringMatchesFormat($expected, $errorRenderer->render($exception));
} }
public function getRenderData() public function getRenderData(): iterable
{ {
$expectedDebug = <<<XML $expectedDebug = <<<XML
<?xml version="1.0" encoding="UTF-8" ?> <?xml version="1.0" encoding="UTF-8" ?>

View File

@ -227,7 +227,7 @@ class FlattenExceptionTest extends TestCase
); );
} }
public function flattenDataProvider() public function flattenDataProvider(): array
{ {
return [ return [
[new \Exception('test', 123), 'Exception'], [new \Exception('test', 123), 'Exception'],
@ -381,7 +381,7 @@ class FlattenExceptionTest extends TestCase
$this->assertSame($exception->__toString(), $flattened->getAsString()); $this->assertSame($exception->__toString(), $flattened->getAsString());
} }
private function createException($foo) private function createException($foo): \Exception
{ {
return new \Exception(); return new \Exception();
} }