From 6ce70e4bf98a193212d44fba95bbe2e61ad7b019 Mon Sep 17 00:00:00 2001 From: Robin Chalas Date: Sat, 5 Aug 2017 16:43:05 +0200 Subject: [PATCH 1/2] Add scalar typehints/return types on final/internal/private code --- .../Doctrine/Form/ChoiceList/IdReader.php | 6 +- .../SecurityBundle/Debug/WrappedListener.php | 4 +- .../Security/FirewallConfig.php | 63 ++----- .../Tests/Security/FirewallMapTest.php | 3 +- .../Component/Config/Loader/FileLoader.php | 6 +- .../Console/Event/ConsoleErrorEvent.php | 53 ++---- .../Component/Console/Helper/ProgressBar.php | 172 +++++------------- .../Component/Console/Style/SymfonyStyle.php | 17 +- .../CssSelector/Node/AbstractNode.php | 2 +- .../CssSelector/Node/AttributeNode.php | 4 +- .../Component/CssSelector/Node/ClassNode.php | 4 +- .../CssSelector/Node/CombinedSelectorNode.php | 4 +- .../CssSelector/Node/ElementNode.php | 4 +- .../CssSelector/Node/FunctionNode.php | 4 +- .../Component/CssSelector/Node/HashNode.php | 4 +- .../CssSelector/Node/NegationNode.php | 4 +- .../CssSelector/Node/NodeInterface.php | 21 +-- .../Component/CssSelector/Node/PseudoNode.php | 4 +- .../CssSelector/Node/SelectorNode.php | 4 +- .../CssSelector/Node/Specificity.php | 23 +-- .../Parser/Handler/CommentHandler.php | 2 +- .../Parser/Handler/HandlerInterface.php | 2 +- .../Parser/Handler/HashHandler.php | 2 +- .../Parser/Handler/IdentifierHandler.php | 2 +- .../Parser/Handler/NumberHandler.php | 2 +- .../Parser/Handler/StringHandler.php | 2 +- .../Parser/Handler/WhitespaceHandler.php | 2 +- .../Component/CssSelector/Parser/Parser.php | 43 +---- .../CssSelector/Parser/ParserInterface.php | 2 +- .../Parser/Shortcut/ClassParser.php | 2 +- .../Parser/Shortcut/ElementParser.php | 2 +- .../Parser/Shortcut/EmptyStringParser.php | 2 +- .../Parser/Shortcut/HashParser.php | 2 +- .../Component/CssSelector/Parser/Token.php | 44 +---- .../Parser/Tokenizer/TokenizerEscaping.php | 24 +-- .../XPath/Extension/CombinationExtension.php | 4 +- .../CssSelector/XPath/Translator.php | 72 ++------ .../CssSelector/XPath/TranslatorInterface.php | 4 +- .../Component/CssSelector/XPath/XPathExpr.php | 39 +--- src/Symfony/Component/Dotenv/Dotenv.php | 6 +- .../ExpressionLanguage/ExpressionLanguage.php | 6 +- .../ExpressionLanguage/Node/UnaryNode.php | 4 +- src/Symfony/Component/Form/Forms.php | 4 +- .../Controller/ArgumentResolver.php | 4 +- .../AbstractSurrogateFragmentRenderer.php | 4 +- .../Fragment/HIncludeFragmentRenderer.php | 7 +- .../Component/HttpKernel/HttpKernel.php | 10 +- src/Symfony/Component/Inflector/Inflector.php | 4 +- .../Data/Provider/LanguageDataProvider.php | 2 +- .../DateFormat/AmPmTransformer.php | 6 +- .../DateFormat/DayOfWeekTransformer.php | 6 +- .../DateFormat/DayOfYearTransformer.php | 6 +- .../DateFormat/DayTransformer.php | 6 +- .../DateFormat/Hour1200Transformer.php | 8 +- .../DateFormat/Hour1201Transformer.php | 8 +- .../DateFormat/Hour2400Transformer.php | 8 +- .../DateFormat/Hour2401Transformer.php | 8 +- .../DateFormat/HourTransformer.php | 2 +- .../DateFormat/MinuteTransformer.php | 6 +- .../DateFormat/MonthTransformer.php | 6 +- .../DateFormat/QuarterTransformer.php | 6 +- .../DateFormat/SecondTransformer.php | 6 +- .../DateFormat/TimezoneTransformer.php | 6 +- .../DateFormatter/DateFormat/Transformer.php | 8 +- .../DateFormat/YearTransformer.php | 6 +- src/Symfony/Component/Intl/Locale.php | 8 +- .../Intl/ResourceBundle/LanguageBundle.php | 10 +- src/Symfony/Component/Ldap/Ldap.php | 2 +- src/Symfony/Component/Lock/Key.php | 29 +-- .../PropertyAccess/PropertyAccess.php | 9 +- .../Extractor/ReflectionExtractor.php | 24 ++- .../PropertyInfo/Util/PhpDocTypeHelper.php | 26 +-- .../Routing/Matcher/Dumper/DumperRoute.php | 22 +-- .../Matcher/Dumper/StaticPrefixCollection.php | 20 +- .../Routing/RouteCollectionBuilder.php | 4 +- .../RememberMe/PersistentToken.php | 13 +- .../Http/Firewall/ExceptionListener.php | 17 +- .../Component/Translation/Translator.php | 15 +- .../Component/Validator/Validation.php | 4 +- .../WebLink/HttpHeaderSerializer.php | 2 +- src/Symfony/Component/Workflow/Definition.php | 10 +- .../Workflow/Dumper/GraphvizDumper.php | 4 +- .../Workflow/EventListener/GuardListener.php | 2 +- src/Symfony/Component/Workflow/Registry.php | 2 +- .../ClassInstanceSupportStrategy.php | 5 +- .../Component/Yaml/Tag/TaggedValue.php | 14 +- 86 files changed, 311 insertions(+), 744 deletions(-) diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php index 4140629d93..a04be3a790 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php @@ -82,7 +82,7 @@ class IdReader * @return bool Returns `true` if the class has a single-column ID and * `false` otherwise. */ - public function isSingleId() + public function isSingleId(): bool { return $this->singleId; } @@ -93,7 +93,7 @@ class IdReader * @return bool Returns `true` if the class has a single-column integer ID * and `false` otherwise. */ - public function isIntId() + public function isIntId(): bool { return $this->intId; } @@ -138,7 +138,7 @@ class IdReader * * @return string The name of the ID field */ - public function getIdField() + public function getIdField(): string { return $this->idField; } diff --git a/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php b/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php index 435ecc5feb..85878e2193 100644 --- a/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php +++ b/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php @@ -56,12 +56,12 @@ final class WrappedListener implements ListenerInterface return call_user_func_array(array($this->listener, $method), $arguments); } - public function getWrappedListener() + public function getWrappedListener(): ListenerInterface { return $this->listener; } - public function getInfo() + public function getInfo(): array { if (null === $this->stub) { $this->stub = self::$hasVarDumper ? new ClassStub(get_class($this->listener)) : get_class($this->listener); diff --git a/src/Symfony/Bundle/SecurityBundle/Security/FirewallConfig.php b/src/Symfony/Bundle/SecurityBundle/Security/FirewallConfig.php index 62317f625c..308442810b 100644 --- a/src/Symfony/Bundle/SecurityBundle/Security/FirewallConfig.php +++ b/src/Symfony/Bundle/SecurityBundle/Security/FirewallConfig.php @@ -29,21 +29,7 @@ final class FirewallConfig private $listeners; private $switchUser; - /** - * @param string $name - * @param string $userChecker - * @param string|null $requestMatcher - * @param bool $securityEnabled - * @param bool $stateless - * @param string|null $provider - * @param string|null $context - * @param string|null $entryPoint - * @param string|null $accessDeniedHandler - * @param string|null $accessDeniedUrl - * @param string[] $listeners - * @param array|null $switchUser - */ - public function __construct($name, $userChecker, $requestMatcher = null, $securityEnabled = true, $stateless = false, $provider = null, $context = null, $entryPoint = null, $accessDeniedHandler = null, $accessDeniedUrl = null, $listeners = array(), $switchUser = null) + public function __construct(string $name, string $userChecker, string $requestMatcher = null, bool $securityEnabled = true, bool $stateless = false, string $provider = null, string $context = null, string $entryPoint = null, string $accessDeniedHandler = null, string $accessDeniedUrl = null, array $listeners = array(), $switchUser = null) { $this->name = $name; $this->userChecker = $userChecker; @@ -59,7 +45,7 @@ final class FirewallConfig $this->switchUser = $switchUser; } - public function getName() + public function getName(): string { return $this->name; } @@ -68,30 +54,27 @@ final class FirewallConfig * @return string|null The request matcher service id or null if neither the request matcher, pattern or host * options were provided */ - public function getRequestMatcher() + public function getRequestMatcher(): ?string { return $this->requestMatcher; } - public function isSecurityEnabled() + public function isSecurityEnabled(): bool { return $this->securityEnabled; } - public function allowsAnonymous() + public function allowsAnonymous(): bool { return in_array('anonymous', $this->listeners, true); } - public function isStateless() + public function isStateless(): bool { return $this->stateless; } - /** - * @return string|null The provider service id - */ - public function getProvider() + public function getProvider(): ?string { return $this->provider; } @@ -99,55 +82,37 @@ final class FirewallConfig /** * @return string|null The context key (will be null if the firewall is stateless) */ - public function getContext() + public function getContext(): ?string { return $this->context; } - /** - * @return string|null The entry_point service id if configured, null otherwise - */ - public function getEntryPoint() + public function getEntryPoint(): ?string { return $this->entryPoint; } - /** - * @return string The user_checker service id - */ - public function getUserChecker() + public function getUserChecker(): string { return $this->userChecker; } - /** - * @return string|null The access_denied_handler service id if configured, null otherwise - */ - public function getAccessDeniedHandler() + public function getAccessDeniedHandler(): ?string { return $this->accessDeniedHandler; } - /** - * @return string|null The access_denied_handler URL if configured, null otherwise - */ - public function getAccessDeniedUrl() + public function getAccessDeniedUrl(): ?string { return $this->accessDeniedUrl; } - /** - * @return string[] An array of listener keys - */ - public function getListeners() + public function getListeners(): array { return $this->listeners; } - /** - * @return array|null The switch_user parameters if configured, null otherwise - */ - public function getSwitchUser() + public function getSwitchUser(): ?array { return $this->switchUser; } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php index f9047cfdd2..3e6f0a1ac7 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallMapTest.php @@ -18,7 +18,6 @@ use Symfony\Bundle\SecurityBundle\Security\FirewallMap; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestMatcherInterface; -use Symfony\Component\Security\Core\User\UserCheckerInterface; use Symfony\Component\Security\Http\Firewall\ExceptionListener; use Symfony\Component\Security\Http\Firewall\ListenerInterface; @@ -63,7 +62,7 @@ class FirewallMapTest extends TestCase $firewallContext = $this->getMockBuilder(FirewallContext::class)->disableOriginalConstructor()->getMock(); - $firewallConfig = new FirewallConfig('main', $this->getMockBuilder(UserCheckerInterface::class)->getMock()); + $firewallConfig = new FirewallConfig('main', 'user_checker'); $firewallContext->expects($this->once())->method('getConfig')->willReturn($firewallConfig); $listener = $this->getMockBuilder(ListenerInterface::class)->getMock(); diff --git a/src/Symfony/Component/Config/Loader/FileLoader.php b/src/Symfony/Component/Config/Loader/FileLoader.php index 02aa811fc5..9fb5faa7a9 100644 --- a/src/Symfony/Component/Config/Loader/FileLoader.php +++ b/src/Symfony/Component/Config/Loader/FileLoader.php @@ -81,7 +81,7 @@ abstract class FileLoader extends Loader * @throws FileLoaderImportCircularReferenceException * @throws FileLocatorFileNotFoundException */ - public function import($resource, $type = null, $ignoreErrors = false, $sourceResource = null) + public function import($resource, $type = null, bool $ignoreErrors = false, $sourceResource = null) { if (is_string($resource) && strlen($resource) !== $i = strcspn($resource, '*?{[')) { $ret = array(); @@ -104,7 +104,7 @@ abstract class FileLoader extends Loader /** * @internal */ - protected function glob($pattern, $recursive, &$resource = null, $ignoreErrors = false) + protected function glob(string $pattern, bool $recursive, &$resource = null, bool $ignoreErrors = false) { if (strlen($pattern) === $i = strcspn($pattern, '*?{[')) { $prefix = $pattern; @@ -138,7 +138,7 @@ abstract class FileLoader extends Loader } } - private function doImport($resource, $type = null, $ignoreErrors = false, $sourceResource = null) + private function doImport($resource, $type = null, bool $ignoreErrors = false, $sourceResource = null) { try { $loader = $this->resolve($resource, $type); diff --git a/src/Symfony/Component/Console/Event/ConsoleErrorEvent.php b/src/Symfony/Component/Console/Event/ConsoleErrorEvent.php index 49edb723d2..038d97af8a 100644 --- a/src/Symfony/Component/Console/Event/ConsoleErrorEvent.php +++ b/src/Symfony/Component/Console/Event/ConsoleErrorEvent.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Console\Event; use Symfony\Component\Console\Command\Command; -use Symfony\Component\Console\Exception\InvalidArgumentException; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -26,57 +25,33 @@ final class ConsoleErrorEvent extends ConsoleEvent private $error; private $exitCode; - public function __construct(InputInterface $input, OutputInterface $output, $error, Command $command = null) + public function __construct(InputInterface $input, OutputInterface $output, \Throwable $error, Command $command = null) { parent::__construct($command, $input, $output); - $this->setError($error); - } - - /** - * Returns the thrown error/exception. - * - * @return \Throwable - */ - public function getError() - { - return $this->error; - } - - /** - * Replaces the thrown error/exception. - * - * @param \Throwable $error - */ - public function setError($error) - { - if (!$error instanceof \Throwable && !$error instanceof \Exception) { - throw new InvalidArgumentException(sprintf('The error passed to ConsoleErrorEvent must be an instance of \Throwable or \Exception, "%s" was passed instead.', is_object($error) ? get_class($error) : gettype($error))); - } - $this->error = $error; } - /** - * Sets the exit code. - * - * @param int $exitCode The command exit code - */ - public function setExitCode($exitCode) + public function getError(): \Throwable { - $this->exitCode = (int) $exitCode; + return $this->error; + } + + public function setError(\Throwable $error): void + { + $this->error = $error; + } + + public function setExitCode(int $exitCode): void + { + $this->exitCode = $exitCode; $r = new \ReflectionProperty($this->error, 'code'); $r->setAccessible(true); $r->setValue($this->error, $this->exitCode); } - /** - * Gets the exit code. - * - * @return int The command exit code - */ - public function getExitCode() + public function getExitCode(): int { return null !== $this->exitCode ? $this->exitCode : ($this->error->getCode() ?: 1); } diff --git a/src/Symfony/Component/Console/Helper/ProgressBar.php b/src/Symfony/Component/Console/Helper/ProgressBar.php index 31c49ef730..6177a87a83 100644 --- a/src/Symfony/Component/Console/Helper/ProgressBar.php +++ b/src/Symfony/Component/Console/Helper/ProgressBar.php @@ -55,7 +55,7 @@ final class ProgressBar * @param OutputInterface $output An OutputInterface instance * @param int $max Maximum steps (0 if unknown) */ - public function __construct(OutputInterface $output, $max = 0) + public function __construct(OutputInterface $output, int $max = 0) { if ($output instanceof ConsoleOutputInterface) { $output = $output->getErrorOutput(); @@ -84,7 +84,7 @@ final class ProgressBar * @param string $name The placeholder name (including the delimiter char like %) * @param callable $callable A PHP callable */ - public static function setPlaceholderFormatterDefinition($name, callable $callable) + public static function setPlaceholderFormatterDefinition(string $name, callable $callable): void { if (!self::$formatters) { self::$formatters = self::initPlaceholderFormatters(); @@ -100,7 +100,7 @@ final class ProgressBar * * @return callable|null A PHP callable */ - public static function getPlaceholderFormatterDefinition($name) + public static function getPlaceholderFormatterDefinition(string $name): ?callable { if (!self::$formatters) { self::$formatters = self::initPlaceholderFormatters(); @@ -117,7 +117,7 @@ final class ProgressBar * @param string $name The format name * @param string $format A format string */ - public static function setFormatDefinition($name, $format) + public static function setFormatDefinition(string $name, string $format): void { if (!self::$formats) { self::$formats = self::initFormats(); @@ -133,7 +133,7 @@ final class ProgressBar * * @return string|null A format string */ - public static function getFormatDefinition($name) + public static function getFormatDefinition(string $name): ?string { if (!self::$formats) { self::$formats = self::initFormats(); @@ -152,102 +152,57 @@ final class ProgressBar * @param string $message The text to associate with the placeholder * @param string $name The name of the placeholder */ - public function setMessage($message, $name = 'message') + public function setMessage(string $message, string $name = 'message') { $this->messages[$name] = $message; } - public function getMessage($name = 'message') + public function getMessage(string $name = 'message') { return $this->messages[$name]; } - /** - * Gets the progress bar start time. - * - * @return int The progress bar start time - */ - public function getStartTime() + public function getStartTime(): int { return $this->startTime; } - /** - * Gets the progress bar maximal steps. - * - * @return int The progress bar max steps - */ - public function getMaxSteps() + public function getMaxSteps(): int { return $this->max; } - /** - * Gets the current step position. - * - * @return int The progress bar step - */ - public function getProgress() + public function getProgress(): int { return $this->step; } - /** - * Gets the progress bar step width. - * - * @return int The progress bar step width - */ - private function getStepWidth() + private function getStepWidth(): int { return $this->stepWidth; } - /** - * Gets the current progress bar percent. - * - * @return float The current progress bar percent - */ - public function getProgressPercent() + public function getProgressPercent(): float { return $this->percent; } - /** - * Sets the progress bar width. - * - * @param int $size The progress bar size - */ - public function setBarWidth($size) + public function setBarWidth(int $size) { - $this->barWidth = max(1, (int) $size); + $this->barWidth = max(1, $size); } - /** - * Gets the progress bar width. - * - * @return int The progress bar size - */ - public function getBarWidth() + public function getBarWidth(): int { return $this->barWidth; } - /** - * Sets the bar character. - * - * @param string $char A character - */ - public function setBarCharacter($char) + public function setBarCharacter(string $char) { $this->barChar = $char; } - /** - * Gets the bar character. - * - * @return string A character - */ - public function getBarCharacter() + public function getBarCharacter(): string { if (null === $this->barChar) { return $this->max ? '=' : $this->emptyBarChar; @@ -256,52 +211,27 @@ final class ProgressBar return $this->barChar; } - /** - * Sets the empty bar character. - * - * @param string $char A character - */ - public function setEmptyBarCharacter($char) + public function setEmptyBarCharacter(string $char) { $this->emptyBarChar = $char; } - /** - * Gets the empty bar character. - * - * @return string A character - */ - public function getEmptyBarCharacter() + public function getEmptyBarCharacter(): string { return $this->emptyBarChar; } - /** - * Sets the progress bar character. - * - * @param string $char A character - */ - public function setProgressCharacter($char) + public function setProgressCharacter(string $char) { $this->progressChar = $char; } - /** - * Gets the progress bar character. - * - * @return string A character - */ - public function getProgressCharacter() + public function getProgressCharacter(): string { return $this->progressChar; } - /** - * Sets the progress bar format. - * - * @param string $format The format - */ - public function setFormat($format) + public function setFormat(string $format) { $this->format = null; $this->internalFormat = $format; @@ -312,9 +242,9 @@ final class ProgressBar * * @param int|float $freq The frequency in steps */ - public function setRedrawFrequency($freq) + public function setRedrawFrequency(int $freq) { - $this->redrawFreq = max((int) $freq, 1); + $this->redrawFreq = max($freq, 1); } /** @@ -322,7 +252,7 @@ final class ProgressBar * * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged */ - public function start($max = null) + public function start(int $max = null) { $this->startTime = time(); $this->step = 0; @@ -340,7 +270,7 @@ final class ProgressBar * * @param int $step Number of steps to advance */ - public function advance($step = 1) + public function advance(int $step = 1) { $this->setProgress($this->step + $step); } @@ -350,20 +280,13 @@ final class ProgressBar * * @param bool $overwrite */ - public function setOverwrite($overwrite) + public function setOverwrite(bool $overwrite) { - $this->overwrite = (bool) $overwrite; + $this->overwrite = $overwrite; } - /** - * Sets the current progress. - * - * @param int $step The current progress - */ - public function setProgress($step) + public function setProgress(int $step) { - $step = (int) $step; - if ($this->max && $step > $this->max) { $this->max = $step; } elseif ($step < 0) { @@ -382,7 +305,7 @@ final class ProgressBar /** * Finishes the progress output. */ - public function finish() + public function finish(): void { if (!$this->max) { $this->max = $this->step; @@ -399,7 +322,7 @@ final class ProgressBar /** * Outputs the current progress string. */ - public function display() + public function display(): void { if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) { return; @@ -419,7 +342,7 @@ final class ProgressBar * while a progress bar is running. * Call display() to show the progress bar again. */ - public function clear() + public function clear(): void { if (!$this->overwrite) { return; @@ -432,12 +355,7 @@ final class ProgressBar $this->overwrite(''); } - /** - * Sets the progress bar format. - * - * @param string $format The format - */ - private function setRealFormat($format) + private function setRealFormat(string $format) { // try to use the _nomax variant if available if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) { @@ -451,15 +369,10 @@ final class ProgressBar $this->formatLineCount = substr_count($this->format, "\n"); } - /** - * Sets the progress bar maximal steps. - * - * @param int $max The progress bar max steps - */ - private function setMaxSteps($max) + private function setMaxSteps(int $max) { - $this->max = max(0, (int) $max); - $this->stepWidth = $this->max ? Helper::strlen($this->max) : 4; + $this->max = max(0, $max); + $this->stepWidth = $this->max ? Helper::strlen((string) $this->max) : 4; } /** @@ -467,7 +380,7 @@ final class ProgressBar * * @param string $message The message */ - private function overwrite($message) + private function overwrite(string $message): void { if ($this->overwrite) { if (!$this->firstRun) { @@ -491,7 +404,7 @@ final class ProgressBar $this->output->write($message); } - private function determineBestFormat() + private function determineBestFormat(): string { switch ($this->output->getVerbosity()) { // OutputInterface::VERBOSITY_QUIET: display is disabled anyway @@ -506,7 +419,7 @@ final class ProgressBar } } - private static function initPlaceholderFormatters() + private static function initPlaceholderFormatters(): array { return array( 'bar' => function (ProgressBar $bar, OutputInterface $output) { @@ -563,7 +476,7 @@ final class ProgressBar ); } - private static function initFormats() + private static function initFormats(): array { return array( 'normal' => ' %current%/%max% [%bar%] %percent:3s%%', @@ -580,10 +493,7 @@ final class ProgressBar ); } - /** - * @return string - */ - private function buildLine() + private function buildLine(): string { $regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i"; $callback = function ($matches) { diff --git a/src/Symfony/Component/Console/Style/SymfonyStyle.php b/src/Symfony/Component/Console/Style/SymfonyStyle.php index a867961767..c15ae46600 100644 --- a/src/Symfony/Component/Console/Style/SymfonyStyle.php +++ b/src/Symfony/Component/Console/Style/SymfonyStyle.php @@ -344,10 +344,7 @@ class SymfonyStyle extends OutputStyle return new self($this->input, $this->getErrorOutput()); } - /** - * @return ProgressBar - */ - private function getProgressBar() + private function getProgressBar(): ProgressBar { if (!$this->progressBar) { throw new RuntimeException('The ProgressBar is not started.'); @@ -356,18 +353,20 @@ class SymfonyStyle extends OutputStyle return $this->progressBar; } - private function autoPrependBlock() + private function autoPrependBlock(): void { $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2); if (!isset($chars[0])) { - return $this->newLine(); //empty history, so we should start with a new line. + $this->newLine(); //empty history, so we should start with a new line. + + return; } //Prepend new line for each non LF chars (This means no blank line was output before) $this->newLine(2 - substr_count($chars, "\n")); } - private function autoPrependText() + private function autoPrependText(): void { $fetched = $this->bufferedOutput->fetch(); //Prepend new line if last char isn't EOL: @@ -376,7 +375,7 @@ class SymfonyStyle extends OutputStyle } } - private function reduceBuffer($messages) + private function reduceBuffer($messages): array { // We need to know if the two last chars are PHP_EOL // Preserve the last 4 chars inserted (PHP_EOL on windows is two chars) in the history buffer @@ -385,7 +384,7 @@ class SymfonyStyle extends OutputStyle }, array_merge(array($this->bufferedOutput->fetch()), (array) $messages)); } - private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false) + private function createBlock(iterable $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = false) { $indentLength = 0; $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix); diff --git a/src/Symfony/Component/CssSelector/Node/AbstractNode.php b/src/Symfony/Component/CssSelector/Node/AbstractNode.php index 7477e9119d..123ef1b117 100644 --- a/src/Symfony/Component/CssSelector/Node/AbstractNode.php +++ b/src/Symfony/Component/CssSelector/Node/AbstractNode.php @@ -31,7 +31,7 @@ abstract class AbstractNode implements NodeInterface /** * @return string */ - public function getNodeName() + public function getNodeName(): string { if (null === $this->nodeName) { $this->nodeName = preg_replace('~.*\\\\([^\\\\]+)Node$~', '$1', get_called_class()); diff --git a/src/Symfony/Component/CssSelector/Node/AttributeNode.php b/src/Symfony/Component/CssSelector/Node/AttributeNode.php index af872b79e9..0db22c0095 100644 --- a/src/Symfony/Component/CssSelector/Node/AttributeNode.php +++ b/src/Symfony/Component/CssSelector/Node/AttributeNode.php @@ -107,7 +107,7 @@ class AttributeNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); } @@ -115,7 +115,7 @@ class AttributeNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { $attribute = $this->namespace ? $this->namespace.'|'.$this->attribute : $this->attribute; diff --git a/src/Symfony/Component/CssSelector/Node/ClassNode.php b/src/Symfony/Component/CssSelector/Node/ClassNode.php index f965e7773e..f036c41c15 100644 --- a/src/Symfony/Component/CssSelector/Node/ClassNode.php +++ b/src/Symfony/Component/CssSelector/Node/ClassNode.php @@ -62,7 +62,7 @@ class ClassNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); } @@ -70,7 +70,7 @@ class ClassNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { return sprintf('%s[%s.%s]', $this->getNodeName(), $this->selector, $this->name); } diff --git a/src/Symfony/Component/CssSelector/Node/CombinedSelectorNode.php b/src/Symfony/Component/CssSelector/Node/CombinedSelectorNode.php index 39f6599777..97a122cb2a 100644 --- a/src/Symfony/Component/CssSelector/Node/CombinedSelectorNode.php +++ b/src/Symfony/Component/CssSelector/Node/CombinedSelectorNode.php @@ -77,7 +77,7 @@ class CombinedSelectorNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->selector->getSpecificity()->plus($this->subSelector->getSpecificity()); } @@ -85,7 +85,7 @@ class CombinedSelectorNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { $combinator = ' ' === $this->combinator ? '' : $this->combinator; diff --git a/src/Symfony/Component/CssSelector/Node/ElementNode.php b/src/Symfony/Component/CssSelector/Node/ElementNode.php index 06e343e969..5b57a3a4f0 100644 --- a/src/Symfony/Component/CssSelector/Node/ElementNode.php +++ b/src/Symfony/Component/CssSelector/Node/ElementNode.php @@ -62,7 +62,7 @@ class ElementNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return new Specificity(0, 0, $this->element ? 1 : 0); } @@ -70,7 +70,7 @@ class ElementNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { $element = $this->element ?: '*'; diff --git a/src/Symfony/Component/CssSelector/Node/FunctionNode.php b/src/Symfony/Component/CssSelector/Node/FunctionNode.php index 612f348c5e..ba2434c062 100644 --- a/src/Symfony/Component/CssSelector/Node/FunctionNode.php +++ b/src/Symfony/Component/CssSelector/Node/FunctionNode.php @@ -79,7 +79,7 @@ class FunctionNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); } @@ -87,7 +87,7 @@ class FunctionNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { $arguments = implode(', ', array_map(function (Token $token) { return "'".$token->getValue()."'"; diff --git a/src/Symfony/Component/CssSelector/Node/HashNode.php b/src/Symfony/Component/CssSelector/Node/HashNode.php index 20db465162..50e6d09ff7 100644 --- a/src/Symfony/Component/CssSelector/Node/HashNode.php +++ b/src/Symfony/Component/CssSelector/Node/HashNode.php @@ -62,7 +62,7 @@ class HashNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->selector->getSpecificity()->plus(new Specificity(1, 0, 0)); } @@ -70,7 +70,7 @@ class HashNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { return sprintf('%s[%s#%s]', $this->getNodeName(), $this->selector, $this->id); } diff --git a/src/Symfony/Component/CssSelector/Node/NegationNode.php b/src/Symfony/Component/CssSelector/Node/NegationNode.php index 4b5aa2260d..e481b52861 100644 --- a/src/Symfony/Component/CssSelector/Node/NegationNode.php +++ b/src/Symfony/Component/CssSelector/Node/NegationNode.php @@ -62,7 +62,7 @@ class NegationNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->selector->getSpecificity()->plus($this->subSelector->getSpecificity()); } @@ -70,7 +70,7 @@ class NegationNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { return sprintf('%s[%s:not(%s)]', $this->getNodeName(), $this->selector, $this->subSelector); } diff --git a/src/Symfony/Component/CssSelector/Node/NodeInterface.php b/src/Symfony/Component/CssSelector/Node/NodeInterface.php index d919e20c71..b078d26d4d 100644 --- a/src/Symfony/Component/CssSelector/Node/NodeInterface.php +++ b/src/Symfony/Component/CssSelector/Node/NodeInterface.php @@ -23,24 +23,9 @@ namespace Symfony\Component\CssSelector\Node; */ interface NodeInterface { - /** - * Returns node's name. - * - * @return string - */ - public function getNodeName(); + public function getNodeName(): string; - /** - * Returns node's specificity. - * - * @return Specificity - */ - public function getSpecificity(); + public function getSpecificity(): Specificity; - /** - * Returns node's string representation. - * - * @return string - */ - public function __toString(); + public function __toString(): string; } diff --git a/src/Symfony/Component/CssSelector/Node/PseudoNode.php b/src/Symfony/Component/CssSelector/Node/PseudoNode.php index c23ddd5912..25aa9e2b27 100644 --- a/src/Symfony/Component/CssSelector/Node/PseudoNode.php +++ b/src/Symfony/Component/CssSelector/Node/PseudoNode.php @@ -62,7 +62,7 @@ class PseudoNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->selector->getSpecificity()->plus(new Specificity(0, 1, 0)); } @@ -70,7 +70,7 @@ class PseudoNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { return sprintf('%s[%s:%s]', $this->getNodeName(), $this->selector, $this->identifier); } diff --git a/src/Symfony/Component/CssSelector/Node/SelectorNode.php b/src/Symfony/Component/CssSelector/Node/SelectorNode.php index 729e0911b3..34c323b17c 100644 --- a/src/Symfony/Component/CssSelector/Node/SelectorNode.php +++ b/src/Symfony/Component/CssSelector/Node/SelectorNode.php @@ -62,7 +62,7 @@ class SelectorNode extends AbstractNode /** * {@inheritdoc} */ - public function getSpecificity() + public function getSpecificity(): Specificity { return $this->tree->getSpecificity()->plus(new Specificity(0, 0, $this->pseudoElement ? 1 : 0)); } @@ -70,7 +70,7 @@ class SelectorNode extends AbstractNode /** * {@inheritdoc} */ - public function __toString() + public function __toString(): string { return sprintf('%s[%s%s]', $this->getNodeName(), $this->tree, $this->pseudoElement ? '::'.$this->pseudoElement : ''); } diff --git a/src/Symfony/Component/CssSelector/Node/Specificity.php b/src/Symfony/Component/CssSelector/Node/Specificity.php index d09eaca77e..be8a0e0114 100644 --- a/src/Symfony/Component/CssSelector/Node/Specificity.php +++ b/src/Symfony/Component/CssSelector/Node/Specificity.php @@ -44,36 +44,19 @@ class Specificity */ private $c; - /** - * Constructor. - * - * @param int $a - * @param int $b - * @param int $c - */ - public function __construct($a, $b, $c) + public function __construct(int $a, int $b, int $c) { $this->a = $a; $this->b = $b; $this->c = $c; } - /** - * @param Specificity $specificity - * - * @return self - */ - public function plus(Specificity $specificity) + public function plus(Specificity $specificity): Specificity { return new self($this->a + $specificity->a, $this->b + $specificity->b, $this->c + $specificity->c); } - /** - * Returns global specificity value. - * - * @return int - */ - public function getValue() + public function getValue(): int { return $this->a * self::A_FACTOR + $this->b * self::B_FACTOR + $this->c * self::C_FACTOR; } diff --git a/src/Symfony/Component/CssSelector/Parser/Handler/CommentHandler.php b/src/Symfony/Component/CssSelector/Parser/Handler/CommentHandler.php index a29775cab3..93f318844a 100644 --- a/src/Symfony/Component/CssSelector/Parser/Handler/CommentHandler.php +++ b/src/Symfony/Component/CssSelector/Parser/Handler/CommentHandler.php @@ -29,7 +29,7 @@ class CommentHandler implements HandlerInterface /** * {@inheritdoc} */ - public function handle(Reader $reader, TokenStream $stream) + public function handle(Reader $reader, TokenStream $stream): bool { if ('/*' !== $reader->getSubstring(2)) { return false; diff --git a/src/Symfony/Component/CssSelector/Parser/Handler/HandlerInterface.php b/src/Symfony/Component/CssSelector/Parser/Handler/HandlerInterface.php index a1297c80c0..10e20ac711 100644 --- a/src/Symfony/Component/CssSelector/Parser/Handler/HandlerInterface.php +++ b/src/Symfony/Component/CssSelector/Parser/Handler/HandlerInterface.php @@ -32,5 +32,5 @@ interface HandlerInterface * * @return bool */ - public function handle(Reader $reader, TokenStream $stream); + public function handle(Reader $reader, TokenStream $stream): bool; } diff --git a/src/Symfony/Component/CssSelector/Parser/Handler/HashHandler.php b/src/Symfony/Component/CssSelector/Parser/Handler/HashHandler.php index f74bda5126..145fe5925f 100644 --- a/src/Symfony/Component/CssSelector/Parser/Handler/HashHandler.php +++ b/src/Symfony/Component/CssSelector/Parser/Handler/HashHandler.php @@ -52,7 +52,7 @@ class HashHandler implements HandlerInterface /** * {@inheritdoc} */ - public function handle(Reader $reader, TokenStream $stream) + public function handle(Reader $reader, TokenStream $stream): bool { $match = $reader->findPattern($this->patterns->getHashPattern()); diff --git a/src/Symfony/Component/CssSelector/Parser/Handler/IdentifierHandler.php b/src/Symfony/Component/CssSelector/Parser/Handler/IdentifierHandler.php index 358c7c14ad..704f939d61 100644 --- a/src/Symfony/Component/CssSelector/Parser/Handler/IdentifierHandler.php +++ b/src/Symfony/Component/CssSelector/Parser/Handler/IdentifierHandler.php @@ -52,7 +52,7 @@ class IdentifierHandler implements HandlerInterface /** * {@inheritdoc} */ - public function handle(Reader $reader, TokenStream $stream) + public function handle(Reader $reader, TokenStream $stream): bool { $match = $reader->findPattern($this->patterns->getIdentifierPattern()); diff --git a/src/Symfony/Component/CssSelector/Parser/Handler/NumberHandler.php b/src/Symfony/Component/CssSelector/Parser/Handler/NumberHandler.php index 4ea5c484b2..7ef2fe3171 100644 --- a/src/Symfony/Component/CssSelector/Parser/Handler/NumberHandler.php +++ b/src/Symfony/Component/CssSelector/Parser/Handler/NumberHandler.php @@ -44,7 +44,7 @@ class NumberHandler implements HandlerInterface /** * {@inheritdoc} */ - public function handle(Reader $reader, TokenStream $stream) + public function handle(Reader $reader, TokenStream $stream): bool { $match = $reader->findPattern($this->patterns->getNumberPattern()); diff --git a/src/Symfony/Component/CssSelector/Parser/Handler/StringHandler.php b/src/Symfony/Component/CssSelector/Parser/Handler/StringHandler.php index 4205296016..18a88acbc3 100644 --- a/src/Symfony/Component/CssSelector/Parser/Handler/StringHandler.php +++ b/src/Symfony/Component/CssSelector/Parser/Handler/StringHandler.php @@ -54,7 +54,7 @@ class StringHandler implements HandlerInterface /** * {@inheritdoc} */ - public function handle(Reader $reader, TokenStream $stream) + public function handle(Reader $reader, TokenStream $stream): bool { $quote = $reader->getSubstring(1); diff --git a/src/Symfony/Component/CssSelector/Parser/Handler/WhitespaceHandler.php b/src/Symfony/Component/CssSelector/Parser/Handler/WhitespaceHandler.php index 4c2d3354fb..ebf8a19fe2 100644 --- a/src/Symfony/Component/CssSelector/Parser/Handler/WhitespaceHandler.php +++ b/src/Symfony/Component/CssSelector/Parser/Handler/WhitespaceHandler.php @@ -30,7 +30,7 @@ class WhitespaceHandler implements HandlerInterface /** * {@inheritdoc} */ - public function handle(Reader $reader, TokenStream $stream) + public function handle(Reader $reader, TokenStream $stream): bool { $match = $reader->findPattern('~^[ \t\r\n\f]+~'); diff --git a/src/Symfony/Component/CssSelector/Parser/Parser.php b/src/Symfony/Component/CssSelector/Parser/Parser.php index 3c5b2dd264..aefb84386d 100644 --- a/src/Symfony/Component/CssSelector/Parser/Parser.php +++ b/src/Symfony/Component/CssSelector/Parser/Parser.php @@ -45,7 +45,7 @@ class Parser implements ParserInterface /** * {@inheritdoc} */ - public function parse($source) + public function parse(string $source): array { $reader = new Reader($source); $stream = $this->tokenizer->tokenize($reader); @@ -102,14 +102,7 @@ class Parser implements ParserInterface ); } - /** - * Parses selector nodes. - * - * @param TokenStream $stream - * - * @return array - */ - private function parseSelectorList(TokenStream $stream) + private function parseSelectorList(TokenStream $stream): array { $stream->skipWhitespace(); $selectors = array(); @@ -128,16 +121,7 @@ class Parser implements ParserInterface return $selectors; } - /** - * Parses next selector or combined node. - * - * @param TokenStream $stream - * - * @return Node\SelectorNode - * - * @throws SyntaxErrorException - */ - private function parserSelectorNode(TokenStream $stream) + private function parserSelectorNode(TokenStream $stream): Node\SelectorNode { list($result, $pseudoElement) = $this->parseSimpleSelector($stream); @@ -291,14 +275,7 @@ class Parser implements ParserInterface return array($result, $pseudoElement); } - /** - * Parses next element node. - * - * @param TokenStream $stream - * - * @return Node\ElementNode - */ - private function parseElementNode(TokenStream $stream) + private function parseElementNode(TokenStream $stream): Node\ElementNode { $peek = $stream->getPeek(); @@ -324,17 +301,7 @@ class Parser implements ParserInterface return new Node\ElementNode($namespace, $element); } - /** - * Parses next attribute node. - * - * @param Node\NodeInterface $selector - * @param TokenStream $stream - * - * @return Node\AttributeNode - * - * @throws SyntaxErrorException - */ - private function parseAttributeNode(Node\NodeInterface $selector, TokenStream $stream) + private function parseAttributeNode(Node\NodeInterface $selector, TokenStream $stream): Node\AttributeNode { $stream->skipWhitespace(); $attribute = $stream->getNextIdentifierOrStar(); diff --git a/src/Symfony/Component/CssSelector/Parser/ParserInterface.php b/src/Symfony/Component/CssSelector/Parser/ParserInterface.php index c5af20367d..88c8879e0b 100644 --- a/src/Symfony/Component/CssSelector/Parser/ParserInterface.php +++ b/src/Symfony/Component/CssSelector/Parser/ParserInterface.php @@ -32,5 +32,5 @@ interface ParserInterface * * @return SelectorNode[] */ - public function parse($source); + public function parse(string $source): array; } diff --git a/src/Symfony/Component/CssSelector/Parser/Shortcut/ClassParser.php b/src/Symfony/Component/CssSelector/Parser/Shortcut/ClassParser.php index c513de5ff1..ce7b20ef2e 100644 --- a/src/Symfony/Component/CssSelector/Parser/Shortcut/ClassParser.php +++ b/src/Symfony/Component/CssSelector/Parser/Shortcut/ClassParser.php @@ -31,7 +31,7 @@ class ClassParser implements ParserInterface /** * {@inheritdoc} */ - public function parse($source) + public function parse(string $source): array { // Matches an optional namespace, optional element, and required class // $source = 'test|input.ab6bd_field'; diff --git a/src/Symfony/Component/CssSelector/Parser/Shortcut/ElementParser.php b/src/Symfony/Component/CssSelector/Parser/Shortcut/ElementParser.php index c29f5e442e..3b93f0068f 100644 --- a/src/Symfony/Component/CssSelector/Parser/Shortcut/ElementParser.php +++ b/src/Symfony/Component/CssSelector/Parser/Shortcut/ElementParser.php @@ -30,7 +30,7 @@ class ElementParser implements ParserInterface /** * {@inheritdoc} */ - public function parse($source) + public function parse(string $source): array { // Matches an optional namespace, required element or `*` // $source = 'testns|testel'; diff --git a/src/Symfony/Component/CssSelector/Parser/Shortcut/EmptyStringParser.php b/src/Symfony/Component/CssSelector/Parser/Shortcut/EmptyStringParser.php index 016cf0a848..0c366cc4e0 100644 --- a/src/Symfony/Component/CssSelector/Parser/Shortcut/EmptyStringParser.php +++ b/src/Symfony/Component/CssSelector/Parser/Shortcut/EmptyStringParser.php @@ -34,7 +34,7 @@ class EmptyStringParser implements ParserInterface /** * {@inheritdoc} */ - public function parse($source) + public function parse(string $source): array { // Matches an empty string if ($source == '') { diff --git a/src/Symfony/Component/CssSelector/Parser/Shortcut/HashParser.php b/src/Symfony/Component/CssSelector/Parser/Shortcut/HashParser.php index 3f3883bb8d..e94ce0a46a 100644 --- a/src/Symfony/Component/CssSelector/Parser/Shortcut/HashParser.php +++ b/src/Symfony/Component/CssSelector/Parser/Shortcut/HashParser.php @@ -31,7 +31,7 @@ class HashParser implements ParserInterface /** * {@inheritdoc} */ - public function parse($source) + public function parse(string $source): array { // Matches an optional namespace, optional element, and required id // $source = 'test|input#ab6bd_field'; diff --git a/src/Symfony/Component/CssSelector/Parser/Token.php b/src/Symfony/Component/CssSelector/Parser/Token.php index 68fac59b03..43cabb5e92 100644 --- a/src/Symfony/Component/CssSelector/Parser/Token.php +++ b/src/Symfony/Component/CssSelector/Parser/Token.php @@ -47,7 +47,7 @@ class Token private $position; /** - * @param int $type + * @param string $type * @param string $value * @param int $position */ @@ -82,20 +82,12 @@ class Token return $this->position; } - /** - * @return bool - */ - public function isFileEnd() + public function isFileEnd(): bool { return self::TYPE_FILE_END === $this->type; } - /** - * @param array $values - * - * @return bool - */ - public function isDelimiter(array $values = array()) + public function isDelimiter(array $values = array()): bool { if (self::TYPE_DELIMITER !== $this->type) { return false; @@ -108,50 +100,32 @@ class Token return in_array($this->value, $values); } - /** - * @return bool - */ - public function isWhitespace() + public function isWhitespace(): bool { return self::TYPE_WHITESPACE === $this->type; } - /** - * @return bool - */ - public function isIdentifier() + public function isIdentifier(): bool { return self::TYPE_IDENTIFIER === $this->type; } - /** - * @return bool - */ - public function isHash() + public function isHash(): bool { return self::TYPE_HASH === $this->type; } - /** - * @return bool - */ - public function isNumber() + public function isNumber(): bool { return self::TYPE_NUMBER === $this->type; } - /** - * @return bool - */ - public function isString() + public function isString(): bool { return self::TYPE_STRING === $this->type; } - /** - * @return string - */ - public function __toString() + public function __toString(): string { if ($this->value) { return sprintf('<%s "%s" at %s>', $this->type, $this->value, $this->position); diff --git a/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerEscaping.php b/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerEscaping.php index af4c31e5b0..2ca10f3a13 100644 --- a/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerEscaping.php +++ b/src/Symfony/Component/CssSelector/Parser/Tokenizer/TokenizerEscaping.php @@ -28,44 +28,26 @@ class TokenizerEscaping */ private $patterns; - /** - * @param TokenizerPatterns $patterns - */ public function __construct(TokenizerPatterns $patterns) { $this->patterns = $patterns; } - /** - * @param string $value - * - * @return string - */ - public function escapeUnicode($value) + public function escapeUnicode(string $value): string { $value = $this->replaceUnicodeSequences($value); return preg_replace($this->patterns->getSimpleEscapePattern(), '$1', $value); } - /** - * @param string $value - * - * @return string - */ - public function escapeUnicodeAndNewLine($value) + public function escapeUnicodeAndNewLine(string $value): string { $value = preg_replace($this->patterns->getNewLineEscapePattern(), '', $value); return $this->escapeUnicode($value); } - /** - * @param string $value - * - * @return string - */ - private function replaceUnicodeSequences($value) + private function replaceUnicodeSequences(string $value): string { return preg_replace_callback($this->patterns->getUnicodeEscapePattern(), function ($match) { $c = hexdec($match[1]); diff --git a/src/Symfony/Component/CssSelector/XPath/Extension/CombinationExtension.php b/src/Symfony/Component/CssSelector/XPath/Extension/CombinationExtension.php index 0d2d658b65..a13ea32e5b 100644 --- a/src/Symfony/Component/CssSelector/XPath/Extension/CombinationExtension.php +++ b/src/Symfony/Component/CssSelector/XPath/Extension/CombinationExtension.php @@ -28,7 +28,7 @@ class CombinationExtension extends AbstractExtension /** * {@inheritdoc} */ - public function getCombinationTranslators() + public function getCombinationTranslators(): array { return array( ' ' => array($this, 'translateDescendant'), @@ -44,7 +44,7 @@ class CombinationExtension extends AbstractExtension * * @return XPathExpr */ - public function translateDescendant(XPathExpr $xpath, XPathExpr $combinedXpath) + public function translateDescendant(XPathExpr $xpath, XPathExpr $combinedXpath): XPathExpr { return $xpath->join('/descendant-or-self::*/', $combinedXpath); } diff --git a/src/Symfony/Component/CssSelector/XPath/Translator.php b/src/Symfony/Component/CssSelector/XPath/Translator.php index 2b01fc8e52..4c43f3c9eb 100644 --- a/src/Symfony/Component/CssSelector/XPath/Translator.php +++ b/src/Symfony/Component/CssSelector/XPath/Translator.php @@ -83,12 +83,7 @@ class Translator implements TranslatorInterface ; } - /** - * @param string $element - * - * @return string - */ - public static function getXpathLiteral($element) + public static function getXpathLiteral(string $element): string { if (false === strpos($element, "'")) { return "'".$element."'"; @@ -117,7 +112,7 @@ class Translator implements TranslatorInterface /** * {@inheritdoc} */ - public function cssToXPath($cssExpr, $prefix = 'descendant-or-self::') + public function cssToXPath(string $cssExpr, string $prefix = 'descendant-or-self::'): string { $selectors = $this->parseSelectors($cssExpr); @@ -136,19 +131,12 @@ class Translator implements TranslatorInterface /** * {@inheritdoc} */ - public function selectorToXPath(SelectorNode $selector, $prefix = 'descendant-or-self::') + public function selectorToXPath(SelectorNode $selector, string $prefix = 'descendant-or-self::'): string { return ($prefix ?: '').$this->nodeToXPath($selector); } - /** - * Registers an extension. - * - * @param Extension\ExtensionInterface $extension - * - * @return $this - */ - public function registerExtension(Extension\ExtensionInterface $extension) + public function registerExtension(Extension\ExtensionInterface $extension): Translator { $this->extensions[$extension->getName()] = $extension; @@ -162,13 +150,9 @@ class Translator implements TranslatorInterface } /** - * @param string $name - * - * @return Extension\ExtensionInterface - * * @throws ExpressionErrorException */ - public function getExtension($name) + public function getExtension(string $name): Extension\ExtensionInterface { if (!isset($this->extensions[$name])) { throw new ExpressionErrorException(sprintf('Extension "%s" not registered.', $name)); @@ -177,14 +161,7 @@ class Translator implements TranslatorInterface return $this->extensions[$name]; } - /** - * Registers a shortcut parser. - * - * @param ParserInterface $shortcut - * - * @return $this - */ - public function registerParserShortcut(ParserInterface $shortcut) + public function registerParserShortcut(ParserInterface $shortcut): Translator { $this->shortcutParsers[] = $shortcut; @@ -192,13 +169,9 @@ class Translator implements TranslatorInterface } /** - * @param NodeInterface $node - * - * @return XPathExpr - * * @throws ExpressionErrorException */ - public function nodeToXPath(NodeInterface $node) + public function nodeToXPath(NodeInterface $node): XPathExpr { if (!isset($this->nodeTranslators[$node->getNodeName()])) { throw new ExpressionErrorException(sprintf('Node "%s" not supported.', $node->getNodeName())); @@ -208,15 +181,9 @@ class Translator implements TranslatorInterface } /** - * @param string $combiner - * @param NodeInterface $xpath - * @param NodeInterface $combinedXpath - * - * @return XPathExpr - * * @throws ExpressionErrorException */ - public function addCombination($combiner, NodeInterface $xpath, NodeInterface $combinedXpath) + public function addCombination(string $combiner, NodeInterface $xpath, NodeInterface $combinedXpath): XPathExpr { if (!isset($this->combinationTranslators[$combiner])) { throw new ExpressionErrorException(sprintf('Combiner "%s" not supported.', $combiner)); @@ -226,14 +193,9 @@ class Translator implements TranslatorInterface } /** - * @param XPathExpr $xpath - * @param FunctionNode $function - * - * @return XPathExpr - * * @throws ExpressionErrorException */ - public function addFunction(XPathExpr $xpath, FunctionNode $function) + public function addFunction(XPathExpr $xpath, FunctionNode $function): XPathExpr { if (!isset($this->functionTranslators[$function->getName()])) { throw new ExpressionErrorException(sprintf('Function "%s" not supported.', $function->getName())); @@ -243,14 +205,9 @@ class Translator implements TranslatorInterface } /** - * @param XPathExpr $xpath - * @param string $pseudoClass - * - * @return XPathExpr - * * @throws ExpressionErrorException */ - public function addPseudoClass(XPathExpr $xpath, $pseudoClass) + public function addPseudoClass(XPathExpr $xpath, string $pseudoClass): XPathExpr { if (!isset($this->pseudoClassTranslators[$pseudoClass])) { throw new ExpressionErrorException(sprintf('Pseudo-class "%s" not supported.', $pseudoClass)); @@ -260,16 +217,9 @@ class Translator implements TranslatorInterface } /** - * @param XPathExpr $xpath - * @param string $operator - * @param string $attribute - * @param string $value - * - * @return XPathExpr - * * @throws ExpressionErrorException */ - public function addAttributeMatching(XPathExpr $xpath, $operator, $attribute, $value) + public function addAttributeMatching(XPathExpr $xpath, string $operator, string $attribute, $value): XPathExpr { if (!isset($this->attributeMatchingTranslators[$operator])) { throw new ExpressionErrorException(sprintf('Attribute matcher operator "%s" not supported.', $operator)); diff --git a/src/Symfony/Component/CssSelector/XPath/TranslatorInterface.php b/src/Symfony/Component/CssSelector/XPath/TranslatorInterface.php index 0b5de83d57..3224859559 100644 --- a/src/Symfony/Component/CssSelector/XPath/TranslatorInterface.php +++ b/src/Symfony/Component/CssSelector/XPath/TranslatorInterface.php @@ -33,7 +33,7 @@ interface TranslatorInterface * * @return string */ - public function cssToXPath($cssExpr, $prefix = 'descendant-or-self::'); + public function cssToXPath(string $cssExpr, string $prefix = 'descendant-or-self::'): string; /** * Translates a parsed selector node to an XPath expression. @@ -43,5 +43,5 @@ interface TranslatorInterface * * @return string */ - public function selectorToXPath(SelectorNode $selector, $prefix = 'descendant-or-self::'); + public function selectorToXPath(SelectorNode $selector, string $prefix = 'descendant-or-self::'): string; } diff --git a/src/Symfony/Component/CssSelector/XPath/XPathExpr.php b/src/Symfony/Component/CssSelector/XPath/XPathExpr.php index 38ca295540..093cfaf32f 100644 --- a/src/Symfony/Component/CssSelector/XPath/XPathExpr.php +++ b/src/Symfony/Component/CssSelector/XPath/XPathExpr.php @@ -38,13 +38,7 @@ class XPathExpr */ private $condition; - /** - * @param string $path - * @param string $element - * @param string $condition - * @param bool $starPrefix - */ - public function __construct($path = '', $element = '*', $condition = '', $starPrefix = false) + public function __construct(string $path = '', string $element = '*', string $condition = '', bool $starPrefix = false) { $this->path = $path; $this->element = $element; @@ -55,20 +49,12 @@ class XPathExpr } } - /** - * @return string - */ - public function getElement() + public function getElement(): string { return $this->element; } - /** - * @param $condition - * - * @return $this - */ - public function addCondition($condition) + public function addCondition(string $condition): XPathExpr { $this->condition = $this->condition ? sprintf('%s and (%s)', $this->condition, $condition) : $condition; @@ -78,15 +64,12 @@ class XPathExpr /** * @return string */ - public function getCondition() + public function getCondition(): string { return $this->condition; } - /** - * @return $this - */ - public function addNameTest() + public function addNameTest(): XPathExpr { if ('*' !== $this->element) { $this->addCondition('name() = '.Translator::getXpathLiteral($this->element)); @@ -96,10 +79,7 @@ class XPathExpr return $this; } - /** - * @return $this - */ - public function addStarPrefix() + public function addStarPrefix(): XPathExpr { $this->path .= '*/'; @@ -114,7 +94,7 @@ class XPathExpr * * @return $this */ - public function join($combiner, XPathExpr $expr) + public function join(string $combiner, XPathExpr $expr): XPathExpr { $path = $this->__toString().$combiner; @@ -129,10 +109,7 @@ class XPathExpr return $this; } - /** - * @return string - */ - public function __toString() + public function __toString(): string { $path = $this->path.$this->element; $condition = null === $this->condition || '' === $this->condition ? '' : '['.$this->condition.']'; diff --git a/src/Symfony/Component/Dotenv/Dotenv.php b/src/Symfony/Component/Dotenv/Dotenv.php index 630e6f79c7..c5f28d6e69 100644 --- a/src/Symfony/Component/Dotenv/Dotenv.php +++ b/src/Symfony/Component/Dotenv/Dotenv.php @@ -45,7 +45,7 @@ final class Dotenv * @throws FormatException when a file has a syntax error * @throws PathException when a file does not exist or is not readable */ - public function load($path, ...$paths) + public function load(string $path, string ...$paths): void { array_unshift($paths, $path); @@ -65,7 +65,7 @@ final class Dotenv * * @param array $values An array of env variables */ - public function populate($values) + public function populate(array $values): void { $loadedVars = array_flip(explode(',', getenv('SYMFONY_DOTENV_VARS'))); unset($loadedVars['']); @@ -104,7 +104,7 @@ final class Dotenv * * @throws FormatException when a file has a syntax error */ - public function parse($data, $path = '.env') + public function parse(string $data, string $path = '.env'): array { $this->path = $path; $this->data = str_replace(array("\r\n", "\r"), "\n", $data); diff --git a/src/Symfony/Component/ExpressionLanguage/ExpressionLanguage.php b/src/Symfony/Component/ExpressionLanguage/ExpressionLanguage.php index 64f4dd1737..c011b0c270 100644 --- a/src/Symfony/Component/ExpressionLanguage/ExpressionLanguage.php +++ b/src/Symfony/Component/ExpressionLanguage/ExpressionLanguage.php @@ -141,7 +141,7 @@ class ExpressionLanguage $this->addFunction(ExpressionFunction::fromPhp('constant')); } - private function getLexer() + private function getLexer(): Lexer { if (null === $this->lexer) { $this->lexer = new Lexer(); @@ -150,7 +150,7 @@ class ExpressionLanguage return $this->lexer; } - private function getParser() + private function getParser(): Parser { if (null === $this->parser) { $this->parser = new Parser($this->functions); @@ -159,7 +159,7 @@ class ExpressionLanguage return $this->parser; } - private function getCompiler() + private function getCompiler(): Compiler { if (null === $this->compiler) { $this->compiler = new Compiler($this->functions); diff --git a/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php b/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php index 583103217a..4a18e83a5d 100644 --- a/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php +++ b/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php @@ -27,7 +27,7 @@ class UnaryNode extends Node '-' => '-', ); - public function __construct($operator, Node $node) + public function __construct(string $operator, Node $node) { parent::__construct( array('node' => $node), @@ -59,7 +59,7 @@ class UnaryNode extends Node return $value; } - public function toArray() + public function toArray(): array { return array('(', $this->attributes['operator'].' ', $this->nodes['node'], ')'); } diff --git a/src/Symfony/Component/Form/Forms.php b/src/Symfony/Component/Form/Forms.php index e84fcd0ab0..061e98e170 100644 --- a/src/Symfony/Component/Form/Forms.php +++ b/src/Symfony/Component/Form/Forms.php @@ -105,7 +105,7 @@ final class Forms * * @return FormFactoryInterface The form factory */ - public static function createFormFactory() + public static function createFormFactory(): FormFactoryInterface { return self::createFormFactoryBuilder()->getFormFactory(); } @@ -115,7 +115,7 @@ final class Forms * * @return FormFactoryBuilderInterface The form factory builder */ - public static function createFormFactoryBuilder() + public static function createFormFactoryBuilder(): FormFactoryBuilderInterface { $builder = new FormFactoryBuilder(); $builder->addExtension(new CoreExtension()); diff --git a/src/Symfony/Component/HttpKernel/Controller/ArgumentResolver.php b/src/Symfony/Component/HttpKernel/Controller/ArgumentResolver.php index 2c17125c5a..186007ebe4 100644 --- a/src/Symfony/Component/HttpKernel/Controller/ArgumentResolver.php +++ b/src/Symfony/Component/HttpKernel/Controller/ArgumentResolver.php @@ -34,7 +34,7 @@ final class ArgumentResolver implements ArgumentResolverInterface */ private $argumentValueResolvers; - public function __construct(ArgumentMetadataFactoryInterface $argumentMetadataFactory = null, $argumentValueResolvers = array()) + public function __construct(ArgumentMetadataFactoryInterface $argumentMetadataFactory = null, iterable $argumentValueResolvers = array()) { $this->argumentMetadataFactory = $argumentMetadataFactory ?: new ArgumentMetadataFactory(); $this->argumentValueResolvers = $argumentValueResolvers ?: self::getDefaultArgumentValueResolvers(); @@ -81,7 +81,7 @@ final class ArgumentResolver implements ArgumentResolverInterface return $arguments; } - public static function getDefaultArgumentValueResolvers() + public static function getDefaultArgumentValueResolvers(): iterable { return array( new RequestAttributeValueResolver(), diff --git a/src/Symfony/Component/HttpKernel/Fragment/AbstractSurrogateFragmentRenderer.php b/src/Symfony/Component/HttpKernel/Fragment/AbstractSurrogateFragmentRenderer.php index 07ab304e93..74a0a7ca69 100644 --- a/src/Symfony/Component/HttpKernel/Fragment/AbstractSurrogateFragmentRenderer.php +++ b/src/Symfony/Component/HttpKernel/Fragment/AbstractSurrogateFragmentRenderer.php @@ -85,7 +85,7 @@ abstract class AbstractSurrogateFragmentRenderer extends RoutableFragmentRendere return new Response($tag); } - private function generateSignedFragmentUri($uri, Request $request) + private function generateSignedFragmentUri($uri, Request $request): string { if (null === $this->signer) { throw new \LogicException('You must use a URI when using the ESI rendering strategy or set a URL signer.'); @@ -97,7 +97,7 @@ abstract class AbstractSurrogateFragmentRenderer extends RoutableFragmentRendere return substr($fragmentUri, strlen($request->getSchemeAndHttpHost())); } - private function containsNonScalars(array $values) + private function containsNonScalars(array $values): bool { foreach ($values as $value) { if (is_array($value) && $this->containsNonScalars($value)) { diff --git a/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php b/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php index ec2a40716a..632da8f8a5 100644 --- a/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php +++ b/src/Symfony/Component/HttpKernel/Fragment/HIncludeFragmentRenderer.php @@ -123,12 +123,7 @@ class HIncludeFragmentRenderer extends RoutableFragmentRenderer return new Response(sprintf('%s', $uri, $renderedAttributes, $content)); } - /** - * @param string $template - * - * @return bool - */ - private function templateExists($template) + private function templateExists(string $template): bool { if ($this->templating instanceof EngineInterface) { try { diff --git a/src/Symfony/Component/HttpKernel/HttpKernel.php b/src/Symfony/Component/HttpKernel/HttpKernel.php index 4a35a9990b..394147fc3f 100644 --- a/src/Symfony/Component/HttpKernel/HttpKernel.php +++ b/src/Symfony/Component/HttpKernel/HttpKernel.php @@ -118,7 +118,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface * @throws \LogicException If one of the listener does not behave as expected * @throws NotFoundHttpException When controller cannot be found */ - private function handleRaw(Request $request, $type = self::MASTER_REQUEST) + private function handleRaw(Request $request, int $type = self::MASTER_REQUEST) { $this->requestStack->push($request); @@ -184,7 +184,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface * * @throws \RuntimeException if the passed object is not a Response instance */ - private function filterResponse(Response $response, Request $request, $type) + private function filterResponse(Response $response, Request $request, int $type) { $event = new FilterResponseEvent($this, $request, $type, $response); @@ -205,7 +205,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface * @param Request $request * @param int $type */ - private function finishRequest(Request $request, $type) + private function finishRequest(Request $request, int $type) { $this->dispatcher->dispatch(KernelEvents::FINISH_REQUEST, new FinishRequestEvent($this, $request, $type)); $this->requestStack->pop(); @@ -222,7 +222,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface * * @throws \Exception */ - private function handleException(\Exception $e, $request, $type) + private function handleException(\Exception $e, Request $request, int $type) { $event = new GetResponseForExceptionEvent($this, $request, $type, $e); $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event); @@ -257,7 +257,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface } } - private function varToString($var) + private function varToString($var): string { if (is_object($var)) { return sprintf('Object(%s)', get_class($var)); diff --git a/src/Symfony/Component/Inflector/Inflector.php b/src/Symfony/Component/Inflector/Inflector.php index fbe8cc8a45..cf685159a7 100644 --- a/src/Symfony/Component/Inflector/Inflector.php +++ b/src/Symfony/Component/Inflector/Inflector.php @@ -91,7 +91,7 @@ final class Inflector // accesses (access), addresses (address), kisses (kiss) array('sess', 4, true, false, 'ss'), - // analyses (analysis), ellipses (ellipsis), funguses (fungus), + // analyses (analysis), ellipses (ellipsis), fungi (fungus), // neuroses (neurosis), theses (thesis), emphases (emphasis), // oases (oasis), crises (crisis), houses (house), bases (base), // atlases (atlas) @@ -159,7 +159,7 @@ final class Inflector * * @internal */ - public static function singularize($plural) + public static function singularize(string $plural) { $pluralRev = strrev($plural); $lowerPluralRev = strtolower($pluralRev); diff --git a/src/Symfony/Component/Intl/Data/Provider/LanguageDataProvider.php b/src/Symfony/Component/Intl/Data/Provider/LanguageDataProvider.php index b601c91405..c9256ccc58 100644 --- a/src/Symfony/Component/Intl/Data/Provider/LanguageDataProvider.php +++ b/src/Symfony/Component/Intl/Data/Provider/LanguageDataProvider.php @@ -41,7 +41,7 @@ class LanguageDataProvider * @param BundleEntryReaderInterface $reader The reader for reading the .res * files. */ - public function __construct($path, BundleEntryReaderInterface $reader) + public function __construct(string $path, BundleEntryReaderInterface $reader) { $this->path = $path; $this->reader = $reader; diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/AmPmTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/AmPmTransformer.php index 66376475c6..69d8a03a3a 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/AmPmTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/AmPmTransformer.php @@ -23,7 +23,7 @@ class AmPmTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { return $dateTime->format('A'); } @@ -31,7 +31,7 @@ class AmPmTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return 'AM|PM'; } @@ -39,7 +39,7 @@ class AmPmTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'marker' => $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfWeekTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfWeekTransformer.php index a174fdcabc..0bbc5cb44f 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfWeekTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfWeekTransformer.php @@ -23,7 +23,7 @@ class DayOfWeekTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $dayOfWeek = $dateTime->format('l'); switch ($length) { @@ -41,7 +41,7 @@ class DayOfWeekTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { switch ($length) { case 4: @@ -58,7 +58,7 @@ class DayOfWeekTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array(); } diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfYearTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfYearTransformer.php index 5af6dd7243..23000311c7 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfYearTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayOfYearTransformer.php @@ -23,7 +23,7 @@ class DayOfYearTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $dayOfYear = $dateTime->format('z') + 1; @@ -33,7 +33,7 @@ class DayOfYearTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return '\d{'.$length.'}'; } @@ -41,7 +41,7 @@ class DayOfYearTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array(); } diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayTransformer.php index f0ded907c3..f05157f402 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/DayTransformer.php @@ -23,7 +23,7 @@ class DayTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { return $this->padLeft($dateTime->format('j'), $length); } @@ -31,7 +31,7 @@ class DayTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return 1 === $length ? '\d{1,2}' : '\d{'.$length.'}'; } @@ -39,7 +39,7 @@ class DayTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'day' => (int) $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1200Transformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1200Transformer.php index 948e345044..dd3a1a8e71 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1200Transformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1200Transformer.php @@ -23,7 +23,7 @@ class Hour1200Transformer extends HourTransformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $hourOfDay = $dateTime->format('g'); $hourOfDay = '12' == $hourOfDay ? '0' : $hourOfDay; @@ -34,7 +34,7 @@ class Hour1200Transformer extends HourTransformer /** * {@inheritdoc} */ - public function normalizeHour($hour, $marker = null) + public function normalizeHour(int $hour, string $marker = null): int { if ('PM' === $marker) { $hour += 12; @@ -46,7 +46,7 @@ class Hour1200Transformer extends HourTransformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return '\d{1,2}'; } @@ -54,7 +54,7 @@ class Hour1200Transformer extends HourTransformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'hour' => (int) $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1201Transformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1201Transformer.php index 19c4d203ab..63aea50498 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1201Transformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour1201Transformer.php @@ -23,7 +23,7 @@ class Hour1201Transformer extends HourTransformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { return $this->padLeft($dateTime->format('g'), $length); } @@ -31,7 +31,7 @@ class Hour1201Transformer extends HourTransformer /** * {@inheritdoc} */ - public function normalizeHour($hour, $marker = null) + public function normalizeHour(int $hour, string $marker = null): int { if ('PM' !== $marker && 12 === $hour) { $hour = 0; @@ -46,7 +46,7 @@ class Hour1201Transformer extends HourTransformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return '\d{1,2}'; } @@ -54,7 +54,7 @@ class Hour1201Transformer extends HourTransformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'hour' => (int) $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2400Transformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2400Transformer.php index e43d0ee8b2..78233f3d38 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2400Transformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2400Transformer.php @@ -23,7 +23,7 @@ class Hour2400Transformer extends HourTransformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { return $this->padLeft($dateTime->format('G'), $length); } @@ -31,7 +31,7 @@ class Hour2400Transformer extends HourTransformer /** * {@inheritdoc} */ - public function normalizeHour($hour, $marker = null) + public function normalizeHour(int $hour, string $marker = null): int { if ('AM' == $marker) { $hour = 0; @@ -45,7 +45,7 @@ class Hour2400Transformer extends HourTransformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return '\d{1,2}'; } @@ -53,7 +53,7 @@ class Hour2400Transformer extends HourTransformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'hour' => (int) $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2401Transformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2401Transformer.php index df4e671aaf..e82c04da95 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2401Transformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Hour2401Transformer.php @@ -23,7 +23,7 @@ class Hour2401Transformer extends HourTransformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $hourOfDay = $dateTime->format('G'); $hourOfDay = ('0' == $hourOfDay) ? '24' : $hourOfDay; @@ -34,7 +34,7 @@ class Hour2401Transformer extends HourTransformer /** * {@inheritdoc} */ - public function normalizeHour($hour, $marker = null) + public function normalizeHour(int $hour, string $marker = null): int { if ((null === $marker && 24 === $hour) || 'AM' == $marker) { $hour = 0; @@ -48,7 +48,7 @@ class Hour2401Transformer extends HourTransformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return '\d{1,2}'; } @@ -56,7 +56,7 @@ class Hour2401Transformer extends HourTransformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'hour' => (int) $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/HourTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/HourTransformer.php index 349d8e29ae..349cd794de 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/HourTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/HourTransformer.php @@ -28,5 +28,5 @@ abstract class HourTransformer extends Transformer * * @return int The normalized hour value */ - abstract public function normalizeHour($hour, $marker = null); + abstract public function normalizeHour(int $hour, string $marker = null): int; } diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/MinuteTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/MinuteTransformer.php index 08b5356e3f..1f4dec8d1a 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/MinuteTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/MinuteTransformer.php @@ -23,7 +23,7 @@ class MinuteTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $minuteOfHour = (int) $dateTime->format('i'); @@ -33,7 +33,7 @@ class MinuteTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return 1 === $length ? '\d{1,2}' : '\d{'.$length.'}'; } @@ -41,7 +41,7 @@ class MinuteTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'minute' => (int) $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/MonthTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/MonthTransformer.php index 6d7c819800..75ca2d897c 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/MonthTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/MonthTransformer.php @@ -77,7 +77,7 @@ class MonthTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $matchLengthMap = array( 1 => 'n', @@ -100,7 +100,7 @@ class MonthTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { switch ($length) { case 1: @@ -126,7 +126,7 @@ class MonthTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { if (!is_numeric($matched)) { if (3 === $length) { diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/QuarterTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/QuarterTransformer.php index fa7e91d038..ec02e7f305 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/QuarterTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/QuarterTransformer.php @@ -23,7 +23,7 @@ class QuarterTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $month = (int) $dateTime->format('n'); $quarter = (int) floor(($month - 1) / 3) + 1; @@ -43,7 +43,7 @@ class QuarterTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { switch ($length) { case 1: @@ -59,7 +59,7 @@ class QuarterTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array(); } diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/SecondTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/SecondTransformer.php index dd2e7bd9f9..6b1ffd0ce1 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/SecondTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/SecondTransformer.php @@ -23,7 +23,7 @@ class SecondTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $secondOfMinute = (int) $dateTime->format('s'); @@ -33,7 +33,7 @@ class SecondTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return 1 === $length ? '\d{1,2}' : '\d{'.$length.'}'; } @@ -41,7 +41,7 @@ class SecondTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'second' => (int) $matched, diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/TimezoneTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/TimezoneTransformer.php index 1cfcc9bdea..03026a46a1 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/TimezoneTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/TimezoneTransformer.php @@ -27,7 +27,7 @@ class TimezoneTransformer extends Transformer * * @throws NotImplementedException When time zone is different than UTC or GMT (Etc/GMT) */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { $timeZone = substr($dateTime->getTimezone()->getName(), 0, 3); @@ -63,7 +63,7 @@ class TimezoneTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return 'GMT[+-]\d{2}:?\d{2}'; } @@ -71,7 +71,7 @@ class TimezoneTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'timezone' => self::getEtcTimeZoneId($matched), diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php index 26a25db355..5bdb7267af 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/Transformer.php @@ -29,7 +29,7 @@ abstract class Transformer * * @return string The formatted value */ - abstract public function format(\DateTime $dateTime, $length); + abstract public function format(\DateTime $dateTime, int $length): string; /** * Returns a reverse matching regular expression of a string generated by format(). @@ -38,7 +38,7 @@ abstract class Transformer * * @return string The reverse matching regular expression */ - abstract public function getReverseMatchingRegExp($length); + abstract public function getReverseMatchingRegExp(int $length): string; /** * Extract date options from a matched value returned by the processing of the reverse matching @@ -49,7 +49,7 @@ abstract class Transformer * * @return array An associative array */ - abstract public function extractDateOptions($matched, $length); + abstract public function extractDateOptions(string $matched, int $length): array; /** * Pad a string with zeros to the left. @@ -59,7 +59,7 @@ abstract class Transformer * * @return string The padded string */ - protected function padLeft($value, $length) + protected function padLeft(string $value, int $length): string { return str_pad($value, $length, '0', STR_PAD_LEFT); } diff --git a/src/Symfony/Component/Intl/DateFormatter/DateFormat/YearTransformer.php b/src/Symfony/Component/Intl/DateFormatter/DateFormat/YearTransformer.php index 0b546b774a..b41420b722 100644 --- a/src/Symfony/Component/Intl/DateFormatter/DateFormat/YearTransformer.php +++ b/src/Symfony/Component/Intl/DateFormatter/DateFormat/YearTransformer.php @@ -23,7 +23,7 @@ class YearTransformer extends Transformer /** * {@inheritdoc} */ - public function format(\DateTime $dateTime, $length) + public function format(\DateTime $dateTime, int $length): string { if (2 === $length) { return $dateTime->format('y'); @@ -35,7 +35,7 @@ class YearTransformer extends Transformer /** * {@inheritdoc} */ - public function getReverseMatchingRegExp($length) + public function getReverseMatchingRegExp(int $length): string { return 2 === $length ? '\d{2}' : '\d{4}'; } @@ -43,7 +43,7 @@ class YearTransformer extends Transformer /** * {@inheritdoc} */ - public function extractDateOptions($matched, $length) + public function extractDateOptions(string $matched, int $length): array { return array( 'year' => (int) $matched, diff --git a/src/Symfony/Component/Intl/Locale.php b/src/Symfony/Component/Intl/Locale.php index ee09bd263c..3dfeacf3f3 100644 --- a/src/Symfony/Component/Intl/Locale.php +++ b/src/Symfony/Component/Intl/Locale.php @@ -35,7 +35,7 @@ final class Locale extends \Locale * * @see getFallback() */ - public static function setDefaultFallback($locale) + public static function setDefaultFallback(string $locale) { self::$defaultFallback = $locale; } @@ -48,7 +48,7 @@ final class Locale extends \Locale * @see setDefaultFallback() * @see getFallback() */ - public static function getDefaultFallback() + public static function getDefaultFallback(): string { return self::$defaultFallback; } @@ -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) + public static function getFallback($locale): ?string { if (false === $pos = strrpos($locale, '_')) { if (self::$defaultFallback === $locale) { @@ -78,7 +78,7 @@ final class Locale extends \Locale return self::$defaultFallback; } - return; + return null; } return substr($locale, 0, $pos); diff --git a/src/Symfony/Component/Intl/ResourceBundle/LanguageBundle.php b/src/Symfony/Component/Intl/ResourceBundle/LanguageBundle.php index d12b892a10..84c676c742 100644 --- a/src/Symfony/Component/Intl/ResourceBundle/LanguageBundle.php +++ b/src/Symfony/Component/Intl/ResourceBundle/LanguageBundle.php @@ -36,15 +36,7 @@ class LanguageBundle extends LanguageDataProvider implements LanguageBundleInter */ private $scriptProvider; - /** - * Creates a new language bundle. - * - * @param string $path - * @param BundleEntryReaderInterface $reader - * @param LocaleDataProvider $localeProvider - * @param ScriptDataProvider $scriptProvider - */ - public function __construct($path, BundleEntryReaderInterface $reader, LocaleDataProvider $localeProvider, ScriptDataProvider $scriptProvider) + public function __construct(string $path, BundleEntryReaderInterface $reader, LocaleDataProvider $localeProvider, ScriptDataProvider $scriptProvider) { parent::__construct($path, $reader); diff --git a/src/Symfony/Component/Ldap/Ldap.php b/src/Symfony/Component/Ldap/Ldap.php index 514f51d22c..26fd4f946c 100644 --- a/src/Symfony/Component/Ldap/Ldap.php +++ b/src/Symfony/Component/Ldap/Ldap.php @@ -70,7 +70,7 @@ final class Ldap implements LdapInterface * * @return static */ - public static function create($adapter, array $config = array()) + public static function create($adapter, array $config = array()): Ldap { if (!isset(self::$adapterMap[$adapter])) { throw new DriverNotFoundException(sprintf( diff --git a/src/Symfony/Component/Lock/Key.php b/src/Symfony/Component/Lock/Key.php index 5069901761..95936a3e89 100644 --- a/src/Symfony/Component/Lock/Key.php +++ b/src/Symfony/Component/Lock/Key.php @@ -25,9 +25,9 @@ final class Key /** * @param string $resource */ - public function __construct($resource) + public function __construct(string $resource) { - $this->resource = (string) $resource; + $this->resource = $resource; } public function __toString() @@ -35,39 +35,22 @@ final class Key return $this->resource; } - /** - * @param string $stateKey - * - * @return bool - */ - public function hasState($stateKey) + public function hasState(string $stateKey): bool { return isset($this->state[$stateKey]); } - /** - * @param string $stateKey - * @param mixed $state - */ - public function setState($stateKey, $state) + public function setState(string $stateKey, $state): void { $this->state[$stateKey] = $state; } - /** - * @param string $stateKey - */ - public function removeState($stateKey) + public function removeState(string $stateKey): void { unset($this->state[$stateKey]); } - /** - * @param $stateKey - * - * @return mixed - */ - public function getState($stateKey) + public function getState(string $stateKey) { return $this->state[$stateKey]; } diff --git a/src/Symfony/Component/PropertyAccess/PropertyAccess.php b/src/Symfony/Component/PropertyAccess/PropertyAccess.php index 3c8dc1c56c..e929347e65 100644 --- a/src/Symfony/Component/PropertyAccess/PropertyAccess.php +++ b/src/Symfony/Component/PropertyAccess/PropertyAccess.php @@ -23,17 +23,12 @@ final class PropertyAccess * * @return PropertyAccessor */ - public static function createPropertyAccessor() + public static function createPropertyAccessor(): PropertyAccessor { return self::createPropertyAccessorBuilder()->getPropertyAccessor(); } - /** - * Creates a property accessor builder. - * - * @return PropertyAccessorBuilder - */ - public static function createPropertyAccessorBuilder() + public static function createPropertyAccessorBuilder(): PropertyAccessorBuilder { return new PropertyAccessorBuilder(); } diff --git a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php index 838fb9c417..68506c4eb4 100644 --- a/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php +++ b/src/Symfony/Component/PropertyInfo/Extractor/ReflectionExtractor.php @@ -162,18 +162,18 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp * * @return Type[]|null */ - private function extractFromMutator($class, $property) + private function extractFromMutator(string $class, string $property): ?array { list($reflectionMethod, $prefix) = $this->getMutatorMethod($class, $property); if (null === $reflectionMethod) { - return; + return null; } $reflectionParameters = $reflectionMethod->getParameters(); $reflectionParameter = $reflectionParameters[0]; if (!$reflectionType = $reflectionParameter->getType()) { - return; + return null; } $type = $this->extractFromReflectionType($reflectionType); @@ -192,11 +192,11 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp * * @return Type[]|null */ - private function extractFromAccessor($class, $property) + private function extractFromAccessor(string $class, string $property): ?array { list($reflectionMethod, $prefix) = $this->getAccessorMethod($class, $property); if (null === $reflectionMethod) { - return; + return null; } if ($reflectionType = $reflectionMethod->getReturnType()) { @@ -206,6 +206,8 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp if (in_array($prefix, array('is', 'can'))) { return array(new Type(Type::BUILTIN_TYPE_BOOL)); } + + return null; } /** @@ -215,7 +217,7 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp * * @return Type */ - private function extractFromReflectionType(\ReflectionType $reflectionType) + private function extractFromReflectionType(\ReflectionType $reflectionType): Type { $phpTypeOrClass = $reflectionType->getName(); $nullable = $reflectionType->allowsNull(); @@ -241,7 +243,7 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp * * @return bool */ - private function isPublicProperty($class, $property) + private function isPublicProperty(string $class, string $property): bool { try { $reflectionProperty = new \ReflectionProperty($class, $property); @@ -265,7 +267,7 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp * * @return array|null */ - private function getAccessorMethod($class, $property) + private function getAccessorMethod(string $class, string $property): ?array { $ucProperty = ucfirst($property); @@ -283,6 +285,8 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp // Return null if the property doesn't exist } } + + return null; } /** @@ -296,7 +300,7 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp * * @return array */ - private function getMutatorMethod($class, $property) + private function getMutatorMethod(string $class, string $property) { $ucProperty = ucfirst($property); $ucSingulars = (array) Inflector::singularize($ucProperty); @@ -333,7 +337,7 @@ class ReflectionExtractor implements PropertyListExtractorInterface, PropertyTyp * * @return string */ - private function getPropertyName($methodName, array $reflectionProperties) + private function getPropertyName(string $methodName, array $reflectionProperties) { $pattern = implode('|', array_merge($this->accessorPrefixes, $this->mutatorPrefixes)); diff --git a/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php b/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php index bc14cd8b69..9c8fc8d3f6 100644 --- a/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php +++ b/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php @@ -27,9 +27,9 @@ final class PhpDocTypeHelper /** * Creates a {@see Type} from a PHPDoc type. * - * @return Type + * @return Type[] */ - public function getTypes(DocType $varType) + public function getTypes(DocType $varType): array { $types = array(); $nullable = false; @@ -79,11 +79,11 @@ final class PhpDocTypeHelper * * @return Type|null */ - private function createType($docType, $nullable) + private function createType(string $docType, bool $nullable): ?Type { // Cannot guess if (!$docType || 'mixed' === $docType) { - return; + return null; } if ($collection = '[]' === substr($docType, -2)) { @@ -110,14 +110,7 @@ final class PhpDocTypeHelper return new Type($phpType, $nullable, $class); } - /** - * Normalizes the type. - * - * @param string $docType - * - * @return string - */ - private function normalizeType($docType) + private function normalizeType(string $docType): string { switch ($docType) { case 'integer': @@ -141,14 +134,7 @@ final class PhpDocTypeHelper } } - /** - * Gets an array containing the PHP type and the class. - * - * @param string $docType - * - * @return array - */ - private function getPhpTypeAndClass($docType) + private function getPhpTypeAndClass(string $docType): array { if (in_array($docType, Type::$builtinTypes)) { return array($docType, null); diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/DumperRoute.php b/src/Symfony/Component/Routing/Matcher/Dumper/DumperRoute.php index 3ad08c2006..9895de9110 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/DumperRoute.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/DumperRoute.php @@ -32,34 +32,18 @@ class DumperRoute */ private $route; - /** - * Constructor. - * - * @param string $name The route name - * @param Route $route The route - */ - public function __construct($name, Route $route) + public function __construct(string $name, Route $route) { $this->name = $name; $this->route = $route; } - /** - * Returns the route name. - * - * @return string The route name - */ - public function getName() + public function getName(): string { return $this->name; } - /** - * Returns the route. - * - * @return Route The route - */ - public function getRoute() + public function getRoute(): Route { return $this->route; } diff --git a/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php b/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php index b2bfa34376..675dab9193 100644 --- a/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php +++ b/src/Symfony/Component/Routing/Matcher/Dumper/StaticPrefixCollection.php @@ -35,12 +35,12 @@ class StaticPrefixCollection */ private $matchStart = 0; - public function __construct($prefix = '') + public function __construct(string $prefix = '') { $this->prefix = $prefix; } - public function getPrefix() + public function getPrefix(): string { return $this->prefix; } @@ -48,7 +48,7 @@ class StaticPrefixCollection /** * @return mixed[]|StaticPrefixCollection[] */ - public function getItems() + public function getItems(): array { return $this->items; } @@ -59,7 +59,7 @@ class StaticPrefixCollection * @param string $prefix * @param mixed $route */ - public function addRoute($prefix, $route) + public function addRoute(string $prefix, $route) { $prefix = '/' === $prefix ? $prefix : rtrim($prefix, '/'); $this->guardAgainstAddingNotAcceptedRoutes($prefix); @@ -108,7 +108,7 @@ class StaticPrefixCollection * * @return null|StaticPrefixCollection */ - private function groupWithItem($item, $prefix, $route) + private function groupWithItem($item, string $prefix, $route) { $itemPrefix = $item instanceof self ? $item->prefix : $item[0]; $commonPrefix = $this->detectCommonPrefix($prefix, $itemPrefix); @@ -137,7 +137,7 @@ class StaticPrefixCollection * * @return bool Whether a prefix could belong in a given group */ - private function accepts($prefix) + private function accepts(string $prefix): bool { return '' === $this->prefix || strpos($prefix, $this->prefix) === 0; } @@ -150,7 +150,7 @@ class StaticPrefixCollection * * @return false|string A common prefix, longer than the base/group prefix, or false when none available */ - private function detectCommonPrefix($prefix, $anotherPrefix) + private function detectCommonPrefix(string $prefix, string $anotherPrefix) { $baseLength = strlen($this->prefix); $commonLength = $baseLength; @@ -176,7 +176,7 @@ class StaticPrefixCollection /** * Optimizes the tree by inlining items from groups with less than 3 items. */ - public function optimizeGroups() + public function optimizeGroups(): void { $index = -1; @@ -199,7 +199,7 @@ class StaticPrefixCollection } } - private function shouldBeInlined() + private function shouldBeInlined(): bool { if (count($this->items) >= 3) { return false; @@ -227,7 +227,7 @@ class StaticPrefixCollection * * @throws \LogicException When a prefix does not belong in a group. */ - private function guardAgainstAddingNotAcceptedRoutes($prefix) + private function guardAgainstAddingNotAcceptedRoutes(string $prefix) { if (!$this->accepts($prefix)) { $message = sprintf('Could not add route with prefix %s to collection with prefix %s', $prefix, $this->prefix); diff --git a/src/Symfony/Component/Routing/RouteCollectionBuilder.php b/src/Symfony/Component/Routing/RouteCollectionBuilder.php index 3998ce1ede..6044ca99d3 100644 --- a/src/Symfony/Component/Routing/RouteCollectionBuilder.php +++ b/src/Symfony/Component/Routing/RouteCollectionBuilder.php @@ -258,7 +258,7 @@ class RouteCollectionBuilder * * @return $this */ - private function addResource(ResourceInterface $resource) + private function addResource(ResourceInterface $resource): RouteCollectionBuilder { $this->resources[] = $resource; @@ -356,7 +356,7 @@ class RouteCollectionBuilder * * @throws FileLoaderLoadException If no loader is found */ - private function load($resource, $type = null) + private function load($resource, string $type = null): array { if (null === $this->loader) { throw new \BadMethodCallException('Cannot import other routing resources: you must pass a LoaderInterface when constructing RouteCollectionBuilder.'); diff --git a/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentToken.php b/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentToken.php index 76873fc603..996ad285fd 100644 --- a/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentToken.php +++ b/src/Symfony/Component/Security/Core/Authentication/RememberMe/PersistentToken.php @@ -24,18 +24,7 @@ final class PersistentToken implements PersistentTokenInterface private $tokenValue; private $lastUsed; - /** - * Constructor. - * - * @param string $class - * @param string $username - * @param string $series - * @param string $tokenValue - * @param \DateTime $lastUsed - * - * @throws \InvalidArgumentException - */ - public function __construct($class, $username, $series, $tokenValue, \DateTime $lastUsed) + public function __construct(string $class, string $username, string $series, string $tokenValue, \DateTime $lastUsed) { if (empty($class)) { throw new \InvalidArgumentException('$class must not be empty.'); diff --git a/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php b/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php index fc279c0b3a..2091c84f60 100644 --- a/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php +++ b/src/Symfony/Component/Security/Http/Firewall/ExceptionListener.php @@ -104,7 +104,7 @@ class ExceptionListener } while (null !== $exception = $exception->getPrevious()); } - private function handleAuthenticationException(GetResponseForExceptionEvent $event, AuthenticationException $exception) + private function handleAuthenticationException(GetResponseForExceptionEvent $event, AuthenticationException $exception): void { if (null !== $this->logger) { $this->logger->info('An AuthenticationException was thrown; redirecting to authentication entry point.', array('exception' => $exception)); @@ -167,22 +167,14 @@ class ExceptionListener } } - private function handleLogoutException(LogoutException $exception) + private function handleLogoutException(LogoutException $exception): void { if (null !== $this->logger) { $this->logger->info('A LogoutException was thrown.', array('exception' => $exception)); } } - /** - * @param Request $request - * @param AuthenticationException $authException - * - * @return Response - * - * @throws AuthenticationException - */ - private function startAuthentication(Request $request, AuthenticationException $authException) + private function startAuthentication(Request $request, AuthenticationException $authException): Response { if (null === $this->authenticationEntryPoint) { throw $authException; @@ -216,9 +208,6 @@ class ExceptionListener return $response; } - /** - * @param Request $request - */ protected function setTargetPath(Request $request) { // session isn't required when using HTTP basic authentication mechanism for example diff --git a/src/Symfony/Component/Translation/Translator.php b/src/Symfony/Component/Translation/Translator.php index 897aced271..c877e43ba2 100644 --- a/src/Symfony/Component/Translation/Translator.php +++ b/src/Symfony/Component/Translation/Translator.php @@ -280,10 +280,7 @@ class Translator implements TranslatorInterface, TranslatorBagInterface $this->loadFallbackCatalogues($locale); } - /** - * @param string $locale - */ - private function initializeCacheCatalogue($locale) + private function initializeCacheCatalogue(string $locale): void { if (isset($this->catalogues[$locale])) { /* Catalogue already initialized. */ @@ -306,7 +303,7 @@ class Translator implements TranslatorInterface, TranslatorBagInterface $this->catalogues[$locale] = include $cache->getPath(); } - private function dumpCatalogue($locale, ConfigCacheInterface $cache) + private function dumpCatalogue($locale, ConfigCacheInterface $cache): void { $this->initializeCatalogue($locale); $fallbackContent = $this->getFallbackContent($this->catalogues[$locale]); @@ -331,7 +328,7 @@ EOF $cache->write($content, $this->catalogues[$locale]->getResources()); } - private function getFallbackContent(MessageCatalogue $catalogue) + private function getFallbackContent(MessageCatalogue $catalogue): string { $fallbackContent = ''; $current = ''; @@ -366,7 +363,7 @@ EOF return $this->cacheDir.'/catalogue.'.$locale.'.'.strtr(substr(base64_encode(hash('sha256', serialize($this->fallbackLocales), true)), 0, 7), '/', '_').'.php'; } - private function doLoadCatalogue($locale) + private function doLoadCatalogue($locale): void { $this->catalogues[$locale] = new MessageCatalogue($locale); @@ -380,7 +377,7 @@ EOF } } - private function loadFallbackCatalogues($locale) + private function loadFallbackCatalogues($locale): void { $current = $this->catalogues[$locale]; @@ -436,7 +433,7 @@ EOF * * @return ConfigCacheFactoryInterface $configCacheFactory */ - private function getConfigCacheFactory() + private function getConfigCacheFactory(): ConfigCacheFactoryInterface { if (!$this->configCacheFactory) { $this->configCacheFactory = new ConfigCacheFactory($this->debug); diff --git a/src/Symfony/Component/Validator/Validation.php b/src/Symfony/Component/Validator/Validation.php index 950efb6cce..71edfedb18 100644 --- a/src/Symfony/Component/Validator/Validation.php +++ b/src/Symfony/Component/Validator/Validation.php @@ -28,7 +28,7 @@ final class Validation * * @return ValidatorInterface The new validator */ - public static function createValidator() + public static function createValidator(): ValidatorInterface { return self::createValidatorBuilder()->getValidator(); } @@ -38,7 +38,7 @@ final class Validation * * @return ValidatorBuilderInterface The new builder */ - public static function createValidatorBuilder() + public static function createValidatorBuilder(): ValidatorBuilder { return new ValidatorBuilder(); } diff --git a/src/Symfony/Component/WebLink/HttpHeaderSerializer.php b/src/Symfony/Component/WebLink/HttpHeaderSerializer.php index 66bfa55ab4..01bb9f154b 100644 --- a/src/Symfony/Component/WebLink/HttpHeaderSerializer.php +++ b/src/Symfony/Component/WebLink/HttpHeaderSerializer.php @@ -29,7 +29,7 @@ final class HttpHeaderSerializer * * @return string|null */ - public function serialize($links) + public function serialize(iterable $links) { $elements = array(); foreach ($links as $link) { diff --git a/src/Symfony/Component/Workflow/Definition.php b/src/Symfony/Component/Workflow/Definition.php index 5f8571b329..a8bc0806e2 100644 --- a/src/Symfony/Component/Workflow/Definition.php +++ b/src/Symfony/Component/Workflow/Definition.php @@ -30,7 +30,7 @@ final class Definition * @param Transition[] $transitions * @param string|null $initialPlace */ - public function __construct(array $places, array $transitions, $initialPlace = null) + public function __construct(array $places, array $transitions, string $initialPlace = null) { foreach ($places as $place) { $this->addPlace($place); @@ -54,7 +54,7 @@ final class Definition /** * @return string[] */ - public function getPlaces() + public function getPlaces(): array { return $this->places; } @@ -62,12 +62,12 @@ final class Definition /** * @return Transition[] */ - public function getTransitions() + public function getTransitions(): array { return $this->transitions; } - private function setInitialPlace($place) + private function setInitialPlace(string $place = null) { if (null === $place) { return; @@ -80,7 +80,7 @@ final class Definition $this->initialPlace = $place; } - private function addPlace($place) + private function addPlace(string $place) { if (!preg_match('{^[\w\d_-]+$}', $place)) { throw new InvalidArgumentException(sprintf('The place "%s" contains invalid characters.', $place)); diff --git a/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php b/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php index 3681b6f139..1344980bee 100644 --- a/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php +++ b/src/Symfony/Component/Workflow/Dumper/GraphvizDumper.php @@ -201,7 +201,7 @@ class GraphvizDumper implements DumperInterface return strtolower(preg_replace('/[^\w]/i', '_', $id)); } - private function addAttributes(array $attributes) + private function addAttributes(array $attributes): string { $code = array(); @@ -212,7 +212,7 @@ class GraphvizDumper implements DumperInterface return $code ? ', '.implode(', ', $code) : ''; } - private function addOptions(array $options) + private function addOptions(array $options): string { $code = array(); diff --git a/src/Symfony/Component/Workflow/EventListener/GuardListener.php b/src/Symfony/Component/Workflow/EventListener/GuardListener.php index 20ba04c007..ad281f0fb8 100644 --- a/src/Symfony/Component/Workflow/EventListener/GuardListener.php +++ b/src/Symfony/Component/Workflow/EventListener/GuardListener.php @@ -51,7 +51,7 @@ class GuardListener } // code should be sync with Symfony\Component\Security\Core\Authorization\Voter\ExpressionVoter - private function getVariables(GuardEvent $event) + private function getVariables(GuardEvent $event): array { $token = $this->tokenStorage->getToken(); diff --git a/src/Symfony/Component/Workflow/Registry.php b/src/Symfony/Component/Workflow/Registry.php index b10af2fbbc..2430dcb34c 100644 --- a/src/Symfony/Component/Workflow/Registry.php +++ b/src/Symfony/Component/Workflow/Registry.php @@ -61,7 +61,7 @@ class Registry return $matched; } - private function supports(Workflow $workflow, SupportStrategyInterface $supportStrategy, $subject, $workflowName) + private function supports(Workflow $workflow, SupportStrategyInterface $supportStrategy, $subject, $workflowName): bool { if (null !== $workflowName && $workflowName !== $workflow->getName()) { return false; diff --git a/src/Symfony/Component/Workflow/SupportStrategy/ClassInstanceSupportStrategy.php b/src/Symfony/Component/Workflow/SupportStrategy/ClassInstanceSupportStrategy.php index 8828946dbf..ed4cd4e6ab 100644 --- a/src/Symfony/Component/Workflow/SupportStrategy/ClassInstanceSupportStrategy.php +++ b/src/Symfony/Component/Workflow/SupportStrategy/ClassInstanceSupportStrategy.php @@ -11,10 +11,7 @@ final class ClassInstanceSupportStrategy implements SupportStrategyInterface { private $className; - /** - * @param string $className a FQCN - */ - public function __construct($className) + public function __construct(string $className) { $this->className = $className; } diff --git a/src/Symfony/Component/Yaml/Tag/TaggedValue.php b/src/Symfony/Component/Yaml/Tag/TaggedValue.php index 000c1d992c..4ea3406135 100644 --- a/src/Symfony/Component/Yaml/Tag/TaggedValue.php +++ b/src/Symfony/Component/Yaml/Tag/TaggedValue.php @@ -20,27 +20,17 @@ final class TaggedValue private $tag; private $value; - /** - * @param string $tag - * @param mixed $value - */ - public function __construct($tag, $value) + public function __construct(string $tag, $value) { $this->tag = $tag; $this->value = $value; } - /** - * @return string - */ - public function getTag() + public function getTag(): string { return $this->tag; } - /** - * @return mixed - */ public function getValue() { return $this->value; From 7b1715b0782af05d5114cb5ad4433ac7e7e45e72 Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 26 Jun 2017 08:08:08 +0200 Subject: [PATCH 2/2] [Yaml] use scalar type hints where possible --- src/Symfony/Component/Yaml/Dumper.php | 7 +-- src/Symfony/Component/Yaml/Escaper.php | 8 +-- .../Yaml/Exception/ParseException.php | 2 +- src/Symfony/Component/Yaml/Inline.php | 48 +++++++------- src/Symfony/Component/Yaml/Parser.php | 62 +++++++++---------- src/Symfony/Component/Yaml/Unescaper.php | 8 +-- src/Symfony/Component/Yaml/Yaml.php | 4 +- 7 files changed, 68 insertions(+), 71 deletions(-) diff --git a/src/Symfony/Component/Yaml/Dumper.php b/src/Symfony/Component/Yaml/Dumper.php index 87e06b5255..92ce4c9d28 100644 --- a/src/Symfony/Component/Yaml/Dumper.php +++ b/src/Symfony/Component/Yaml/Dumper.php @@ -27,10 +27,7 @@ class Dumper */ protected $indentation; - /** - * @param int $indentation - */ - public function __construct($indentation = 4) + public function __construct(int $indentation = 4) { if ($indentation < 1) { throw new \InvalidArgumentException('The indentation must be greater than zero.'); @@ -49,7 +46,7 @@ class Dumper * * @return string The YAML representation of the PHP value */ - public function dump($input, $inline = 0, $indent = 0, $flags = 0) + public function dump($input, int $inline = 0, int $indent = 0, int $flags = 0): string { $output = ''; $prefix = $indent ? str_repeat(' ', $indent) : ''; diff --git a/src/Symfony/Component/Yaml/Escaper.php b/src/Symfony/Component/Yaml/Escaper.php index 94bb3924b6..66e65bc618 100644 --- a/src/Symfony/Component/Yaml/Escaper.php +++ b/src/Symfony/Component/Yaml/Escaper.php @@ -50,7 +50,7 @@ class Escaper * * @return bool True if the value would require double quotes */ - public static function requiresDoubleQuoting($value) + public static function requiresDoubleQuoting(string $value): bool { return 0 < preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value); } @@ -62,7 +62,7 @@ class Escaper * * @return string The quoted, escaped string */ - public static function escapeWithDoubleQuotes($value) + public static function escapeWithDoubleQuotes(string $value): string { return sprintf('"%s"', str_replace(self::$escapees, self::$escaped, $value)); } @@ -74,7 +74,7 @@ class Escaper * * @return bool True if the value would require single quotes */ - public static function requiresSingleQuoting($value) + public static function requiresSingleQuoting(string $value): bool { // Determines if a PHP value is entirely composed of a value that would // require single quoting in YAML. @@ -94,7 +94,7 @@ class Escaper * * @return string The quoted, escaped string */ - public static function escapeWithSingleQuotes($value) + public static function escapeWithSingleQuotes(string $value): string { return sprintf("'%s'", str_replace('\'', '\'\'', $value)); } diff --git a/src/Symfony/Component/Yaml/Exception/ParseException.php b/src/Symfony/Component/Yaml/Exception/ParseException.php index 3b38b64396..b04cbd69ce 100644 --- a/src/Symfony/Component/Yaml/Exception/ParseException.php +++ b/src/Symfony/Component/Yaml/Exception/ParseException.php @@ -32,7 +32,7 @@ class ParseException extends RuntimeException * @param string|null $parsedFile The file name where the error occurred * @param \Exception|null $previous The previous exception */ - public function __construct($message, $parsedLine = -1, $snippet = null, $parsedFile = null, \Exception $previous = null) + public function __construct(string $message, int $parsedLine = -1, string $snippet = null, string $parsedFile = null, \Exception $previous = null) { $this->parsedFile = $parsedFile; $this->parsedLine = $parsedLine; diff --git a/src/Symfony/Component/Yaml/Inline.php b/src/Symfony/Component/Yaml/Inline.php index 3212aeca58..cc7f723726 100644 --- a/src/Symfony/Component/Yaml/Inline.php +++ b/src/Symfony/Component/Yaml/Inline.php @@ -44,7 +44,7 @@ class Inline * * @throws ParseException */ - public static function parse($value, $flags = 0, $references = array()) + public static function parse(string $value = null, int $flags = 0, array $references = array()) { self::$exceptionOnInvalidType = (bool) (Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE & $flags); self::$objectSupport = (bool) (Yaml::PARSE_OBJECT & $flags); @@ -103,7 +103,7 @@ class Inline * * @throws DumpException When trying to dump PHP resource */ - public static function dump($value, $flags = 0) + public static function dump($value, int $flags = 0): string { switch (true) { case is_resource($value): @@ -124,7 +124,13 @@ class Inline } if (Yaml::DUMP_OBJECT_AS_MAP & $flags && ($value instanceof \stdClass || $value instanceof \ArrayObject)) { - return self::dumpArray($value, $flags & ~Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE); + $output = array(); + + foreach ($value as $key => $val) { + $output[] = sprintf('%s: %s', self::dump($key, $flags), self::dump($val, $flags)); + } + + return sprintf('{ %s }', implode(', ', $output)); } if (Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE & $flags) { @@ -182,13 +188,11 @@ class Inline /** * Check if given array is hash or just normal indexed array. * - * @internal - * * @param array|\ArrayObject|\stdClass $value The PHP array or array-like object to check * * @return bool true if value is hash array, false otherwise */ - public static function isHash($value) + public static function isHash($value): bool { if ($value instanceof \stdClass || $value instanceof \ArrayObject) { return true; @@ -213,7 +217,7 @@ class Inline * * @return string The YAML string representing the PHP array */ - private static function dumpArray($value, $flags) + private static function dumpArray(array $value, int $flags): string { // array if (($value || Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE & $flags) && !self::isHash($value)) { @@ -244,13 +248,11 @@ class Inline * @param bool $evaluate * @param array $references * - * @return string + * @return mixed * * @throws ParseException When malformed inline YAML string is parsed - * - * @internal */ - public static function parseScalar($scalar, $flags = 0, $delimiters = null, &$i = 0, $evaluate = true, $references = array()) + public static function parseScalar(string $scalar, int $flags = 0, array $delimiters = null, int &$i = 0, bool $evaluate = true, array $references = array()) { if (in_array($scalar[$i], array('"', "'"))) { // quoted scalar @@ -302,7 +304,7 @@ class Inline * * @throws ParseException When malformed inline YAML string is parsed */ - private static function parseQuotedScalar($scalar, &$i) + private static function parseQuotedScalar(string $scalar, int &$i): string { if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i))); @@ -334,7 +336,7 @@ class Inline * * @throws ParseException When malformed inline YAML string is parsed */ - private static function parseSequence($sequence, $flags, &$i = 0, $references = array()) + private static function parseSequence(string $sequence, int $flags, int &$i = 0, array $references = array()): array { $output = array(); $len = strlen($sequence); @@ -403,7 +405,7 @@ class Inline * * @throws ParseException When malformed inline YAML string is parsed */ - private static function parseMapping($mapping, $flags, &$i = 0, $references = array()) + private static function parseMapping(string $mapping, int $flags, int &$i = 0, array $references = array()) { $output = array(); $len = strlen($mapping); @@ -515,7 +517,7 @@ class Inline * * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved */ - private static function evaluateScalar($scalar, $flags, $references = array()) + private static function evaluateScalar(string $scalar, int $flags, array $references = array()) { $scalar = trim($scalar); $scalarLower = strtolower($scalar); @@ -638,10 +640,10 @@ class Inline * * @return null|string */ - private static function parseTag($value, &$i, $flags) + private static function parseTag(string $value, int &$i, int $flags): ?string { if ('!' !== $value[$i]) { - return; + return null; } $tagLength = strcspn($value, " \t\n[]{},", $i + 1); @@ -653,7 +655,7 @@ class Inline // Is followed by a scalar and is a built-in tag if ($tag && (!isset($value[$nextOffset]) || !in_array($value[$nextOffset], array('[', '{'), true)) && ('!' === $tag[0] || 'str' === $tag || 'php/const' === $tag || 'php/object' === $tag)) { // Manage in {@link self::evaluateScalar()} - return; + return null; } $i = $nextOffset; @@ -674,10 +676,8 @@ class Inline * @param string $scalar * * @return string - * - * @internal */ - public static function evaluateBinaryScalar($scalar) + public static function evaluateBinaryScalar(string $scalar): string { $parsedBinaryData = self::parseScalar(preg_replace('/\s/', '', $scalar)); @@ -692,7 +692,7 @@ class Inline return base64_decode($parsedBinaryData, true); } - private static function isBinaryString($value) + private static function isBinaryString(string $value) { return !preg_match('//u', $value) || preg_match('/[^\x00\x07-\x0d\x1B\x20-\xff]/', $value); } @@ -704,7 +704,7 @@ class Inline * * @see http://www.yaml.org/spec/1.2/spec.html#id2761573 */ - private static function getTimestampRegex() + private static function getTimestampRegex(): string { return <<getRealCurrentLineNb(); } - private function doParse($value, $flags) + private function doParse(string $value, int $flags) { $this->currentLineNb = -1; $this->currentLine = ''; @@ -146,7 +146,7 @@ class Parser // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { - $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $flags); + $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true) ?? '', $flags); } elseif (null !== $subTag = $this->getLineTag(ltrim($values['value'], ' '), $flags)) { $data[] = new TaggedValue( $subTag, @@ -383,7 +383,7 @@ class Parser return empty($data) ? null : $data; } - private function parseBlock($offset, $yaml, $flags) + private function parseBlock(int $offset, string $yaml, int $flags) { $skippedLineNumbers = $this->skippedLineNumbers; @@ -411,7 +411,7 @@ class Parser * * @return int The current line number */ - public function getRealCurrentLineNb() + public function getRealCurrentLineNb(): int { $realCurrentLineNumber = $this->currentLineNb + $this->offset; @@ -431,7 +431,7 @@ class Parser * * @return int The current line indentation */ - private function getCurrentLineIndentation() + private function getCurrentLineIndentation(): int { return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); } @@ -439,14 +439,14 @@ class Parser /** * Returns the next embed block of YAML. * - * @param int $indentation The indent level at which the block is to be read, or null for default - * @param bool $inSequence True if the enclosing data structure is a sequence + * @param int|null $indentation The indent level at which the block is to be read, or null for default + * @param bool $inSequence True if the enclosing data structure is a sequence * * @return string A YAML string * * @throws ParseException When indentation problem are detected */ - private function getNextEmbedBlock($indentation = null, $inSequence = false) + private function getNextEmbedBlock(int $indentation = null, bool $inSequence = false): ?string { $oldLineIndentation = $this->getCurrentLineIndentation(); $blockScalarIndentations = array(); @@ -456,7 +456,7 @@ class Parser } if (!$this->moveToNextLine()) { - return; + return null; } if (null === $indentation) { @@ -477,7 +477,7 @@ class Parser } else { $this->moveToPreviousLine(); - return; + return null; } if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) { @@ -485,7 +485,7 @@ class Parser // and therefore no nested list or mapping $this->moveToPreviousLine(); - return; + return null; } $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem(); @@ -556,7 +556,7 @@ class Parser * * @return bool */ - private function moveToNextLine() + private function moveToNextLine(): bool { if ($this->currentLineNb >= count($this->lines) - 1) { return false; @@ -572,7 +572,7 @@ class Parser * * @return bool */ - private function moveToPreviousLine() + private function moveToPreviousLine(): bool { if ($this->currentLineNb < 1) { return false; @@ -594,7 +594,7 @@ class Parser * * @throws ParseException When reference does not exist */ - private function parseValue($value, $flags, $context) + private function parseValue(string $value, int $flags, string $context) { if (0 === strpos($value, '*')) { if (false !== $pos = strpos($value, '#')) { @@ -675,7 +675,7 @@ class Parser * * @return string The text value */ - private function parseBlockScalar($style, $chomping = '', $indentation = 0) + private function parseBlockScalar(string $style, string $chomping = '', int $indentation = 0): string { $notEOF = $this->moveToNextLine(); if (!$notEOF) { @@ -782,7 +782,7 @@ class Parser * * @return bool Returns true if the next line is indented, false otherwise */ - private function isNextLineIndented() + private function isNextLineIndented(): bool { $currentIndentation = $this->getCurrentLineIndentation(); $EOF = !$this->moveToNextLine(); @@ -807,7 +807,7 @@ class Parser * * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise */ - private function isCurrentLineEmpty() + private function isCurrentLineEmpty(): bool { return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); } @@ -817,7 +817,7 @@ class Parser * * @return bool Returns true if the current line is blank, false otherwise */ - private function isCurrentLineBlank() + private function isCurrentLineBlank(): bool { return '' == trim($this->currentLine, ' '); } @@ -827,7 +827,7 @@ class Parser * * @return bool Returns true if the current line is a comment line, false otherwise */ - private function isCurrentLineComment() + private function isCurrentLineComment(): bool { //checking explicitly the first char of the trim is faster than loops or strpos $ltrimmedLine = ltrim($this->currentLine, ' '); @@ -835,7 +835,7 @@ class Parser return '' !== $ltrimmedLine && $ltrimmedLine[0] === '#'; } - private function isCurrentLineLastLineInDocument() + private function isCurrentLineLastLineInDocument(): bool { return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1); } @@ -847,7 +847,7 @@ class Parser * * @return string A cleaned up YAML string */ - private function cleanup($value) + private function cleanup(string $value): string { $value = str_replace(array("\r\n", "\r"), "\n", $value); @@ -883,7 +883,7 @@ class Parser * * @return bool Returns true if the next line starts unindented collection, false otherwise */ - private function isNextLineUnIndentedCollection() + private function isNextLineUnIndentedCollection(): bool { $currentIndentation = $this->getCurrentLineIndentation(); $notEOF = $this->moveToNextLine(); @@ -908,7 +908,7 @@ class Parser * * @return bool Returns true if the string is un-indented collection item, false otherwise */ - private function isStringUnIndentedCollectionItem() + private function isStringUnIndentedCollectionItem(): bool { return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- '); } @@ -918,7 +918,7 @@ class Parser * * @return bool */ - private function isBlockScalarHeader() + private function isBlockScalarHeader(): bool { return (bool) self::preg_match('~'.self::BLOCK_SCALAR_HEADER_PATTERN.'$~', $this->currentLine); } @@ -936,7 +936,7 @@ class Parser * * @internal */ - public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0) + public static function preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int { if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) { switch (preg_last_error()) { @@ -971,7 +971,7 @@ class Parser * Prevent values such as `!foo {quz: bar}` to be considered as * a mapping block. */ - private function trimTag($value) + private function trimTag(string $value): string { if ('!' === $value[0]) { return ltrim(substr($value, 1, strcspn($value, " \r\n", 1)), ' '); @@ -980,14 +980,14 @@ class Parser return $value; } - private function getLineTag($value, $flags, $nextLineCheck = true) + private function getLineTag(string $value, int $flags, bool $nextLineCheck = true): ?string { if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) { - return; + return null; } if ($nextLineCheck && !$this->isNextLineIndented()) { - return; + return null; } $tag = substr($matches['tag'], 1); diff --git a/src/Symfony/Component/Yaml/Unescaper.php b/src/Symfony/Component/Yaml/Unescaper.php index 6e863e12f2..c9285acb49 100644 --- a/src/Symfony/Component/Yaml/Unescaper.php +++ b/src/Symfony/Component/Yaml/Unescaper.php @@ -35,7 +35,7 @@ class Unescaper * * @return string The unescaped string */ - public function unescapeSingleQuotedString($value) + public function unescapeSingleQuotedString(string $value): string { return str_replace('\'\'', '\'', $value); } @@ -47,7 +47,7 @@ class Unescaper * * @return string The unescaped string */ - public function unescapeDoubleQuotedString($value) + public function unescapeDoubleQuotedString(string $value): string { $callback = function ($match) { return $this->unescapeCharacter($match[0]); @@ -64,7 +64,7 @@ class Unescaper * * @return string The unescaped character */ - private function unescapeCharacter($value) + private function unescapeCharacter(string $value): string { switch ($value[1]) { case '0': @@ -125,7 +125,7 @@ class Unescaper * * @return string The corresponding UTF-8 character */ - private static function utf8chr($c) + private static function utf8chr(int $c): string { if (0x80 > $c %= 0x200000) { return chr($c); diff --git a/src/Symfony/Component/Yaml/Yaml.php b/src/Symfony/Component/Yaml/Yaml.php index 674982c33e..992aac1ece 100644 --- a/src/Symfony/Component/Yaml/Yaml.php +++ b/src/Symfony/Component/Yaml/Yaml.php @@ -50,7 +50,7 @@ class Yaml * * @throws ParseException If the YAML is not valid */ - public static function parse($input, $flags = 0) + public static function parse(string $input, int $flags = 0) { $yaml = new Parser(); @@ -70,7 +70,7 @@ class Yaml * * @return string A YAML string representing the original PHP value */ - public static function dump($input, $inline = 2, $indent = 4, $flags = 0) + public static function dump($input, int $inline = 2, int $indent = 4, int $flags = 0): string { $yaml = new Dumper($indent);