Skip to content

Convert switch cases to match expression #47654

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 5 additions & 10 deletions src/Symfony/Bridge/Twig/Command/DebugCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,16 +101,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int
throw new InvalidArgumentException(sprintf('Argument "name" not supported, it requires the Twig loader "%s".', FilesystemLoader::class));
}

switch ($input->getOption('format')) {
case 'text':
$name ? $this->displayPathsText($io, $name) : $this->displayGeneralText($io, $filter);
break;
case 'json':
$name ? $this->displayPathsJson($io, $name) : $this->displayGeneralJson($io, $filter);
break;
default:
throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $input->getOption('format')));
}
match ($input->getOption('format')) {
'text' => $name ? $this->displayPathsText($io, $name) : $this->displayGeneralText($io, $filter),
'json' => $name ? $this->displayPathsJson($io, $name) : $this->displayGeneralJson($io, $filter),
default => throw new InvalidArgumentException(sprintf('The format "%s" is not supported.', $input->getOption('format'))),
};

return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,49 +46,22 @@ public function describe(OutputInterface $output, mixed $object, array $options
(new AnalyzeServiceReferencesPass(false, false))->process($object);
}

switch (true) {
case $object instanceof RouteCollection:
$this->describeRouteCollection($object, $options);
break;
case $object instanceof Route:
$this->describeRoute($object, $options);
break;
case $object instanceof ParameterBag:
$this->describeContainerParameters($object, $options);
break;
case $object instanceof ContainerBuilder && !empty($options['env-vars']):
$this->describeContainerEnvVars($this->getContainerEnvVars($object), $options);
break;
case $object instanceof ContainerBuilder && isset($options['group_by']) && 'tags' === $options['group_by']:
$this->describeContainerTags($object, $options);
break;
case $object instanceof ContainerBuilder && isset($options['id']):
$this->describeContainerService($this->resolveServiceDefinition($object, $options['id']), $options, $object);
break;
case $object instanceof ContainerBuilder && isset($options['parameter']):
$this->describeContainerParameter($object->resolveEnvPlaceholders($object->getParameter($options['parameter'])), $options);
break;
case $object instanceof ContainerBuilder && isset($options['deprecations']):
$this->describeContainerDeprecations($object, $options);
break;
case $object instanceof ContainerBuilder:
$this->describeContainerServices($object, $options);
break;
case $object instanceof Definition:
$this->describeContainerDefinition($object, $options);
break;
case $object instanceof Alias:
$this->describeContainerAlias($object, $options);
break;
case $object instanceof EventDispatcherInterface:
$this->describeEventDispatcherListeners($object, $options);
break;
case \is_callable($object):
$this->describeCallable($object, $options);
break;
default:
throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object)));
}
match (true) {
$object instanceof RouteCollection => $this->describeRouteCollection($object, $options),
$object instanceof Route => $this->describeRoute($object, $options),
$object instanceof ParameterBag => $this->describeContainerParameters($object, $options),
$object instanceof ContainerBuilder && !empty($options['env-vars']) => $this->describeContainerEnvVars($this->getContainerEnvVars($object), $options),
$object instanceof ContainerBuilder && isset($options['group_by']) && 'tags' === $options['group_by'] => $this->describeContainerTags($object, $options),
$object instanceof ContainerBuilder && isset($options['id']) => $this->describeContainerService($this->resolveServiceDefinition($object, $options['id']), $options, $object),
$object instanceof ContainerBuilder && isset($options['parameter']) => $this->describeContainerParameter($object->resolveEnvPlaceholders($object->getParameter($options['parameter'])), $options),
$object instanceof ContainerBuilder && isset($options['deprecations']) => $this->describeContainerDeprecations($object, $options),
$object instanceof ContainerBuilder => $this->describeContainerServices($object, $options),
$object instanceof Definition => $this->describeContainerDefinition($object, $options),
$object instanceof Alias => $this->describeContainerAlias($object, $options),
$object instanceof EventDispatcherInterface => $this->describeEventDispatcherListeners($object, $options),
\is_callable($object) => $this->describeCallable($object, $options),
default => throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))),
};

