diff --git a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php index 191a853ac5c93..9855fc477a90e 100644 --- a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php +++ b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php @@ -17,6 +17,16 @@ use Doctrine\Persistence\ManagerRegistry; use Doctrine\Persistence\Mapping\MappingException; use Doctrine\Persistence\Proxy; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\CollectionType; +use Symfony\Component\Form\Extension\Core\Type\DateIntervalType; +use Symfony\Component\Form\Extension\Core\Type\DateTimeType; +use Symfony\Component\Form\Extension\Core\Type\DateType; +use Symfony\Component\Form\Extension\Core\Type\IntegerType; +use Symfony\Component\Form\Extension\Core\Type\NumberType; +use Symfony\Component\Form\Extension\Core\Type\TextareaType; +use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Form\Extension\Core\Type\TimeType; use Symfony\Component\Form\FormTypeGuesserInterface; use Symfony\Component\Form\Guess\Guess; use Symfony\Component\Form\Guess\TypeGuess; @@ -51,44 +61,29 @@ public function guessType(string $class, string $property): ?TypeGuess return new TypeGuess('Symfony\Bridge\Doctrine\Form\Type\EntityType', ['em' => $name, 'class' => $mapping['targetEntity'], 'multiple' => $multiple], Guess::HIGH_CONFIDENCE); } - switch ($metadata->getTypeOfField($property)) { - case Types::ARRAY: - case Types::SIMPLE_ARRAY: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CollectionType', [], Guess::MEDIUM_CONFIDENCE); - case Types::BOOLEAN: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\CheckboxType', [], Guess::HIGH_CONFIDENCE); - case Types::DATETIME_MUTABLE: - case Types::DATETIMETZ_MUTABLE: - case 'vardatetime': - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateTimeType', [], Guess::HIGH_CONFIDENCE); - case Types::DATETIME_IMMUTABLE: - case Types::DATETIMETZ_IMMUTABLE: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateTimeType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE); - case Types::DATEINTERVAL: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateIntervalType', [], Guess::HIGH_CONFIDENCE); - case Types::DATE_MUTABLE: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', [], Guess::HIGH_CONFIDENCE); - case Types::DATE_IMMUTABLE: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\DateType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE); - case Types::TIME_MUTABLE: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', [], Guess::HIGH_CONFIDENCE); - case Types::TIME_IMMUTABLE: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TimeType', ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE); - case Types::DECIMAL: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\NumberType', ['input' => 'string'], Guess::MEDIUM_CONFIDENCE); - case Types::FLOAT: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\NumberType', [], Guess::MEDIUM_CONFIDENCE); - case Types::INTEGER: - case Types::BIGINT: - case Types::SMALLINT: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\IntegerType', [], Guess::MEDIUM_CONFIDENCE); - case Types::STRING: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::MEDIUM_CONFIDENCE); - case Types::TEXT: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextareaType', [], Guess::MEDIUM_CONFIDENCE); - default: - return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::LOW_CONFIDENCE); - } + return match ($metadata->getTypeOfField($property)) { + Types::ARRAY, + Types::SIMPLE_ARRAY => new TypeGuess(CollectionType::class, [], Guess::MEDIUM_CONFIDENCE), + Types::BOOLEAN => new TypeGuess(CheckboxType::class, [], Guess::HIGH_CONFIDENCE), + Types::DATETIME_MUTABLE, + Types::DATETIMETZ_MUTABLE, + 'vardatetime' => new TypeGuess(DateTimeType::class, [], Guess::HIGH_CONFIDENCE), + Types::DATETIME_IMMUTABLE, + Types::DATETIMETZ_IMMUTABLE => new TypeGuess(DateTimeType::class, ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE), + Types::DATEINTERVAL => new TypeGuess(DateIntervalType::class, [], Guess::HIGH_CONFIDENCE), + Types::DATE_MUTABLE => new TypeGuess(DateType::class, [], Guess::HIGH_CONFIDENCE), + Types::DATE_IMMUTABLE => new TypeGuess(DateType::class, ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE), + Types::TIME_MUTABLE => new TypeGuess(TimeType::class, [], Guess::HIGH_CONFIDENCE), + Types::TIME_IMMUTABLE => new TypeGuess(TimeType::class, ['input' => 'datetime_immutable'], Guess::HIGH_CONFIDENCE), + Types::DECIMAL => new TypeGuess(NumberType::class, ['input' => 'string'], Guess::MEDIUM_CONFIDENCE), + Types::FLOAT => new TypeGuess(NumberType::class, [], Guess::MEDIUM_CONFIDENCE), + Types::INTEGER, + Types::BIGINT, + Types::SMALLINT => new TypeGuess(IntegerType::class, [], Guess::MEDIUM_CONFIDENCE), + Types::STRING => new TypeGuess(TextType::class, [], Guess::MEDIUM_CONFIDENCE), + Types::TEXT => new TypeGuess(TextareaType::class, [], Guess::MEDIUM_CONFIDENCE), + default => new TypeGuess(TextType::class, [], Guess::LOW_CONFIDENCE), + }; } /** diff --git a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php index c7e51cb172105..aa4149e6cf91d 100644 --- a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php +++ b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php @@ -247,47 +247,33 @@ private function isAssociationNullable(array $associationMapping): bool */ private function getPhpType(string $doctrineType): ?string { - switch ($doctrineType) { - case Types::SMALLINT: - case Types::INTEGER: - return Type::BUILTIN_TYPE_INT; - - case Types::FLOAT: - return Type::BUILTIN_TYPE_FLOAT; - - case Types::BIGINT: - case Types::STRING: - case Types::TEXT: - case Types::GUID: - case Types::DECIMAL: - return Type::BUILTIN_TYPE_STRING; - - case Types::BOOLEAN: - return Type::BUILTIN_TYPE_BOOL; - - case Types::BLOB: - case Types::BINARY: - return Type::BUILTIN_TYPE_RESOURCE; - - case Types::OBJECT: - case Types::DATE_MUTABLE: - case Types::DATETIME_MUTABLE: - case Types::DATETIMETZ_MUTABLE: - case 'vardatetime': - case Types::TIME_MUTABLE: - case Types::DATE_IMMUTABLE: - case Types::DATETIME_IMMUTABLE: - case Types::DATETIMETZ_IMMUTABLE: - case Types::TIME_IMMUTABLE: - case Types::DATEINTERVAL: - return Type::BUILTIN_TYPE_OBJECT; - - case Types::ARRAY: - case Types::SIMPLE_ARRAY: - case 'json_array': - return Type::BUILTIN_TYPE_ARRAY; - } - - return null; + return match ($doctrineType) { + Types::SMALLINT, + Types::INTEGER => Type::BUILTIN_TYPE_INT, + Types::FLOAT => Type::BUILTIN_TYPE_FLOAT, + Types::BIGINT, + Types::STRING, + Types::TEXT, + Types::GUID, + Types::DECIMAL => Type::BUILTIN_TYPE_STRING, + Types::BOOLEAN => Type::BUILTIN_TYPE_BOOL, + Types::BLOB, + Types::BINARY => Type::BUILTIN_TYPE_RESOURCE, + Types::OBJECT, + Types::DATE_MUTABLE, + Types::DATETIME_MUTABLE, + Types::DATETIMETZ_MUTABLE, + 'vardatetime', + Types::TIME_MUTABLE, + Types::DATE_IMMUTABLE, + Types::DATETIME_IMMUTABLE, + Types::DATETIMETZ_IMMUTABLE, + Types::TIME_IMMUTABLE, + Types::DATEINTERVAL => Type::BUILTIN_TYPE_OBJECT, + Types::ARRAY, + Types::SIMPLE_ARRAY, + 'json_array' => Type::BUILTIN_TYPE_ARRAY, + default => null, + }; } } diff --git a/src/Symfony/Bridge/Twig/Command/LintCommand.php b/src/Symfony/Bridge/Twig/Command/LintCommand.php index dfe66054bc496..6aede16f7ff04 100644 --- a/src/Symfony/Bridge/Twig/Command/LintCommand.php +++ b/src/Symfony/Bridge/Twig/Command/LintCommand.php @@ -172,16 +172,12 @@ private function validate(string $template, string $file): array private function display(InputInterface $input, OutputInterface $output, SymfonyStyle $io, array $files) { - switch ($this->format) { - case 'txt': - return $this->displayTxt($output, $io, $files); - case 'json': - return $this->displayJson($output, $files); - case 'github': - return $this->displayTxt($output, $io, $files, true); - default: - throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $input->getOption('format'))); - } + return match ($this->format) { + 'txt' => $this->displayTxt($output, $io, $files), + 'json' => $this->displayJson($output, $files), + 'github' => $this->displayTxt($output, $io, $files, true), + default => throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $input->getOption('format'))), + }; } private function displayTxt(OutputInterface $output, SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false) diff --git a/src/Symfony/Bridge/Twig/Mime/NotificationEmail.php b/src/Symfony/Bridge/Twig/Mime/NotificationEmail.php index 084dc3489f270..45cd06b2b2918 100644 --- a/src/Symfony/Bridge/Twig/Mime/NotificationEmail.php +++ b/src/Symfony/Bridge/Twig/Mime/NotificationEmail.php @@ -192,17 +192,12 @@ public function getPreparedHeaders(): Headers private function determinePriority(string $importance): int { - switch ($importance) { - case self::IMPORTANCE_URGENT: - return self::PRIORITY_HIGHEST; - case self::IMPORTANCE_HIGH: - return self::PRIORITY_HIGH; - case self::IMPORTANCE_MEDIUM: - return self::PRIORITY_NORMAL; - case self::IMPORTANCE_LOW: - default: - return self::PRIORITY_LOW; - } + return match ($importance) { + self::IMPORTANCE_URGENT => self::PRIORITY_HIGHEST, + self::IMPORTANCE_HIGH => self::PRIORITY_HIGH, + self::IMPORTANCE_MEDIUM => self::PRIORITY_NORMAL, + default => self::PRIORITY_LOW, + }; } private function getExceptionAsString(\Throwable|FlattenException $exception): string diff --git a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php index 1cc9c0ebf3e5c..9d57d304ab5af 100644 --- a/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php +++ b/src/Symfony/Bundle/TwigBundle/Tests/DependencyInjection/TwigExtensionTest.php @@ -297,19 +297,11 @@ private function loadFromFile(ContainerBuilder $container, $file, $format) { $locator = new FileLocator(__DIR__.'/Fixtures/'.$format); - switch ($format) { - case 'php': - $loader = new PhpFileLoader($container, $locator); - break; - case 'xml': - $loader = new XmlFileLoader($container, $locator); - break; - case 'yml': - $loader = new YamlFileLoader($container, $locator); - break; - default: - throw new \InvalidArgumentException(sprintf('Unsupported format: "%s"', $format)); - } + $loader = match ($format) { + 'php' => new PhpFileLoader($container, $locator), + 'xml' => new XmlFileLoader($container, $locator), + 'yml' => new YamlFileLoader($container, $locator), + }; $loader->load($file.'.'.$format); } diff --git a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php index df67579218b04..d65c1f81080aa 100644 --- a/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php +++ b/src/Symfony/Bundle/WebProfilerBundle/Tests/Profiler/TemplateManagerTest.php @@ -75,24 +75,20 @@ public function testGetNameValidTemplate() public function profilerHasCallback($panel) { - switch ($panel) { - case 'foo': - case 'bar': - return true; - default: - return false; - } + return match ($panel) { + 'foo', + 'bar' => true, + default => false, + }; } public function profileHasCollectorCallback($panel) { - switch ($panel) { - case 'foo': - case 'baz': - return true; - default: - return false; - } + return match ($panel) { + 'foo', + 'baz' => true, + default => false, + }; } protected function mockTwigEnvironment() @@ -120,12 +116,10 @@ public function __construct() public function hasCollector(string $name): bool { - switch ($name) { - case 'foo': - case 'bar': - return true; - default: - return false; - } + return match ($name) { + 'foo', + 'bar' => true, + default => false, + }; } } diff --git a/src/Symfony/Component/Cache/Adapter/DoctrineDbalAdapter.php b/src/Symfony/Component/Cache/Adapter/DoctrineDbalAdapter.php index 774cdf4ceb11d..c65d0dee7ac2f 100644 --- a/src/Symfony/Component/Cache/Adapter/DoctrineDbalAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/DoctrineDbalAdapter.php @@ -338,28 +338,17 @@ private function getPlatformName(): string $platform = $this->conn->getDatabasePlatform(); - switch (true) { - case $platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform: - return $this->platformName = 'mysql'; - - case $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform: - return $this->platformName = 'sqlite'; - - case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform: - return $this->platformName = 'pgsql'; - - case $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform: - return $this->platformName = 'oci'; - - case $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform: - return $this->platformName = 'sqlsrv'; - - default: - return $this->platformName = \get_class($platform); - } + return match (true) { + $platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform => $this->platformName = 'mysql', + $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform => $this->platformName = 'sqlite', + $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform => $this->platformName = 'pgsql', + $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform => $this->platformName = 'oci', + $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform => $this->platformName = 'sqlsrv', + default => $this->platformName = \get_class($platform), + }; } private function getServerVersion(): string diff --git a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php index 4b76b2004e529..91dd97e9cc087 100644 --- a/src/Symfony/Component/Cache/Adapter/PdoAdapter.php +++ b/src/Symfony/Component/Cache/Adapter/PdoAdapter.php @@ -103,30 +103,19 @@ public function createTable() // connect if we are not yet $conn = $this->getConnection(); - switch ($this->driver) { - case 'mysql': - // We use varbinary for the ID column because it prevents unwanted conversions: - // - character set conversions between server and client - // - trailing space removal - // - case-insensitivity - // - language processing like é == e - $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(255) NOT NULL PRIMARY KEY, $this->dataCol MEDIUMBLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB"; - break; - case 'sqlite': - $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)"; - break; - case 'pgsql': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)"; - break; - case 'oci': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(255) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)"; - break; - case 'sqlsrv': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)"; - break; - default: - throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver)); - } + $sql = match ($this->driver) { + // We use varbinary for the ID column because it prevents unwanted conversions: + // - character set conversions between server and client + // - trailing space removal + // - case-insensitivity + // - language processing like é == e + 'mysql' => "CREATE TABLE $this->table ($this->idCol VARBINARY(255) NOT NULL PRIMARY KEY, $this->dataCol MEDIUMBLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB", + 'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)", + 'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)", + 'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(255) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)", + 'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(255) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER, $this->timeCol INTEGER NOT NULL)", + default => throw new \DomainException(sprintf('Creating the cache table is currently not implemented for PDO driver "%s".', $this->driver)), + }; $conn->exec($sql); } diff --git a/src/Symfony/Component/Cache/Traits/RedisTrait.php b/src/Symfony/Component/Cache/Traits/RedisTrait.php index c0e9016e16d20..e6c6c73cfeb11 100644 --- a/src/Symfony/Component/Cache/Traits/RedisTrait.php +++ b/src/Symfony/Component/Cache/Traits/RedisTrait.php @@ -239,11 +239,11 @@ public static function createConnection(string $dsn, array $options = []): \Redi } } elseif (is_a($class, \RedisArray::class, true)) { foreach ($hosts as $i => $host) { - switch ($host['scheme']) { - case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break; - case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break; - default: $hosts[$i] = $host['path']; - } + $hosts[$i] = match ($host['scheme']) { + 'tcp' => $host['host'].':'.$host['port'], + 'tls' => 'tls://'.$host['host'].':'.$host['port'], + default => $host['path'], + }; } $params['lazy_connect'] = $params['lazy'] ?? true; $params['connect_timeout'] = $params['timeout']; @@ -260,11 +260,11 @@ public static function createConnection(string $dsn, array $options = []): \Redi } elseif (is_a($class, \RedisCluster::class, true)) { $initializer = static function () use ($class, $params, $dsn, $hosts) { foreach ($hosts as $i => $host) { - switch ($host['scheme']) { - case 'tcp': $hosts[$i] = $host['host'].':'.$host['port']; break; - case 'tls': $hosts[$i] = 'tls://'.$host['host'].':'.$host['port']; break; - default: $hosts[$i] = $host['path']; - } + $hosts[$i] = match ($host['scheme']) { + 'tcp' => $host['host'].':'.$host['port'], + 'tls' => 'tls://'.$host['host'].':'.$host['port'], + default => $host['path'], + }; } try { diff --git a/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php b/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php index 2d43b94326b93..1ad8522e00d4d 100644 --- a/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php +++ b/src/Symfony/Component/Config/Definition/Dumper/XmlReferenceDumper.php @@ -13,10 +13,14 @@ use Symfony\Component\Config\Definition\ArrayNode; use Symfony\Component\Config\Definition\BaseNode; +use Symfony\Component\Config\Definition\BooleanNode; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Config\Definition\EnumNode; +use Symfony\Component\Config\Definition\FloatNode; +use Symfony\Component\Config\Definition\IntegerNode; use Symfony\Component\Config\Definition\NodeInterface; use Symfony\Component\Config\Definition\PrototypedArrayNode; +use Symfony\Component\Config\Definition\ScalarNode; /** * Dumps an XML reference configuration for the given configuration/node instance. @@ -100,27 +104,14 @@ private function writeNode(NodeInterface $node, int $depth = 0, bool $root = fal if ($prototype->hasDefaultValue()) { $prototypeValue = $prototype->getDefaultValue(); } else { - switch (\get_class($prototype)) { - case 'Symfony\Component\Config\Definition\ScalarNode': - $prototypeValue = 'scalar value'; - break; - - case 'Symfony\Component\Config\Definition\FloatNode': - case 'Symfony\Component\Config\Definition\IntegerNode': - $prototypeValue = 'numeric value'; - break; - - case 'Symfony\Component\Config\Definition\BooleanNode': - $prototypeValue = 'true|false'; - break; - - case 'Symfony\Component\Config\Definition\EnumNode': - $prototypeValue = implode('|', array_map('json_encode', $prototype->getValues())); - break; - - default: - $prototypeValue = 'value'; - } + $prototypeValue = match (\get_class($prototype)) { + ScalarNode::class => 'scalar value', + FloatNode::class, + IntegerNode::class => 'numeric value', + BooleanNode::class => 'true|false', + EnumNode::class => implode('|', array_map('json_encode', $prototype->getValues())), + default => 'value', + }; } } } diff --git a/src/Symfony/Component/Config/Tests/Fixtures/Builder/NodeBuilder.php b/src/Symfony/Component/Config/Tests/Fixtures/Builder/NodeBuilder.php index df1bcd45374d4..e4763460f28e0 100644 --- a/src/Symfony/Component/Config/Tests/Fixtures/Builder/NodeBuilder.php +++ b/src/Symfony/Component/Config/Tests/Fixtures/Builder/NodeBuilder.php @@ -23,12 +23,10 @@ public function barNode(?string $name): NodeDefinition protected function getNodeClass(string $type): string { - switch ($type) { - case 'bar': - case 'variable': - return __NAMESPACE__.'\\'.ucfirst($type).'NodeDefinition'; - default: - return parent::getNodeClass($type); - } + return match ($type) { + 'bar', + 'variable' => __NAMESPACE__ . '\\' . ucfirst($type) . 'NodeDefinition', + default => parent::getNodeClass($type), + }; } } diff --git a/src/Symfony/Component/Console/Helper/Dumper.php b/src/Symfony/Component/Console/Helper/Dumper.php index 29263d853e26f..ac7571ceafa7d 100644 --- a/src/Symfony/Component/Console/Helper/Dumper.php +++ b/src/Symfony/Component/Console/Helper/Dumper.php @@ -41,18 +41,13 @@ public function __construct(OutputInterface $output, CliDumper $dumper = null, C }; } else { $this->handler = function ($var): string { - switch (true) { - case null === $var: - return 'null'; - case true === $var: - return 'true'; - case false === $var: - return 'false'; - case \is_string($var): - return '"'.$var.'"'; - default: - return rtrim(print_r($var, true)); - } + return match (true) { + null === $var => 'null', + true === $var => 'true', + false === $var => 'false', + \is_string($var) => '"'.$var.'"', + default => rtrim(print_r($var, true)), + }; }; } } diff --git a/src/Symfony/Component/Console/Helper/ProgressBar.php b/src/Symfony/Component/Console/Helper/ProgressBar.php index b087b4b924728..0bb10a2239f0e 100644 --- a/src/Symfony/Component/Console/Helper/ProgressBar.php +++ b/src/Symfony/Component/Console/Helper/ProgressBar.php @@ -489,17 +489,13 @@ private function overwrite(string $message): void private function determineBestFormat(): string { - switch ($this->output->getVerbosity()) { + return match ($this->output->getVerbosity()) { // OutputInterface::VERBOSITY_QUIET: display is disabled anyway - case OutputInterface::VERBOSITY_VERBOSE: - return $this->max ? self::FORMAT_VERBOSE : self::FORMAT_VERBOSE_NOMAX; - case OutputInterface::VERBOSITY_VERY_VERBOSE: - return $this->max ? self::FORMAT_VERY_VERBOSE : self::FORMAT_VERY_VERBOSE_NOMAX; - case OutputInterface::VERBOSITY_DEBUG: - return $this->max ? self::FORMAT_DEBUG : self::FORMAT_DEBUG_NOMAX; - default: - return $this->max ? self::FORMAT_NORMAL : self::FORMAT_NORMAL_NOMAX; - } + OutputInterface::VERBOSITY_VERBOSE => $this->max ? self::FORMAT_VERBOSE : self::FORMAT_VERBOSE_NOMAX, + OutputInterface::VERBOSITY_VERY_VERBOSE => $this->max ? self::FORMAT_VERY_VERBOSE : self::FORMAT_VERY_VERBOSE_NOMAX, + OutputInterface::VERBOSITY_DEBUG => $this->max ? self::FORMAT_DEBUG : self::FORMAT_DEBUG_NOMAX, + default => $this->max ? self::FORMAT_NORMAL : self::FORMAT_NORMAL_NOMAX, + }; } private static function initPlaceholderFormatters(): array diff --git a/src/Symfony/Component/Console/Helper/ProgressIndicator.php b/src/Symfony/Component/Console/Helper/ProgressIndicator.php index 9ca24e9424a4c..955f67e68e580 100644 --- a/src/Symfony/Component/Console/Helper/ProgressIndicator.php +++ b/src/Symfony/Component/Console/Helper/ProgressIndicator.php @@ -191,16 +191,13 @@ private function display() private function determineBestFormat(): string { - switch ($this->output->getVerbosity()) { + return match ($this->output->getVerbosity()) { // OutputInterface::VERBOSITY_QUIET: display is disabled anyway - case OutputInterface::VERBOSITY_VERBOSE: - return $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi'; - case OutputInterface::VERBOSITY_VERY_VERBOSE: - case OutputInterface::VERBOSITY_DEBUG: - return $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi'; - default: - return $this->output->isDecorated() ? 'normal' : 'normal_no_ansi'; - } + OutputInterface::VERBOSITY_VERBOSE => $this->output->isDecorated() ? 'verbose' : 'verbose_no_ansi', + OutputInterface::VERBOSITY_VERY_VERBOSE, + OutputInterface::VERBOSITY_DEBUG => $this->output->isDecorated() ? 'very_verbose' : 'very_verbose_no_ansi', + default => $this->output->isDecorated() ? 'normal' : 'normal_no_ansi', + }; } /** diff --git a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php index 371eb69c04ab9..8f7fbde55b096 100644 --- a/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php +++ b/src/Symfony/Component/DependencyInjection/Dumper/PhpDumper.php @@ -1496,7 +1496,7 @@ private function addDefaultParametersMethod(): string $export = explode('0 => ', substr(rtrim($export, " ]\n"), 2, -1), 2); if ($hasEnum || preg_match("/\\\$this->(?:getEnv\('(?:[-.\w]*+:)*+\w++'\)|targetDir\.'')/", $export[1])) { - $dynamicPhp[$key] = sprintf('%scase %s: $value = %s; break;', $export[0], $this->export($key), $export[1]); + $dynamicPhp[$key] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]); } else { $php[] = sprintf('%s%s => %s,', $export[0], $this->export($key), $export[1]); } @@ -1559,10 +1559,10 @@ public function getParameterBag(): ParameterBagInterface if ($dynamicPhp) { $loadedDynamicParameters = $this->exportParameters(array_combine(array_keys($dynamicPhp), array_fill(0, \count($dynamicPhp), false)), '', 8); $getDynamicParameter = <<<'EOF' - switch ($name) { + $value = match ($name) { %s - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name)); - } + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php b/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php index b150b4ac69a10..43861894296fb 100644 --- a/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php +++ b/src/Symfony/Component/DependencyInjection/Loader/IniFileLoader.php @@ -83,21 +83,18 @@ private function phpize(string $value): mixed } $lowercaseValue = strtolower($value); - switch (true) { - case \defined($value): - return \constant($value); - case 'yes' === $lowercaseValue || 'on' === $lowercaseValue: - return true; - case 'no' === $lowercaseValue || 'off' === $lowercaseValue || 'none' === $lowercaseValue: - return false; - case isset($value[1]) && ( + return match (true) { + \defined($value) => \constant($value), + 'yes' === $lowercaseValue, + 'on' === $lowercaseValue => true, + 'no' === $lowercaseValue, + 'off' === $lowercaseValue, + 'none' === $lowercaseValue => false, + isset($value[1]) && ( ("'" === $value[0] && "'" === $value[\strlen($value) - 1]) || ('"' === $value[0] && '"' === $value[\strlen($value) - 1]) - ): - // quoted string - return substr($value, 1, -1); - default: - return XmlUtils::phpize($value); - } + ) => substr($value, 1, -1), // quoted string + default => XmlUtils::phpize($value), + }; } } diff --git a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php index eed9c45e8b5d5..11e6243b8b177 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Dumper/PhpDumperTest.php @@ -1257,14 +1257,14 @@ public function testDumpHandlesEnumeration() %A private function getDynamicParameter(string $name) { - switch ($name) { - case 'unit_enum': $value = \Symfony\Component\DependencyInjection\Tests\Fixtures\FooUnitEnum::BAR; break; - case 'enum_array': $value = [ + $value = match ($name) { + 'unit_enum' => \Symfony\Component\DependencyInjection\Tests\Fixtures\FooUnitEnum::BAR, + 'enum_array' => [ 0 => \Symfony\Component\DependencyInjection\Tests\Fixtures\FooUnitEnum::BAR, 1 => \Symfony\Component\DependencyInjection\Tests\Fixtures\FooUnitEnum::FOO, - ]; break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + ], + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; %A PHP , $dumpedContainer diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php index 038ed1460e2c3..6094aca5cb514 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services19.php @@ -105,10 +105,10 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'foo': $value = $this->getEnv('FOO'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'foo' => $this->getEnv('FOO'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services26.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services26.php index 4ae8d63c7625b..2ec4dedce6bc8 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services26.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services26.php @@ -104,13 +104,13 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'bar': $value = $this->getEnv('FOO'); break; - case 'baz': $value = $this->getEnv('int:Baz'); break; - case 'json': $value = $this->getEnv('json:file:json_file'); break; - case 'db_dsn': $value = $this->getEnv('resolve:DB'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'bar' => $this->getEnv('FOO'), + 'baz' => $this->getEnv('int:Baz'), + 'json' => $this->getEnv('json:file:json_file'), + 'db_dsn' => $this->getEnv('resolve:DB'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_base64_env.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_base64_env.php index cee2a435a9db9..f95a680c377c0 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_base64_env.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_base64_env.php @@ -77,10 +77,10 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'hello': $value = $this->getEnv('base64:foo'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'hello' => $this->getEnv('base64:foo'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_csv_env.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_csv_env.php index 054fe1ea8384b..86cdfb16b9593 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_csv_env.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_csv_env.php @@ -77,10 +77,10 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'hello': $value = $this->getEnv('csv:foo'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'hello' => $this->getEnv('csv:foo'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_default_env.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_default_env.php index 82044d62df5ba..d80d585b00d38 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_default_env.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_default_env.php @@ -79,12 +79,12 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'fallback_env': $value = $this->getEnv('foobar'); break; - case 'hello': $value = $this->getEnv('default:fallback_param:bar'); break; - case 'hello-bar': $value = $this->getEnv('default:fallback_env:key:baz:json:foo'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'fallback_env' => $this->getEnv('foobar'), + 'hello' => $this->getEnv('default:fallback_param:bar'), + 'hello-bar' => $this->getEnv('default:fallback_env:key:baz:json:foo'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_json_env.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_json_env.php index ef9b95f2ea895..ac545a187a2c5 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_json_env.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_json_env.php @@ -78,11 +78,11 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'hello': $value = $this->getEnv('json:foo'); break; - case 'hello-bar': $value = $this->getEnv('json:bar'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'hello' => $this->getEnv('json:foo'), + 'hello-bar' => $this->getEnv('json:bar'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_query_string_env.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_query_string_env.php index 6d147b930f408..2f94be03a4f09 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_query_string_env.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_query_string_env.php @@ -77,10 +77,10 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'hello': $value = $this->getEnv('query_string:foo'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'hello' => $this->getEnv('query_string:foo'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_rot13_env.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_rot13_env.php index a17f9ed56a7cf..51db550bd7cfe 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_rot13_env.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_rot13_env.php @@ -114,10 +114,10 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'hello': $value = $this->getEnv('rot13:foo'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'hello' => $this->getEnv('rot13:foo'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_url_env.php b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_url_env.php index b370f8db7c009..28dbd86fa5600 100644 --- a/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_url_env.php +++ b/src/Symfony/Component/DependencyInjection/Tests/Fixtures/php/services_url_env.php @@ -77,10 +77,10 @@ public function getParameterBag(): ParameterBagInterface private function getDynamicParameter(string $name) { - switch ($name) { - case 'hello': $value = $this->getEnv('url:foo'); break; - default: throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)); - } + $value = match ($name) { + 'hello' => $this->getEnv('url:foo'), + default => throw new InvalidArgumentException(sprintf('The dynamic parameter "%s" must be defined.', $name)), + }; $this->loadedDynamicParameters[$name] = true; return $this->dynamicParameters[$name] = $value; diff --git a/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php b/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php index 9bd9d9b13525f..9e30d848eb4fc 100644 --- a/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php +++ b/src/Symfony/Component/ExpressionLanguage/Node/UnaryNode.php @@ -48,15 +48,13 @@ public function compile(Compiler $compiler) public function evaluate(array $functions, array $values) { $value = $this->nodes['node']->evaluate($functions, $values); - switch ($this->attributes['operator']) { - case 'not': - case '!': - return !$value; - case '-': - return -$value; - } - return $value; + return match ($this->attributes['operator']) { + 'not', + '!' => !$value, + '-' => -$value, + default => $value, + }; } public function toArray(): array diff --git a/src/Symfony/Component/Finder/Comparator/Comparator.php b/src/Symfony/Component/Finder/Comparator/Comparator.php index f1ba97d3defd0..bd685834739d2 100644 --- a/src/Symfony/Component/Finder/Comparator/Comparator.php +++ b/src/Symfony/Component/Finder/Comparator/Comparator.php @@ -50,19 +50,13 @@ public function getOperator(): string */ public function test(mixed $test): bool { - switch ($this->operator) { - case '>': - return $test > $this->target; - case '>=': - return $test >= $this->target; - case '<': - return $test < $this->target; - case '<=': - return $test <= $this->target; - case '!=': - return $test != $this->target; - } - - return $test == $this->target; + return match ($this->operator) { + '>' => $test > $this->target, + '>=' => $test >= $this->target, + '<' => $test < $this->target, + '<=' => $test <= $this->target, + '!=' => $test != $this->target, + default => $test == $this->target, + }; } } diff --git a/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php b/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php index 028e35845251d..2c23df7fd1785 100644 --- a/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php +++ b/src/Symfony/Component/Finder/Tests/Iterator/MockSplFileInfo.php @@ -89,18 +89,13 @@ public function setMode($mode) public function setType($type) { if (\is_string($type)) { - switch ($type) { - case 'directory': - case 'd': - $this->type = self::TYPE_DIRECTORY; - break; - case 'file': - case 'f': - $this->type = self::TYPE_FILE; - break; - default: - $this->type = self::TYPE_UNKNOWN; - } + $this->type = match ($type) { + 'directory', + 'd' => self::TYPE_DIRECTORY, + 'file', + 'f' => self::TYPE_FILE, + default => self::TYPE_UNKNOWN, + }; } else { $this->type = $type; } diff --git a/src/Symfony/Component/Form/Extension/Validator/ValidatorTypeGuesser.php b/src/Symfony/Component/Form/Extension/Validator/ValidatorTypeGuesser.php index 7c9afa7c9b4d6..dd4f8c7684c55 100644 --- a/src/Symfony/Component/Form/Extension/Validator/ValidatorTypeGuesser.php +++ b/src/Symfony/Component/Form/Extension/Validator/ValidatorTypeGuesser.php @@ -16,6 +16,9 @@ use Symfony\Component\Form\Guess\TypeGuess; use Symfony\Component\Form\Guess\ValueGuess; use Symfony\Component\Validator\Constraint; +use Symfony\Component\Validator\Constraints\IsTrue; +use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Mapping\ClassMetadataInterface; use Symfony\Component\Validator\Mapping\Factory\MetadataFactoryInterface; @@ -166,14 +169,12 @@ public function guessTypeForConstraint(Constraint $constraint): ?TypeGuess */ public function guessRequiredForConstraint(Constraint $constraint): ?ValueGuess { - switch (\get_class($constraint)) { - case 'Symfony\Component\Validator\Constraints\NotNull': - case 'Symfony\Component\Validator\Constraints\NotBlank': - case 'Symfony\Component\Validator\Constraints\IsTrue': - return new ValueGuess(true, Guess::HIGH_CONFIDENCE); - } - - return null; + return match (\get_class($constraint)) { + NotNull::class, + NotBlank::class, + IsTrue::class => new ValueGuess(true, Guess::HIGH_CONFIDENCE), + default => null, + }; } /** diff --git a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php index 95f011899eaa2..aac5736870473 100644 --- a/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php +++ b/src/Symfony/Component/Form/Tests/ChoiceList/Factory/DefaultChoiceListFactoryTest.php @@ -729,11 +729,11 @@ public function testCreateViewFlatAttrClosureReceivesKey() null, // index null, // group function ($object, $key) { - switch ($key) { - case 'B': return ['attr1' => 'value1']; - case 'C': return ['attr2' => 'value2']; - default: return []; - } + return match ($key) { + 'B' => ['attr1' => 'value1'], + 'C' => ['attr2' => 'value2'], + default => [], + }; } ); @@ -749,11 +749,11 @@ public function testCreateViewFlatAttrClosureReceivesValue() null, // index null, // group function ($object, $key, $value) { - switch ($value) { - case '1': return ['attr1' => 'value1']; - case '2': return ['attr2' => 'value2']; - default: return []; - } + return match ($value) { + '1' => ['attr1' => 'value1'], + '2' => ['attr2' => 'value2'], + default => [], + }; } ); @@ -852,10 +852,10 @@ public function testCreateViewFlatlabelTranslationParametersClosureReceivesKey() null, // group null, // attr function ($object, $key) { - switch ($key) { - case 'D': return ['%placeholder1%' => 'value1']; - default: return []; - } + return match ($key) { + 'D' => ['%placeholder1%' => 'value1'], + default => [], + }; } ); @@ -872,10 +872,10 @@ public function testCreateViewFlatlabelTranslationParametersClosureReceivesValue null, // group null, // attr function ($object, $key, $value) { - switch ($value) { - case '3': return ['%placeholder1%' => 'value1']; - default: return []; - } + return match ($value) { + '3' => ['%placeholder1%' => 'value1'], + default => [], + }; } ); diff --git a/src/Symfony/Component/HttpClient/HttpClientTrait.php b/src/Symfony/Component/HttpClient/HttpClientTrait.php index 485c017101057..bc018fd9acf5e 100644 --- a/src/Symfony/Component/HttpClient/HttpClientTrait.php +++ b/src/Symfony/Component/HttpClient/HttpClientTrait.php @@ -369,13 +369,13 @@ private static function normalizeBody($body) private static function normalizePeerFingerprint(mixed $fingerprint): array { if (\is_string($fingerprint)) { - switch (\strlen($fingerprint = str_replace(':', '', $fingerprint))) { - case 32: $fingerprint = ['md5' => $fingerprint]; break; - case 40: $fingerprint = ['sha1' => $fingerprint]; break; - case 44: $fingerprint = ['pin-sha256' => [$fingerprint]]; break; - case 64: $fingerprint = ['sha256' => $fingerprint]; break; - default: throw new InvalidArgumentException(sprintf('Cannot auto-detect fingerprint algorithm for "%s".', $fingerprint)); - } + $fingerprint = match (\strlen($fingerprint = str_replace(':', '', $fingerprint))) { + 32 => ['md5' => $fingerprint], + 40 => ['sha1' => $fingerprint], + 44 => ['pin-sha256' => [$fingerprint]], + 64 => ['sha256' => $fingerprint], + default => throw new InvalidArgumentException(sprintf('Cannot auto-detect fingerprint algorithm for "%s".', $fingerprint)), + }; } elseif (\is_array($fingerprint)) { foreach ($fingerprint as $algo => $hash) { $fingerprint[$algo] = 'pin-sha256' === $algo ? (array) $hash : str_replace(':', '', $hash); diff --git a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php index 9ef1c496e1153..f43507ae55f0f 100644 --- a/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php +++ b/src/Symfony/Component/HttpFoundation/Session/Storage/Handler/PdoSessionHandler.php @@ -184,30 +184,19 @@ public function createTable() // connect if we are not yet $this->getConnection(); - switch ($this->driver) { - case 'mysql': - // We use varbinary for the ID column because it prevents unwanted conversions: - // - character set conversions between server and client - // - trailing space removal - // - case-insensitivity - // - language processing like é == e - $sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB"; - break; - case 'sqlite': - $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; - break; - case 'pgsql': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; - break; - case 'oci': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; - break; - case 'sqlsrv': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)"; - break; - default: - throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)); - } + $sql = match ($this->driver) { + // We use varbinary for the ID column because it prevents unwanted conversions: + // - character set conversions between server and client + // - trailing space removal + // - case-insensitivity + // - language processing like é == e + 'mysql' => "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB", + 'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)", + 'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)", + 'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)", + 'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)", + default => throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)), + }; try { $this->pdo->exec($sql); diff --git a/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php b/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php index 2b20819b7a222..c7a592c37b0f2 100644 --- a/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php +++ b/src/Symfony/Component/HttpFoundation/Tests/File/UploadedFileTest.php @@ -173,31 +173,16 @@ public function failedUploadedFile() */ public function testMoveFailed(UploadedFile $file) { - switch ($file->getError()) { - case \UPLOAD_ERR_INI_SIZE: - $exceptionClass = IniSizeFileException::class; - break; - case \UPLOAD_ERR_FORM_SIZE: - $exceptionClass = FormSizeFileException::class; - break; - case \UPLOAD_ERR_PARTIAL: - $exceptionClass = PartialFileException::class; - break; - case \UPLOAD_ERR_NO_FILE: - $exceptionClass = NoFileException::class; - break; - case \UPLOAD_ERR_CANT_WRITE: - $exceptionClass = CannotWriteFileException::class; - break; - case \UPLOAD_ERR_NO_TMP_DIR: - $exceptionClass = NoTmpDirFileException::class; - break; - case \UPLOAD_ERR_EXTENSION: - $exceptionClass = ExtensionFileException::class; - break; - default: - $exceptionClass = FileException::class; - } + $exceptionClass = match ($file->getError()) { + \UPLOAD_ERR_INI_SIZE => IniSizeFileException::class, + \UPLOAD_ERR_FORM_SIZE => FormSizeFileException::class, + \UPLOAD_ERR_PARTIAL => PartialFileException::class, + \UPLOAD_ERR_NO_FILE => NoFileException::class, + \UPLOAD_ERR_CANT_WRITE => CannotWriteFileException::class, + \UPLOAD_ERR_NO_TMP_DIR => NoTmpDirFileException::class, + \UPLOAD_ERR_EXTENSION => ExtensionFileException::class, + default => FileException::class, + }; $this->expectException($exceptionClass); diff --git a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php index e7d7fde93020d..3445b5c5f58b4 100644 --- a/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php +++ b/src/Symfony/Component/Ldap/Adapter/ExtLdap/Query.php @@ -75,19 +75,12 @@ public function execute(): CollectionInterface $this->results = []; $con = $this->connection->getResource(); - switch ($this->options['scope']) { - case static::SCOPE_BASE: - $func = 'ldap_read'; - break; - case static::SCOPE_ONE: - $func = 'ldap_list'; - break; - case static::SCOPE_SUB: - $func = 'ldap_search'; - break; - default: - throw new LdapException(sprintf('Could not search in scope "%s".', $this->options['scope'])); - } + $func = match ($this->options['scope']) { + static::SCOPE_BASE => 'ldap_read', + static::SCOPE_ONE => 'ldap_list', + static::SCOPE_SUB => 'ldap_search', + default => throw new LdapException(sprintf('Could not search in scope "%s".', $this->options['scope'])), + }; $itemsLeft = $maxItems = $this->options['maxItems']; $pageSize = $this->options['pageSize']; diff --git a/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php b/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php index d0bdca474923d..23090ce473c06 100644 --- a/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php +++ b/src/Symfony/Component/Lock/Store/DoctrineDbalStore.php @@ -223,28 +223,17 @@ private function prune(): void private function getCurrentTimestampStatement(): string { $platform = $this->conn->getDatabasePlatform(); - switch (true) { - case $platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform: - return 'UNIX_TIMESTAMP()'; - - case $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform: - return 'strftime(\'%s\',\'now\')'; - - case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform: - return 'CAST(EXTRACT(epoch FROM NOW()) AS INT)'; - - case $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform: - return '(SYSDATE - TO_DATE(\'19700101\',\'yyyymmdd\'))*86400 - TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone), 1, 3))*3600'; - - case $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform: - return 'DATEDIFF(s, \'1970-01-01\', GETUTCDATE())'; - - default: - return (string) time(); - } + return match (true) { + $platform instanceof \Doctrine\DBAL\Platforms\MySQLPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\MySQL57Platform => 'UNIX_TIMESTAMP()', + $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform => 'strftime(\'%s\',\'now\')', + $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform => 'CAST(EXTRACT(epoch FROM NOW()) AS INT)', + $platform instanceof \Doctrine\DBAL\Platforms\OraclePlatform => '(SYSDATE - TO_DATE(\'19700101\',\'yyyymmdd\'))*86400 - TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone), 1, 3))*3600', + $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform => 'DATEDIFF(s, \'1970-01-01\', GETUTCDATE())', + default => (string) time(), + }; } /** @@ -254,15 +243,13 @@ private function platformSupportsTableCreationInTransaction(): bool { $platform = $this->conn->getDatabasePlatform(); - switch (true) { - case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform: - case $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform: - case $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform: - return true; - default: - return false; - } + return match (true) { + $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQLPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\PostgreSQL94Platform, + $platform instanceof \Doctrine\DBAL\Platforms\SqlitePlatform, + $platform instanceof \Doctrine\DBAL\Platforms\SQLServerPlatform, + $platform instanceof \Doctrine\DBAL\Platforms\SQLServer2012Platform => true, + default => false, + }; } } diff --git a/src/Symfony/Component/Lock/Store/PdoStore.php b/src/Symfony/Component/Lock/Store/PdoStore.php index da91e1a77637b..3e6c3db17be9c 100644 --- a/src/Symfony/Component/Lock/Store/PdoStore.php +++ b/src/Symfony/Component/Lock/Store/PdoStore.php @@ -193,25 +193,14 @@ public function createTable(): void $conn = $this->getConnection(); $driver = $this->getDriver(); - switch ($driver) { - case 'mysql': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(44) NOT NULL, $this->expirationCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB"; - break; - case 'sqlite': - $sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->tokenCol TEXT NOT NULL, $this->expirationCol INTEGER)"; - break; - case 'pgsql': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)"; - break; - case 'oci': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR2(64) NOT NULL, $this->expirationCol INTEGER)"; - break; - case 'sqlsrv': - $sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)"; - break; - default: - throw new \DomainException(sprintf('Creating the lock table is currently not implemented for platform "%s".', $driver)); - } + $sql = match ($driver) { + 'mysql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(44) NOT NULL, $this->expirationCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB", + 'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->tokenCol TEXT NOT NULL, $this->expirationCol INTEGER)", + 'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)", + 'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR2(64) NOT NULL, $this->expirationCol INTEGER)", + 'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(64) NOT NULL PRIMARY KEY, $this->tokenCol VARCHAR(64) NOT NULL, $this->expirationCol INTEGER)", + default => throw new \DomainException(sprintf('Creating the lock table is currently not implemented for platform "%s".', $driver)), + }; $conn->exec($sql); } @@ -243,19 +232,13 @@ private function getDriver(): string */ private function getCurrentTimestampStatement(): string { - switch ($this->getDriver()) { - case 'mysql': - return 'UNIX_TIMESTAMP()'; - case 'sqlite': - return 'strftime(\'%s\',\'now\')'; - case 'pgsql': - return 'CAST(EXTRACT(epoch FROM NOW()) AS INT)'; - case 'oci': - return '(SYSDATE - TO_DATE(\'19700101\',\'yyyymmdd\'))*86400 - TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone), 1, 3))*3600'; - case 'sqlsrv': - return 'DATEDIFF(s, \'1970-01-01\', GETUTCDATE())'; - default: - return (string) time(); - } + return match ($this->getDriver()) { + 'mysql' => 'UNIX_TIMESTAMP()', + 'sqlite' => 'strftime(\'%s\',\'now\')', + 'pgsql' => 'CAST(EXTRACT(epoch FROM NOW()) AS INT)', + 'oci' => '(SYSDATE - TO_DATE(\'19700101\',\'yyyymmdd\'))*86400 - TO_NUMBER(SUBSTR(TZ_OFFSET(sessiontimezone), 1, 3))*3600', + 'sqlsrv' => 'DATEDIFF(s, \'1970-01-01\', GETUTCDATE())', + default => (string) time(), + }; } } diff --git a/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php b/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php index b3c8cb7c6ef3f..843853d02d065 100644 --- a/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php +++ b/src/Symfony/Component/Messenger/Transport/Serialization/Serializer.php @@ -174,18 +174,14 @@ private function getContentTypeHeader(): array private function getMimeTypeForFormat(): ?string { - switch ($this->format) { - case 'json': - return 'application/json'; - case 'xml': - return 'application/xml'; - case 'yml': - case 'yaml': - return 'application/x-yaml'; - case 'csv': - return 'text/csv'; - } + return match ($this->format) { + 'json' => 'application/json', + 'xml' => 'application/xml', + 'yml', + 'yaml' => 'application/x-yaml', + 'csv' => 'text/csv', + default => null, + }; - return null; } } diff --git a/src/Symfony/Component/Mime/CharacterStream.php b/src/Symfony/Component/Mime/CharacterStream.php index e1b64b50fa745..21d7bc5f01737 100644 --- a/src/Symfony/Component/Mime/CharacterStream.php +++ b/src/Symfony/Component/Mime/CharacterStream.php @@ -72,29 +72,22 @@ public function __construct($input, ?string $charset = 'utf-8') $this->fixedWidth = 0; $this->map = ['p' => [], 'i' => []]; } else { - switch ($charset) { + $this->fixedWidth = match ($charset) { // 16 bits - case 'ucs2': - case 'ucs-2': - case 'utf16': - case 'utf-16': - $this->fixedWidth = 2; - break; - + 'ucs2', + 'ucs-2', + 'utf16', + 'utf-16' => 2, // 32 bits - case 'ucs4': - case 'ucs-4': - case 'utf32': - case 'utf-32': - $this->fixedWidth = 4; - break; - + 'ucs4', + 'ucs-4', + 'utf32', + 'utf-32' => 4, // 7-8 bit charsets: (us-)?ascii, (iso|iec)-?8859-?[0-9]+, windows-?125[0-9], cp-?[0-9]+, ansi, macintosh, // koi-?7, koi-?8-?.+, mik, (cork|t1), v?iscii // and fallback - default: - $this->fixedWidth = 1; - } + default => 1, + }; } if (\is_resource($input)) { $blocks = 16372; diff --git a/src/Symfony/Component/Mime/Encoder/QpContentEncoder.php b/src/Symfony/Component/Mime/Encoder/QpContentEncoder.php index 4703cc2e68d2e..6f420fff334b2 100644 --- a/src/Symfony/Component/Mime/Encoder/QpContentEncoder.php +++ b/src/Symfony/Component/Mime/Encoder/QpContentEncoder.php @@ -46,15 +46,10 @@ private function standardize(string $string): string // transform =0D=0A to CRLF $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string); - switch (\ord(substr($string, -1))) { - case 0x09: - $string = substr_replace($string, '=09', -1); - break; - case 0x20: - $string = substr_replace($string, '=20', -1); - break; - } - - return $string; + return match (\ord(substr($string, -1))) { + 0x09 => substr_replace($string, '=09', -1), + 0x20 => substr_replace($string, '=20', -1), + default => $string, + }; } } diff --git a/src/Symfony/Component/Mime/Encoder/QpEncoder.php b/src/Symfony/Component/Mime/Encoder/QpEncoder.php index 0b4bcf538de34..2d9f409388df9 100644 --- a/src/Symfony/Component/Mime/Encoder/QpEncoder.php +++ b/src/Symfony/Component/Mime/Encoder/QpEncoder.php @@ -184,12 +184,10 @@ private function encodeByteSequence(array $bytes, int &$size): string private function standardize(string $string): string { $string = str_replace(["\t=0D=0A", ' =0D=0A', '=0D=0A'], ["=09\r\n", "=20\r\n", "\r\n"], $string); - switch ($end = \ord(substr($string, -1))) { - case 0x09: - case 0x20: - $string = substr_replace($string, self::QP_MAP[$end], -1); - } - - return $string; + return match ($end = \ord(substr($string, -1))) { + 0x09, + 0x20 => substr_replace($string, self::QP_MAP[$end], -1), + default => $string, + }; } } diff --git a/src/Symfony/Component/Notifier/Notification/Notification.php b/src/Symfony/Component/Notifier/Notification/Notification.php index e320f155035fa..e568841378820 100644 --- a/src/Symfony/Component/Notifier/Notification/Notification.php +++ b/src/Symfony/Component/Notifier/Notification/Notification.php @@ -167,17 +167,12 @@ protected function getDefaultEmoji(): string return ''; } - switch ($this->importance) { - case self::IMPORTANCE_URGENT: - return '🌩️'; - case self::IMPORTANCE_HIGH: - return '🌧️'; - case self::IMPORTANCE_MEDIUM: - return '🌦️'; - case self::IMPORTANCE_LOW: - default: - return '⛅'; - } + return match ($this->importance) { + self::IMPORTANCE_URGENT => '🌩️', + self::IMPORTANCE_HIGH => '🌧️', + self::IMPORTANCE_MEDIUM => '🌦️', + default => '⛅', + }; } private function computeExceptionAsString(\Throwable $exception): string diff --git a/src/Symfony/Component/Process/Exception/ProcessTimedOutException.php b/src/Symfony/Component/Process/Exception/ProcessTimedOutException.php index 94391a4596327..b052d72cb0020 100644 --- a/src/Symfony/Component/Process/Exception/ProcessTimedOutException.php +++ b/src/Symfony/Component/Process/Exception/ProcessTimedOutException.php @@ -55,15 +55,10 @@ public function isIdleTimeout() public function getExceededTimeout() { - switch ($this->timeoutType) { - case self::TYPE_GENERAL: - return $this->process->getTimeout(); - - case self::TYPE_IDLE: - return $this->process->getIdleTimeout(); - - default: - throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType)); - } + return match ($this->timeoutType) { + self::TYPE_GENERAL => $this->process->getTimeout(), + self::TYPE_IDLE => $this->process->getIdleTimeout(), + default => throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType)), + }; } } diff --git a/src/Symfony/Component/Process/Tests/NonStopableProcess.php b/src/Symfony/Component/Process/Tests/NonStopableProcess.php index c695f544d29ba..846718f0bcf7c 100644 --- a/src/Symfony/Component/Process/Tests/NonStopableProcess.php +++ b/src/Symfony/Component/Process/Tests/NonStopableProcess.php @@ -18,17 +18,11 @@ */ function handleSignal($signal) { - switch ($signal) { - case \SIGTERM: - $name = 'SIGTERM'; - break; - case \SIGINT: - $name = 'SIGINT'; - break; - default: - $name = $signal.' (unknown)'; - break; - } + $name = match ($signal) { + \SIGTERM => 'SIGTERM', + \SIGINT => 'SIGINT', + default => $signal . ' (unknown)', + }; echo "signal $name\n"; } diff --git a/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php b/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php index f4b2d23d4ca04..a776f22368d64 100644 --- a/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php +++ b/src/Symfony/Component/PropertyInfo/Util/PhpDocTypeHelper.php @@ -166,26 +166,15 @@ private function createType(DocType $type, bool $nullable, string $docType = nul private function normalizeType(string $docType): string { - switch ($docType) { - case 'integer': - return 'int'; - - case 'boolean': - return 'bool'; - + return match ($docType) { + 'integer' => 'int', + 'boolean' => 'bool', // real is not part of the PHPDoc standard, so we ignore it - case 'double': - return 'float'; - - case 'callback': - return 'callable'; - - case 'void': - return 'null'; - - default: - return $docType; - } + 'double' => 'float', + 'callback' => 'callable', + 'void' => 'null', + default => $docType, + }; } private function getPhpTypeAndClass(string $docType): array diff --git a/src/Symfony/Component/PropertyInfo/Util/PhpStanTypeHelper.php b/src/Symfony/Component/PropertyInfo/Util/PhpStanTypeHelper.php index d9803fd9bd702..236eaaf873e17 100644 --- a/src/Symfony/Component/PropertyInfo/Util/PhpStanTypeHelper.php +++ b/src/Symfony/Component/PropertyInfo/Util/PhpStanTypeHelper.php @@ -165,48 +165,35 @@ private function extractTypes(TypeNode $node, NameScope $nameScope): array return [new Type($node->name, false, null, \in_array($node->name, Type::$builtinCollectionTypes))]; } - switch ($node->name) { - case 'integer': - case 'positive-int': - case 'negative-int': - return [new Type(Type::BUILTIN_TYPE_INT)]; - case 'double': - return [new Type(Type::BUILTIN_TYPE_FLOAT)]; - case 'list': - case 'non-empty-list': - return [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT))]; - case 'non-empty-array': - return [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true)]; - case 'mixed': - return []; // mixed seems to be ignored in all other extractors - case 'parent': - return [new Type(Type::BUILTIN_TYPE_OBJECT, false, $node->name)]; - case 'static': - case 'self': - return [new Type(Type::BUILTIN_TYPE_OBJECT, false, $nameScope->resolveRootClass())]; - case 'class-string': - case 'html-escaped-string': - case 'lowercase-string': - case 'non-empty-lowercase-string': - case 'non-empty-string': - case 'numeric-string': - case 'trait-string': - case 'interface-string': - case 'literal-string': - return [new Type(Type::BUILTIN_TYPE_STRING)]; - case 'void': - return [new Type(Type::BUILTIN_TYPE_NULL)]; - case 'scalar': - return [new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_FLOAT), new Type(Type::BUILTIN_TYPE_STRING), new Type(Type::BUILTIN_TYPE_BOOL)]; - case 'number': - return [new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_FLOAT)]; - case 'numeric': - return [new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_FLOAT), new Type(Type::BUILTIN_TYPE_STRING)]; - case 'array-key': - return [new Type(Type::BUILTIN_TYPE_STRING), new Type(Type::BUILTIN_TYPE_INT)]; - } + return match ($node->name) { + 'integer', + 'positive-int', + 'negative-int' => [new Type(Type::BUILTIN_TYPE_INT)], + 'double' => [new Type(Type::BUILTIN_TYPE_FLOAT)], + 'list', + 'non-empty-list' => [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true, new Type(Type::BUILTIN_TYPE_INT))], + 'non-empty-array' => [new Type(Type::BUILTIN_TYPE_ARRAY, false, null, true)], + 'mixed' => [], // mixed seems to be ignored in all other extractors + 'parent' => [new Type(Type::BUILTIN_TYPE_OBJECT, false, $node->name)], + 'static', + 'self' => [new Type(Type::BUILTIN_TYPE_OBJECT, false, $nameScope->resolveRootClass())], + 'class-string', + 'html-escaped-string', + 'lowercase-string', + 'non-empty-lowercase-string', + 'non-empty-string', + 'numeric-string', + 'trait-string', + 'interface-string', + 'literal-string' => [new Type(Type::BUILTIN_TYPE_STRING)], + 'void' => [new Type(Type::BUILTIN_TYPE_NULL)], + 'scalar' => [new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_FLOAT), new Type(Type::BUILTIN_TYPE_STRING), new Type(Type::BUILTIN_TYPE_BOOL)], + 'number' => [new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_FLOAT)], + 'numeric' => [new Type(Type::BUILTIN_TYPE_INT), new Type(Type::BUILTIN_TYPE_FLOAT), new Type(Type::BUILTIN_TYPE_STRING)], + 'array-key' => [new Type(Type::BUILTIN_TYPE_STRING), new Type(Type::BUILTIN_TYPE_INT)], + default => [new Type(Type::BUILTIN_TYPE_OBJECT, false, $nameScope->resolveStringName($node->name))], + }; - return [new Type(Type::BUILTIN_TYPE_OBJECT, false, $nameScope->resolveStringName($node->name))]; } return []; diff --git a/src/Symfony/Component/RateLimiter/RateLimiterFactory.php b/src/Symfony/Component/RateLimiter/RateLimiterFactory.php index 4fcb25e98c257..fe5536ef11a67 100644 --- a/src/Symfony/Component/RateLimiter/RateLimiterFactory.php +++ b/src/Symfony/Component/RateLimiter/RateLimiterFactory.php @@ -47,22 +47,13 @@ public function create(string $key = null): LimiterInterface $id = $this->config['id'].'-'.$key; $lock = $this->lockFactory ? $this->lockFactory->createLock($id) : new NoLock(); - switch ($this->config['policy']) { - case 'token_bucket': - return new TokenBucketLimiter($id, $this->config['limit'], $this->config['rate'], $this->storage, $lock); - - case 'fixed_window': - return new FixedWindowLimiter($id, $this->config['limit'], $this->config['interval'], $this->storage, $lock); - - case 'sliding_window': - return new SlidingWindowLimiter($id, $this->config['limit'], $this->config['interval'], $this->storage, $lock); - - case 'no_limit': - return new NoLimiter(); - - default: - throw new \LogicException(sprintf('Limiter policy "%s" does not exists, it must be either "token_bucket", "sliding_window", "fixed_window" or "no_limit".', $this->config['policy'])); - } + return match ($this->config['policy']) { + 'token_bucket' => new TokenBucketLimiter($id, $this->config['limit'], $this->config['rate'], $this->storage, $lock), + 'fixed_window' => new FixedWindowLimiter($id, $this->config['limit'], $this->config['interval'], $this->storage, $lock), + 'sliding_window' => new SlidingWindowLimiter($id, $this->config['limit'], $this->config['interval'], $this->storage, $lock), + 'no_limit' => new NoLimiter(), + default => throw new \LogicException(sprintf('Limiter policy "%s" does not exists, it must be either "token_bucket", "sliding_window", "fixed_window" or "no_limit".', $this->config['policy'])), + }; } protected static function configureOptions(OptionsResolver $options): void diff --git a/src/Symfony/Component/Runtime/SymfonyRuntime.php b/src/Symfony/Component/Runtime/SymfonyRuntime.php index 8526c75012eb0..753eb285a7833 100644 --- a/src/Symfony/Component/Runtime/SymfonyRuntime.php +++ b/src/Symfony/Component/Runtime/SymfonyRuntime.php @@ -174,24 +174,15 @@ public function getRunner(?object $application): RunnerInterface protected function getArgument(\ReflectionParameter $parameter, ?string $type): mixed { - switch ($type) { - case Request::class: - return Request::createFromGlobals(); + return match ($type) { + Request::class => Request::createFromGlobals(), + InputInterface::class => $this->getInput(), + OutputInterface::class => $this->output ??= new ConsoleOutput(), + Application::class => $this->console ??= new Application(), + Command::class => $this->command ??= new Command(), + default => parent::getArgument($parameter, $type), + }; - case InputInterface::class: - return $this->getInput(); - - case OutputInterface::class: - return $this->output ??= new ConsoleOutput(); - - case Application::class: - return $this->console ??= new Application(); - - case Command::class: - return $this->command ??= new Command(); - } - - return parent::getArgument($parameter, $type); } protected static function register(GenericRuntime $runtime): GenericRuntime diff --git a/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php b/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php index 09481036d7ea8..acecec58df242 100644 --- a/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php +++ b/src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php @@ -494,18 +494,12 @@ private function validateAndDenormalize(array $types, string $currentClass, stri return (float) $data; } - switch ($data) { - case 'NaN': - return \NAN; - case 'INF': - return \INF; - case '-INF': - return -\INF; - default: - throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $currentClass, $data), $data, [Type::BUILTIN_TYPE_FLOAT], $context['deserialization_path'] ?? null); - } - - break; + return match ($data) { + 'NaN' => \NAN, + 'INF' => \INF, + '-INF' => -\INF, + default => throw NotNormalizableValueException::createForUnexpectedDataType(sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $currentClass, $data), $data, [Type::BUILTIN_TYPE_FLOAT], $context['deserialization_path'] ?? null), + }; } } diff --git a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php index 7609686b827d6..fe006c1878e78 100644 --- a/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php +++ b/src/Symfony/Component/Serializer/Tests/Normalizer/AbstractObjectNormalizerTest.php @@ -258,18 +258,15 @@ public function testDenormalizeWithNestedDiscriminatorMap() $classDiscriminatorResolver = new class() implements ClassDiscriminatorResolverInterface { public function getMappingForClass(string $class): ?ClassDiscriminatorMapping { - switch ($class) { - case AbstractDummy::class: - return new ClassDiscriminatorMapping('type', [ - 'foo' => AbstractDummyFirstChild::class, - ]); - case AbstractDummyFirstChild::class: - return new ClassDiscriminatorMapping('nested_type', [ - 'bar' => AbstractDummySecondChild::class, - ]); - default: - return null; - } + return match ($class) { + AbstractDummy::class => new ClassDiscriminatorMapping('type', [ + 'foo' => AbstractDummyFirstChild::class, + ]), + AbstractDummyFirstChild::class => new ClassDiscriminatorMapping('nested_type', [ + 'bar' => AbstractDummySecondChild::class, + ]), + default => null, + }; } public function getMappingForMappedObject($object): ?ClassDiscriminatorMapping diff --git a/src/Symfony/Component/Translation/Catalogue/AbstractOperation.php b/src/Symfony/Component/Translation/Catalogue/AbstractOperation.php index 43a52fab20029..0691bf78508d8 100644 --- a/src/Symfony/Component/Translation/Catalogue/AbstractOperation.php +++ b/src/Symfony/Component/Translation/Catalogue/AbstractOperation.php @@ -174,12 +174,12 @@ public function moveMessagesToIntlDomainsIfPossible(string $batch = self::ALL_BA foreach ($this->getDomains() as $domain) { $intlDomain = $domain.MessageCatalogueInterface::INTL_DOMAIN_SUFFIX; - switch ($batch) { - case self::OBSOLETE_BATCH: $messages = $this->getObsoleteMessages($domain); break; - case self::NEW_BATCH: $messages = $this->getNewMessages($domain); break; - case self::ALL_BATCH: $messages = $this->getMessages($domain); break; - default: throw new \InvalidArgumentException(sprintf('$batch argument must be one of ["%s", "%s", "%s"].', self::ALL_BATCH, self::NEW_BATCH, self::OBSOLETE_BATCH)); - } + $messages = match ($batch) { + self::OBSOLETE_BATCH => $this->getObsoleteMessages($domain), + self::NEW_BATCH => $this->getNewMessages($domain), + self::ALL_BATCH => $this->getMessages($domain), + default => throw new \InvalidArgumentException(sprintf('$batch argument must be one of ["%s", "%s", "%s"].', self::ALL_BATCH, self::NEW_BATCH, self::OBSOLETE_BATCH)), + }; if (!$messages || (!$this->source->all($intlDomain) && $this->source->all($domain))) { continue; diff --git a/src/Symfony/Component/Translation/Command/XliffLintCommand.php b/src/Symfony/Component/Translation/Command/XliffLintCommand.php index 549a2a111d3db..e03dc53b858ed 100644 --- a/src/Symfony/Component/Translation/Command/XliffLintCommand.php +++ b/src/Symfony/Component/Translation/Command/XliffLintCommand.php @@ -156,16 +156,12 @@ private function validate(string $content, string $file = null): array private function display(SymfonyStyle $io, array $files) { - switch ($this->format) { - case 'txt': - return $this->displayTxt($io, $files); - case 'json': - return $this->displayJson($io, $files); - case 'github': - return $this->displayTxt($io, $files, true); - default: - throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format)); - } + return match ($this->format) { + 'txt' => $this->displayTxt($io, $files), + 'json' => $this->displayJson($io, $files), + 'github' => $this->displayTxt($io, $files, true), + default => throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format)), + }; } private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false) diff --git a/src/Symfony/Component/Translation/Loader/JsonFileLoader.php b/src/Symfony/Component/Translation/Loader/JsonFileLoader.php index 67a8d58ede73f..c70dfde046390 100644 --- a/src/Symfony/Component/Translation/Loader/JsonFileLoader.php +++ b/src/Symfony/Component/Translation/Loader/JsonFileLoader.php @@ -42,19 +42,13 @@ protected function loadResource(string $resource): array */ private function getJSONErrorMessage(int $errorCode): string { - switch ($errorCode) { - case \JSON_ERROR_DEPTH: - return 'Maximum stack depth exceeded'; - case \JSON_ERROR_STATE_MISMATCH: - return 'Underflow or the modes mismatch'; - case \JSON_ERROR_CTRL_CHAR: - return 'Unexpected control character found'; - case \JSON_ERROR_SYNTAX: - return 'Syntax error, malformed JSON'; - case \JSON_ERROR_UTF8: - return 'Malformed UTF-8 characters, possibly incorrectly encoded'; - default: - return 'Unknown error'; - } + return match ($errorCode) { + \JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + \JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch', + \JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + \JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON', + \JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded', + default => 'Unknown error', + }; } } diff --git a/src/Symfony/Component/Uid/Factory/UuidFactory.php b/src/Symfony/Component/Uid/Factory/UuidFactory.php index 35a06e80f33f2..aac35386e95f5 100644 --- a/src/Symfony/Component/Uid/Factory/UuidFactory.php +++ b/src/Symfony/Component/Uid/Factory/UuidFactory.php @@ -84,12 +84,12 @@ private function getNamespace(Uuid|string $namespace): Uuid return $namespace; } - switch ($namespace) { - case 'dns': return new UuidV1(Uuid::NAMESPACE_DNS); - case 'url': return new UuidV1(Uuid::NAMESPACE_URL); - case 'oid': return new UuidV1(Uuid::NAMESPACE_OID); - case 'x500': return new UuidV1(Uuid::NAMESPACE_X500); - default: return Uuid::fromString($namespace); - } + return match ($namespace) { + 'dns' => new UuidV1(Uuid::NAMESPACE_DNS), + 'url' => new UuidV1(Uuid::NAMESPACE_URL), + 'oid' => new UuidV1(Uuid::NAMESPACE_OID), + 'x500' => new UuidV1(Uuid::NAMESPACE_X500), + default => Uuid::fromString($namespace), + }; } } diff --git a/src/Symfony/Component/Uid/Uuid.php b/src/Symfony/Component/Uid/Uuid.php index 800f32f2f35b0..13c47e94088d3 100644 --- a/src/Symfony/Component/Uid/Uuid.php +++ b/src/Symfony/Component/Uid/Uuid.php @@ -64,15 +64,15 @@ public static function fromString(string $uuid): static return new NilUuid(); } - switch ($uuid[14]) { - case UuidV1::TYPE: return new UuidV1($uuid); - case UuidV3::TYPE: return new UuidV3($uuid); - case UuidV4::TYPE: return new UuidV4($uuid); - case UuidV5::TYPE: return new UuidV5($uuid); - case UuidV6::TYPE: return new UuidV6($uuid); - } + return match ((int) $uuid[14]) { + UuidV1::TYPE => new UuidV1($uuid), + UuidV3::TYPE => new UuidV3($uuid), + UuidV4::TYPE => new UuidV4($uuid), + UuidV5::TYPE => new UuidV5($uuid), + UuidV6::TYPE => new UuidV6($uuid), + default => new self($uuid), + }; - return new self($uuid); } final public static function v1(): UuidV1 diff --git a/src/Symfony/Component/Validator/Constraints/IpValidator.php b/src/Symfony/Component/Validator/Constraints/IpValidator.php index c21ce0215e788..573c7a3b17f61 100644 --- a/src/Symfony/Component/Validator/Constraints/IpValidator.php +++ b/src/Symfony/Component/Validator/Constraints/IpValidator.php @@ -47,55 +47,20 @@ public function validate(mixed $value, Constraint $constraint) $value = ($constraint->normalizer)($value); } - switch ($constraint->version) { - case Ip::V4: - $flag = \FILTER_FLAG_IPV4; - break; - - case Ip::V6: - $flag = \FILTER_FLAG_IPV6; - break; - - case Ip::V4_NO_PRIV: - $flag = \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_PRIV_RANGE; - break; - - case Ip::V6_NO_PRIV: - $flag = \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_PRIV_RANGE; - break; - - case Ip::ALL_NO_PRIV: - $flag = \FILTER_FLAG_NO_PRIV_RANGE; - break; - - case Ip::V4_NO_RES: - $flag = \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_RES_RANGE; - break; - - case Ip::V6_NO_RES: - $flag = \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_RES_RANGE; - break; - - case Ip::ALL_NO_RES: - $flag = \FILTER_FLAG_NO_RES_RANGE; - break; - - case Ip::V4_ONLY_PUBLIC: - $flag = \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE; - break; - - case Ip::V6_ONLY_PUBLIC: - $flag = \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE; - break; - - case Ip::ALL_ONLY_PUBLIC: - $flag = \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE; - break; - - default: - $flag = 0; - break; - } + $flag = match ($constraint->version) { + Ip::V4 => \FILTER_FLAG_IPV4, + Ip::V6 => \FILTER_FLAG_IPV6, + Ip::V4_NO_PRIV => \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_PRIV_RANGE, + Ip::V6_NO_PRIV => \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_PRIV_RANGE, + Ip::ALL_NO_PRIV => \FILTER_FLAG_NO_PRIV_RANGE, + Ip::V4_NO_RES => \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_RES_RANGE, + Ip::V6_NO_RES => \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_RES_RANGE, + Ip::ALL_NO_RES => \FILTER_FLAG_NO_RES_RANGE, + Ip::V4_ONLY_PUBLIC => \FILTER_FLAG_IPV4 | \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE, + Ip::V6_ONLY_PUBLIC => \FILTER_FLAG_IPV6 | \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE, + Ip::ALL_ONLY_PUBLIC => \FILTER_FLAG_NO_PRIV_RANGE | \FILTER_FLAG_NO_RES_RANGE, + default => 0, + }; if (!filter_var($value, \FILTER_VALIDATE_IP, $flag)) { $this->context->buildViolation($constraint->message) diff --git a/src/Symfony/Component/Yaml/Command/LintCommand.php b/src/Symfony/Component/Yaml/Command/LintCommand.php index 243260ea2bd02..a7d831a286eb3 100644 --- a/src/Symfony/Component/Yaml/Command/LintCommand.php +++ b/src/Symfony/Component/Yaml/Command/LintCommand.php @@ -154,16 +154,12 @@ private function validate(string $content, int $flags, string $file = null) private function display(SymfonyStyle $io, array $files): int { - switch ($this->format) { - case 'txt': - return $this->displayTxt($io, $files); - case 'json': - return $this->displayJson($io, $files); - case 'github': - return $this->displayTxt($io, $files, true); - default: - throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format)); - } + return match ($this->format) { + 'txt' => $this->displayTxt($io, $files), + 'json' => $this->displayJson($io, $files), + 'github' => $this->displayTxt($io, $files, true), + default => throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $this->format)), + }; } private function displayTxt(SymfonyStyle $io, array $filesInfo, bool $errorAsGithubAnnotations = false): int diff --git a/src/Symfony/Component/Yaml/Parser.php b/src/Symfony/Component/Yaml/Parser.php index 18bfed0f15436..9e70ae828f56f 100644 --- a/src/Symfony/Component/Yaml/Parser.php +++ b/src/Symfony/Component/Yaml/Parser.php @@ -1043,25 +1043,14 @@ private function isStringUnIndentedCollectionItem(): bool 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()) { - case \PREG_INTERNAL_ERROR: - $error = 'Internal PCRE error.'; - break; - case \PREG_BACKTRACK_LIMIT_ERROR: - $error = 'pcre.backtrack_limit reached.'; - break; - case \PREG_RECURSION_LIMIT_ERROR: - $error = 'pcre.recursion_limit reached.'; - break; - case \PREG_BAD_UTF8_ERROR: - $error = 'Malformed UTF-8 data.'; - break; - case \PREG_BAD_UTF8_OFFSET_ERROR: - $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.'; - break; - default: - $error = 'Error.'; - } + $error = match (preg_last_error()) { + \PREG_INTERNAL_ERROR => 'Internal PCRE error.', + \PREG_BACKTRACK_LIMIT_ERROR => 'pcre.backtrack_limit reached.', + \PREG_RECURSION_LIMIT_ERROR => 'pcre.recursion_limit reached.', + \PREG_BAD_UTF8_ERROR => 'Malformed UTF-8 data.', + \PREG_BAD_UTF8_OFFSET_ERROR => 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.', + default => 'Error.', + }; throw new ParseException($error); } diff --git a/src/Symfony/Component/Yaml/Unescaper.php b/src/Symfony/Component/Yaml/Unescaper.php index d1ef041233f5a..2238210d93dfe 100644 --- a/src/Symfony/Component/Yaml/Unescaper.php +++ b/src/Symfony/Component/Yaml/Unescaper.php @@ -60,56 +60,34 @@ public function unescapeDoubleQuotedString(string $value): string */ private function unescapeCharacter(string $value): string { - switch ($value[1]) { - case '0': - return "\x0"; - case 'a': - return "\x7"; - case 'b': - return "\x8"; - case 't': - return "\t"; - case "\t": - return "\t"; - case 'n': - return "\n"; - case 'v': - return "\xB"; - case 'f': - return "\xC"; - case 'r': - return "\r"; - case 'e': - return "\x1B"; - case ' ': - return ' '; - case '"': - return '"'; - case '/': - return '/'; - case '\\': - return '\\'; - case 'N': - // U+0085 NEXT LINE - return "\xC2\x85"; - case '_': - // U+00A0 NO-BREAK SPACE - return "\xC2\xA0"; - case 'L': - // U+2028 LINE SEPARATOR - return "\xE2\x80\xA8"; - case 'P': - // U+2029 PARAGRAPH SEPARATOR - return "\xE2\x80\xA9"; - case 'x': - return self::utf8chr(hexdec(substr($value, 2, 2))); - case 'u': - return self::utf8chr(hexdec(substr($value, 2, 4))); - case 'U': - return self::utf8chr(hexdec(substr($value, 2, 8))); - default: - throw new ParseException(sprintf('Found unknown escape character "%s".', $value)); - } + return match ($value[1]) { + '0' => "\x0", + 'a' => "\x7", + 'b' => "\x8", + 't' => "\t", + "\t" => "\t", + 'n' => "\n", + 'v' => "\xB", + 'f' => "\xC", + 'r' => "\r", + 'e' => "\x1B", + ' ' => ' ', + '"' => '"', + '/' => '/', + '\\' => '\\', + // U+0085 NEXT LINE + 'N' => "\xC2\x85", + // U+00A0 NO-BREAK SPACE + '_' => "\xC2\xA0", + // U+2028 LINE SEPARATOR + 'L' => "\xE2\x80\xA8", + // U+2029 PARAGRAPH SEPARATOR + 'P' => "\xE2\x80\xA9", + 'x' => self::utf8chr(hexdec(substr($value, 2, 2))), + 'u' => self::utf8chr(hexdec(substr($value, 2, 4))), + 'U' => self::utf8chr(hexdec(substr($value, 2, 8))), + default => throw new ParseException(sprintf('Found unknown escape character "%s".', $value)), + }; } /** diff --git a/src/Symfony/Contracts/Translation/TranslatorTrait.php b/src/Symfony/Contracts/Translation/TranslatorTrait.php index 9c264bd293f5d..99a639ce69ff3 100644 --- a/src/Symfony/Contracts/Translation/TranslatorTrait.php +++ b/src/Symfony/Contracts/Translation/TranslatorTrait.php @@ -140,121 +140,92 @@ private function getPluralizationRule(float $number, string $locale): int { $number = abs($number); - switch ('pt_BR' !== $locale && 'en_US_POSIX' !== $locale && \strlen($locale) > 3 ? substr($locale, 0, strrpos($locale, '_')) : $locale) { - case 'af': - case 'bn': - case 'bg': - case 'ca': - case 'da': - case 'de': - case 'el': - case 'en': - case 'en_US_POSIX': - case 'eo': - case 'es': - case 'et': - case 'eu': - case 'fa': - case 'fi': - case 'fo': - case 'fur': - case 'fy': - case 'gl': - case 'gu': - case 'ha': - case 'he': - case 'hu': - case 'is': - case 'it': - case 'ku': - case 'lb': - case 'ml': - case 'mn': - case 'mr': - case 'nah': - case 'nb': - case 'ne': - case 'nl': - case 'nn': - case 'no': - case 'oc': - case 'om': - case 'or': - case 'pa': - case 'pap': - case 'ps': - case 'pt': - case 'so': - case 'sq': - case 'sv': - case 'sw': - case 'ta': - case 'te': - case 'tk': - case 'ur': - case 'zu': - return (1 == $number) ? 0 : 1; - - case 'am': - case 'bh': - case 'fil': - case 'fr': - case 'gun': - case 'hi': - case 'hy': - case 'ln': - case 'mg': - case 'nso': - case 'pt_BR': - case 'ti': - case 'wa': - return ($number < 2) ? 0 : 1; - - case 'be': - case 'bs': - case 'hr': - case 'ru': - case 'sh': - case 'sr': - case 'uk': - return ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); - - case 'cs': - case 'sk': - return (1 == $number) ? 0 : ((($number >= 2) && ($number <= 4)) ? 1 : 2); - - case 'ga': - return (1 == $number) ? 0 : ((2 == $number) ? 1 : 2); - - case 'lt': - return ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2); - - case 'sl': - return (1 == $number % 100) ? 0 : ((2 == $number % 100) ? 1 : (((3 == $number % 100) || (4 == $number % 100)) ? 2 : 3)); - - case 'mk': - return (1 == $number % 10) ? 0 : 1; - - case 'mt': - return (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 1) && ($number % 100 < 11))) ? 1 : ((($number % 100 > 10) && ($number % 100 < 20)) ? 2 : 3)); - - case 'lv': - return (0 == $number) ? 0 : (((1 == $number % 10) && (11 != $number % 100)) ? 1 : 2); - - case 'pl': - return (1 == $number) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 12) || ($number % 100 > 14))) ? 1 : 2); - - case 'cy': - return (1 == $number) ? 0 : ((2 == $number) ? 1 : (((8 == $number) || (11 == $number)) ? 2 : 3)); - - case 'ro': - return (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 0) && ($number % 100 < 20))) ? 1 : 2); - - case 'ar': - return (0 == $number) ? 0 : ((1 == $number) ? 1 : ((2 == $number) ? 2 : ((($number % 100 >= 3) && ($number % 100 <= 10)) ? 3 : ((($number % 100 >= 11) && ($number % 100 <= 99)) ? 4 : 5)))); - - default: - return 0; - } + return match ('pt_BR' !== $locale && 'en_US_POSIX' !== $locale && \strlen($locale) > 3 ? substr($locale, 0, strrpos($locale, '_')) : $locale) { + 'af', + 'bn', + 'bg', + 'ca', + 'da', + 'de', + 'el', + 'en', + 'en_US_POSIX', + 'eo', + 'es', + 'et', + 'eu', + 'fa', + 'fi', + 'fo', + 'fur', + 'fy', + 'gl', + 'gu', + 'ha', + 'he', + 'hu', + 'is', + 'it', + 'ku', + 'lb', + 'ml', + 'mn', + 'mr', + 'nah', + 'nb', + 'ne', + 'nl', + 'nn', + 'no', + 'oc', + 'om', + 'or', + 'pa', + 'pap', + 'ps', + 'pt', + 'so', + 'sq', + 'sv', + 'sw', + 'ta', + 'te', + 'tk', + 'ur', + 'zu' => (1 == $number) ? 0 : 1, + 'am', + 'bh', + 'fil', + 'fr', + 'gun', + 'hi', + 'hy', + 'ln', + 'mg', + 'nso', + 'pt_BR', + 'ti', + 'wa' => ($number < 2) ? 0 : 1, + 'be', + 'bs', + 'hr', + 'ru', + 'sh', + 'sr', + 'uk' => ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2), + 'cs', + 'sk' => (1 == $number) ? 0 : ((($number >= 2) && ($number <= 4)) ? 1 : 2), + 'ga' => (1 == $number) ? 0 : ((2 == $number) ? 1 : 2), + 'lt' => ((1 == $number % 10) && (11 != $number % 100)) ? 0 : ((($number % 10 >= 2) && (($number % 100 < 10) || ($number % 100 >= 20))) ? 1 : 2), + 'sl' => (1 == $number % 100) ? 0 : ((2 == $number % 100) ? 1 : (((3 == $number % 100) || (4 == $number % 100)) ? 2 : 3)), + 'mk' => (1 == $number % 10) ? 0 : 1, + 'mt' => (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 1) && ($number % 100 < 11))) ? 1 : ((($number % 100 > 10) && ($number % 100 < 20)) ? 2 : 3)), + 'lv' => (0 == $number) ? 0 : (((1 == $number % 10) && (11 != $number % 100)) ? 1 : 2), + 'pl' => (1 == $number) ? 0 : ((($number % 10 >= 2) && ($number % 10 <= 4) && (($number % 100 < 12) || ($number % 100 > 14))) ? 1 : 2), + 'cy' => (1 == $number) ? 0 : ((2 == $number) ? 1 : (((8 == $number) || (11 == $number)) ? 2 : 3)), + 'ro' => (1 == $number) ? 0 : (((0 == $number) || (($number % 100 > 0) && ($number % 100 < 20))) ? 1 : 2), + 'ar' => (0 == $number) ? 0 : ((1 == $number) ? 1 : ((2 == $number) ? 2 : ((($number % 100 >= 3) && ($number % 100 <= 10)) ? 3 : ((($number % 100 >= 11) && ($number % 100 <= 99)) ? 4 : 5)))), + default => 0, + }; } }