if ($object instanceof ContainerBuilder) {
$object->getCompiler()->getServiceReferenceGraph()->clear();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2268,26 +2268,14 @@ private function assertCachePoolServiceDefinitionIsCreated(ContainerBuilder $con
$parentDefinition = $container->findDefinition($parentId);
} while ($parentDefinition instanceof ChildDefinition);

switch ($adapter) {
case 'cache.adapter.apcu':
$this->assertSame(ApcuAdapter::class, $parentDefinition->getClass());
break;
case 'cache.app':
case 'cache.adapter.filesystem':
$this->assertSame(FilesystemAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.psr6':
$this->assertSame(ProxyAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.redis':
$this->assertSame(RedisAdapter::class, $parentDefinition->getClass());
break;
case 'cache.adapter.array':
$this->assertSame(ArrayAdapter::class, $parentDefinition->getClass());
break;
default:
$this->fail('Unresolved adapter: '.$adapter);
}
match ($adapter) {
'cache.adapter.apcu' => $this->assertSame(ApcuAdapter::class, $parentDefinition->getClass()),
'cache.app', 'cache.adapter.filesystem' => $this->assertSame(FilesystemAdapter::class, $parentDefinition->getClass()),
'cache.adapter.psr6' => $this->assertSame(ProxyAdapter::class, $parentDefinition->getClass()),
'cache.adapter.redis' => $this->assertSame(RedisAdapter::class, $parentDefinition->getClass()),
'cache.adapter.array' => $this->assertSame(ArrayAdapter::class, $parentDefinition->getClass()),
default => $this->fail('Unresolved adapter: '.$adapter),
};
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,18 +179,13 @@ public function load(array $configs, ContainerBuilder $container)
*/
private function createStrategyDefinition(string $strategy, bool $allowIfAllAbstainDecisions, bool $allowIfEqualGrantedDeniedDecisions): Definition
{
switch ($strategy) {
case MainConfiguration::STRATEGY_AFFIRMATIVE:
return new Definition(AffirmativeStrategy::class, [$allowIfAllAbstainDecisions]);
case MainConfiguration::STRATEGY_CONSENSUS:
return new Definition(ConsensusStrategy::class, [$allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions]);
case MainConfiguration::STRATEGY_UNANIMOUS:
return new Definition(UnanimousStrategy::class, [$allowIfAllAbstainDecisions]);
case MainConfiguration::STRATEGY_PRIORITY:
return new Definition(PriorityStrategy::class, [$allowIfAllAbstainDecisions]);
}

throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $strategy));
return match ($strategy) {
MainConfiguration::STRATEGY_AFFIRMATIVE => new Definition(AffirmativeStrategy::class, [$allowIfAllAbstainDecisions]),
MainConfiguration::STRATEGY_CONSENSUS => new Definition(ConsensusStrategy::class, [$allowIfAllAbstainDecisions, $allowIfEqualGrantedDeniedDecisions]),
MainConfiguration::STRATEGY_UNANIMOUS => new Definition(UnanimousStrategy::class, [$allowIfAllAbstainDecisions]),
MainConfiguration::STRATEGY_PRIORITY => new Definition(PriorityStrategy::class, [$allowIfAllAbstainDecisions]),
default => throw new \InvalidArgumentException(sprintf('The strategy "%s" is not supported.', $strategy)),
};
}

private function createRoleHierarchy(array $config, ContainerBuilder $container)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,9 @@ public function __construct()

public function getUserIdentifierFrom(string $accessToken): string
{
switch ($accessToken) {
case 'VALID_ACCESS_TOKEN':
return 'dunglas';
default:
throw new BadCredentialsException('Invalid credentials.');
}
return match ($accessToken) {
'VALID_ACCESS_TOKEN' => 'dunglas',
default => throw new BadCredentialsException('Invalid credentials.'),
};
}
}
23 changes: 7 additions & 16 deletions src/Symfony/Component/Config/Builder/ConfigBuilderGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,22 +109,13 @@ private function buildNode(NodeInterface $node, ClassBuilder $class, string $nam
}

foreach ($node->getChildren() as $child) {
switch (true) {
case $child instanceof ScalarNode:
$this->handleScalarNode($child, $class);
break;
case $child instanceof PrototypedArrayNode:
$this->handlePrototypedArrayNode($child, $class, $namespace);
break;
case $child instanceof VariableNode:
$this->handleVariableNode($child, $class);
break;
case $child instanceof ArrayNode:
$this->handleArrayNode($child, $class, $namespace);
break;
default:
throw new \RuntimeException(sprintf('Unknown node "%s".', $child::class));
}
match (true) {
$child instanceof ScalarNode => $this->handleScalarNode($child, $class),
$child instanceof PrototypedArrayNode => $this->handlePrototypedArrayNode($child, $class, $namespace),
$child instanceof VariableNode => $this->handleVariableNode($child, $class),
$child instanceof ArrayNode => $this->handleArrayNode($child, $class, $namespace),
default => throw new \RuntimeException(sprintf('Unknown node "%s".', $child::class)),
};
}
}

Expand Down
27 changes: 8 additions & 19 deletions src/Symfony/Component/Console/Descriptor/Descriptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,14 @@ public function describe(OutputInterface $output, object $object, array $options
{
$this->output = $output;

switch (true) {
case $object instanceof InputArgument:
$this->describeInputArgument($object, $options);
break;
case $object instanceof InputOption:
$this->describeInputOption($object, $options);
break;
case $object instanceof InputDefinition:
$this->describeInputDefinition($object, $options);
break;
case $object instanceof Command:
$this->describeCommand($object, $options);
break;
case $object instanceof Application:
$this->describeApplication($object, $options);
break;
default:
throw new InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object)));
}
match (true) {
$object instanceof InputArgument => $this->describeInputArgument($object, $options),
$object instanceof InputOption => $this->describeInputOption($object, $options),
$object instanceof InputDefinition => $this->describeInputDefinition($object, $options),
$object instanceof Command => $this->describeCommand($object, $options),
$object instanceof Application => $this->describeApplication($object, $options),
default => throw new InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))),
};
}

/**
Expand Down
19 changes: 6 additions & 13 deletions src/Symfony/Component/Form/Console/Descriptor/Descriptor.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,19 +44,12 @@ public function describe(OutputInterface $output, ?object $object, array $option
{
$this->output = $output instanceof OutputStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output);

switch (true) {
case null === $object:
$this->describeDefaults($options);
break;
case $object instanceof ResolvedFormTypeInterface:
$this->describeResolvedFormType($object, $options);
break;
case $object instanceof OptionsResolver:
$this->describeOption($object, $options);
break;
default:
throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object)));
}
match (true) {
null === $object => $this->describeDefaults($options),
$object instanceof ResolvedFormTypeInterface => $this->describeResolvedFormType($object, $options),
$object instanceof OptionsResolver => $this->describeOption($object, $options),
default => throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_debug_type($object))),
};
}

abstract protected function describeDefaults(array $options);
Expand Down
20 changes: 6 additions & 14 deletions src/Symfony/Component/Notifier/Bridge/Mobyt/MobytOptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,20 +38,12 @@ public function __construct(array $options = [])
public static function fromNotification(Notification $notification): self
{
$options = new self();
switch ($notification->getImportance()) {
case Notification::IMPORTANCE_HIGH:
case Notification::IMPORTANCE_URGENT:
$options->messageType(self::MESSAGE_TYPE_QUALITY_HIGH);
break;
case Notification::IMPORTANCE_MEDIUM:
$options->messageType(self::MESSAGE_TYPE_QUALITY_MEDIUM);
break;
case Notification::IMPORTANCE_LOW:
$options->messageType(self::MESSAGE_TYPE_QUALITY_LOW);
break;
default:
$options->messageType(self::MESSAGE_TYPE_QUALITY_HIGH);
}
match ($notification->getImportance()) {
Notification::IMPORTANCE_HIGH, Notification::IMPORTANCE_URGENT => $options->messageType(self::MESSAGE_TYPE_QUALITY_HIGH),
Notification::IMPORTANCE_MEDIUM => $options->messageType(self::MESSAGE_TYPE_QUALITY_MEDIUM),
Notification::IMPORTANCE_LOW => $options->messageType(self::MESSAGE_TYPE_QUALITY_LOW),
default => $options->messageType(self::MESSAGE_TYPE_QUALITY_HIGH),
};

return $options;
}
Expand Down
19 changes: 7 additions & 12 deletions src/Symfony/Component/Serializer/Normalizer/UidNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,18 +46,13 @@ public function __construct(array $defaultContext = [])
*/
public function normalize(mixed $object, string $format = null, array $context = []): array|string|int|float|bool|\ArrayObject|null
{
switch ($context[self::NORMALIZATION_FORMAT_KEY] ?? $this->defaultContext[self::NORMALIZATION_FORMAT_KEY]) {
case self::NORMALIZATION_FORMAT_CANONICAL:
return (string) $object;
case self::NORMALIZATION_FORMAT_BASE58:
return $object->toBase58();
case self::NORMALIZATION_FORMAT_BASE32:
return $object->toBase32();
case self::NORMALIZATION_FORMAT_RFC4122:
return $object->toRfc4122();
}

throw new LogicException(sprintf('The "%s" format is not valid.', $context[self::NORMALIZATION_FORMAT_KEY] ?? $this->defaultContext[self::NORMALIZATION_FORMAT_KEY]));
return match ($context[self::NORMALIZATION_FORMAT_KEY] ?? $this->defaultContext[self::NORMALIZATION_FORMAT_KEY]) {
self::NORMALIZATION_FORMAT_CANONICAL => (string) $object,
self::NORMALIZATION_FORMAT_BASE58 => $object->toBase58(),
self::NORMALIZATION_FORMAT_BASE32 => $object->toBase32(),
self::NORMALIZATION_FORMAT_RFC4122 => $object->toRfc4122(),
default => throw new LogicException(sprintf('The "%s" format is not valid.', $context[self::NORMALIZATION_FORMAT_KEY] ?? $this->defaultContext[self::NORMALIZATION_FORMAT_KEY])),
};
}

public function supportsNormalization(mixed $data, string $format = null, array $context = []): bool
Expand Down