Skip to content

Leverage first-class callable syntax on array methods using string syntax callback #49043

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

Closed
wants to merge 1 commit into from
Closed
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
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public function getConnections()

public function getQueryCount()
{
return array_sum(array_map('count', $this->data['queries']));
return array_sum(array_map(count(...), $this->data['queries']));
}

public function getQueries()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,7 @@ public function testChoicesForValuesOptimization()
$field->submit(1);

$unitOfWorkIdentityMap = $this->em->getUnitOfWork()->getIdentityMap();
$managedEntitiesNames = array_map('strval', $unitOfWorkIdentityMap['Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity']);
$managedEntitiesNames = array_map(strval(...), $unitOfWorkIdentityMap['Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity']);

$this->assertContains((string) $entity1, $managedEntitiesNames);
$this->assertNotContains((string) $entity2, $managedEntitiesNames);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
}

uasort($serviceIds, 'strnatcmp');
uasort($serviceIds, strnatcmp(...));

$io->title('Autowirable Types');
$io->text('The following classes & interfaces can be used as type-hints when autowiring:');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ private function extractMessages(string $locale, array $transPaths, string $pref

private function filterDuplicateTransPaths(array $transPaths): array
{
$transPaths = array_filter(array_map('realpath', $transPaths));
$transPaths = array_filter(array_map(realpath(...), $transPaths));

sort($transPaths);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public function getConfigTreeBuilder(): TreeBuilder
->fixXmlConfig('trusted_header')
->performNoDeepMerging()
->defaultValue(['x-forwarded-for', 'x-forwarded-port', 'x-forwarded-proto'])
->beforeNormalization()->ifString()->then(function ($v) { return $v ? array_map('trim', explode(',', $v)) : []; })->end()
->beforeNormalization()->ifString()->then(function ($v) { return $v ? array_map(trim(...), explode(',', $v)) : []; })->end()
->enumPrototype()
->values([
'forwarded',
Expand Down Expand Up @@ -1937,7 +1937,7 @@ private function addHttpClientRetrySection()
->arrayNode('methods')
->beforeNormalization()
->ifArray()
->then(fn ($v) => array_map('strtoupper', $v))
->then(fn ($v) => array_map(strtoupper(...), $v))
->end()
->prototype('scalar')->end()
->info('A list of HTTP methods that triggers a retry for this status code. When empty, all methods are retried')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1132,7 +1132,7 @@ private function registerRouterConfiguration(array $config, ContainerBuilder $co
}

if ($enabledLocales) {
$enabledLocales = implode('|', array_map('preg_quote', $enabledLocales));
$enabledLocales = implode('|', array_map(preg_quote(...), $enabledLocales));
$container->getDefinition('routing.loader')->replaceArgument(2, ['_locale' => $enabledLocales]);
}

Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bundle/FrameworkBundle/Secrets/SodiumVault.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public function seal(string $name, string $value): void

$list = $this->list();
$list[$name] = null;
uksort($list, 'strnatcmp');
uksort($list, strnatcmp(...));
file_put_contents($this->pathPrefix.'list.php', sprintf("<?php\n\nreturn %s;\n", VarExporter::export($list)), \LOCK_EX);

$this->lastMessage = sprintf('Secret "%s" encrypted in "%s"; you can commit it.', $name, $this->getPrettyPath(\dirname($this->pathPrefix).\DIRECTORY_SEPARATOR));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1093,7 +1093,7 @@ public function testTranslator()
$this->assertArrayHasKey('cache_dir', $options);
$this->assertSame($container->getParameter('kernel.cache_dir').'/translations', $options['cache_dir']);

$files = array_map('realpath', $options['resource_files']['en']);
$files = array_map(realpath(...), $options['resource_files']['en']);
$ref = new \ReflectionClass(Validation::class);
$this->assertContains(
strtr(\dirname($ref->getFileName()).'/Resources/translations/validators.en.xlf', '/', \DIRECTORY_SEPARATOR),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ public function testCacheValidityWithContainerParameters($parameter)
$this->assertTrue($cache->isFresh());
} finally {
if (is_dir($cacheDir)) {
array_map('unlink', glob($cacheDir.\DIRECTORY_SEPARATOR.'*'));
array_map(unlink(...), glob($cacheDir.\DIRECTORY_SEPARATOR.'*'));
rmdir($cacheDir);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -924,7 +924,7 @@ private function createExpression(ContainerBuilder $container, string $expressio
private function createRequestMatcher(ContainerBuilder $container, string $path = null, string $host = null, int $port = null, array $methods = [], array $ips = null, array $attributes = []): Reference
{
if ($methods) {
$methods = array_map('strtoupper', $methods);
$methods = array_map(strtoupper(...), $methods);
}

if ($ips) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ public function testFirewalls()
foreach (array_keys($arguments[1]->getValues()) as $contextId) {
$contextDef = $container->getDefinition($contextId);
$arguments = $contextDef->getArguments();
$listeners[] = array_map('strval', $arguments[0]->getValues());
$listeners[] = array_map(strval(...), $arguments[0]->getValues());

$configDef = $container->getDefinition((string) $arguments[3]);
$configs[] = array_values($configDef->getArguments());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ public function testConfigureCustomAuthenticator(array $firewall, array $expecte

$container->compile();

$this->assertEquals($expectedAuthenticators, array_map('strval', $container->getDefinition('security.authenticator.manager.main')->getArgument(0)));
$this->assertEquals($expectedAuthenticators, array_map(strval(...), $container->getDefinition('security.authenticator.manager.main')->getArgument(0)));
}

public function provideConfigureCustomAuthenticatorData()
Expand Down Expand Up @@ -844,7 +844,7 @@ public function testConfigureCustomFirewallListener()

/** @var IteratorArgument $listenersIteratorArgument */
$listenersIteratorArgument = $container->getDefinition('security.firewall.map.context.main')->getArgument(0);
$firewallListeners = array_map('strval', $listenersIteratorArgument->getValues());
$firewallListeners = array_map(strval(...), $listenersIteratorArgument->getValues());
$this->assertContains('custom_firewall_listener_id', $firewallListeners);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function __construct(MarshallerInterface $marshaller)

public function marshall(array $values, ?array &$failed): array
{
return array_map('gzdeflate', $this->marshaller->marshall($values, $failed));
return array_map(gzdeflate(...), $this->marshaller->marshall($values, $failed));
}

public function unmarshall(string $value): mixed
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Cache/Tests/LockRegistryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public function testFiles()
}
$lockFiles = LockRegistry::setFiles([]);
LockRegistry::setFiles($lockFiles);
$expected = array_map('realpath', glob(__DIR__.'/../Adapter/*'));
$expected = array_map(realpath(...), glob(__DIR__.'/../Adapter/*'));
$this->assertSame($expected, $lockFiles);
}
}
4 changes: 2 additions & 2 deletions src/Symfony/Component/Cache/Tests/Traits/RedisProxiesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public function testRedis5Proxy($class)
EOPHP;
}

uksort($methods, 'strnatcmp');
uksort($methods, strnatcmp(...));
$proxy .= implode('', $methods)."}\n";

$this->assertStringEqualsFile(\dirname(__DIR__, 2)."/Traits/{$class}5Proxy.php", $proxy);
Expand Down Expand Up @@ -80,7 +80,7 @@ public function testRedis6Proxy($class, $stub)
EOPHP;
}

uksort($methods, 'strnatcmp');
uksort($methods, strnatcmp(...));
$proxy .= implode('', $methods)."}\n";

$this->assertStringEqualsFile(\dirname(__DIR__, 2)."/Traits/{$class}6Proxy.php", $proxy);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private function writeNode(NodeInterface $node, int $depth = 0, bool $root = fal
FloatNode::class,
IntegerNode::class => 'numeric value',
BooleanNode::class => 'true|false',
EnumNode::class => implode('|', array_unique(array_map('json_encode', $prototype->getValues()))),
EnumNode::class => implode('|', array_unique(array_map(json_encode(...), $prototype->getValues()))),
default => 'value',
};
}
Expand Down Expand Up @@ -149,7 +149,7 @@ private function writeNode(NodeInterface $node, int $depth = 0, bool $root = fal
}

if ($child instanceof EnumNode) {
$comments[] = 'One of '.implode('; ', array_unique(array_map('json_encode', $child->getValues())));
$comments[] = 'One of '.implode('; ', array_unique(array_map(json_encode(...), $child->getValues())));
}

if (\count($comments)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ private function writeNode(NodeInterface $node, NodeInterface $parentNode = null
}
}
} elseif ($node instanceof EnumNode) {
$comments[] = 'One of '.implode('; ', array_unique(array_map('json_encode', $node->getValues())));
$comments[] = 'One of '.implode('; ', array_unique(array_map(json_encode(...), $node->getValues())));
$default = $node->hasDefaultValue() ? Inline::dump($node->getDefaultValue()) : '~';
} elseif (VariableNode::class === $node::class && \is_array($example)) {
// If there is an array example, we are sure we dont need to print a default value
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Config/Definition/EnumNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ protected function finalizeValue(mixed $value): mixed
$value = parent::finalizeValue($value);

if (!\in_array($value, $this->values, true)) {
$ex = new InvalidConfigurationException(sprintf('The value %s is not allowed for path "%s". Permissible values: %s', json_encode($value), $this->getPath(), implode(', ', array_map('json_encode', $this->values))));
$ex = new InvalidConfigurationException(sprintf('The value %s is not allowed for path "%s". Permissible values: %s', json_encode($value), $this->getPath(), implode(', ', array_map(json_encode(...), $this->values))));
$ex->setPath($this->getPath());

throw $ex;
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Config/Resource/GlobResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ public function getIterator(): \Traversable
),
\RecursiveIteratorIterator::LEAVES_ONLY
));
uksort($files, 'strnatcmp');
uksort($files, strnatcmp(...));

foreach ($files as $path => $info) {
if ($info->isFile()) {
Expand Down
4 changes: 2 additions & 2 deletions src/Symfony/Component/Console/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -613,7 +613,7 @@ public function getNamespaces(): array
public function findNamespace(string $namespace): string
{
$allNamespaces = $this->getNamespaces();
$expr = implode('[^:]*:', array_map('preg_quote', explode(':', $namespace))).'[^:]*';
$expr = implode('[^:]*:', array_map(preg_quote(...), explode(':', $namespace))).'[^:]*';
$namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);

if (empty($namespaces)) {
Expand Down Expand Up @@ -669,7 +669,7 @@ public function find(string $name)
}

$allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
$expr = implode('[^:]*:', array_map('preg_quote', explode(':', $name))).'[^:]*';
$expr = implode('[^:]*:', array_map(preg_quote(...), explode(':', $name))).'[^:]*';
$commands = preg_grep('{^'.$expr.'}', $allCommands);

if (empty($commands)) {
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Console/Question/Question.php
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ public function getNormalizer(): ?callable

protected function isAssoc(array $array)
{
return (bool) \count(array_filter(array_keys($array), 'is_string'));
return (bool) \count(array_filter(array_keys($array), is_string(...)));
}

public function isTrimmable(): bool
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,6 @@ public function complete(array $input): array
$options[] = '--'.$option->getName();
}

return array_map('strval', array_merge($options, $suggestions->getValueSuggestions()));
return array_map(strval(...), array_merge($options, $suggestions->getValueSuggestions()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ private function createTypeAlternatives(ContainerBuilder $container, TypedRefere
return sprintf(' Available autowiring aliases for this %s are: "$%s".', class_exists($type, false) ? 'class' : 'interface', implode('", "$', $autowiringAliases));
}

if (!$container->has($type) && false !== $key = array_search(strtolower($type), array_map('strtolower', $servicesAndAliases))) {
if (!$container->has($type) && false !== $key = array_search(strtolower($type), array_map(strtolower(...), $servicesAndAliases))) {
return sprintf(' Did you mean "%s"?', $servicesAndAliases[$key]);
} elseif (isset($this->ambiguousServiceTypes[$type])) {
$message = sprintf('one of these existing services: "%s"', implode('", "', $this->ambiguousServiceTypes[$type]));
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/DependencyInjection/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ public function reset()
*/
public function getServiceIds(): array
{
return array_map('strval', array_unique(array_merge(['service_container'], array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->aliases), array_keys($this->services))));
return array_map(strval(...), array_unique(array_merge(['service_container'], array_keys($this->fileMap), array_keys($this->methodMap), array_keys($this->aliases), array_keys($this->services))));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -775,7 +775,7 @@ public function compile(bool $resolveEnvPlaceholders = false)

public function getServiceIds(): array
{
return array_map('strval', array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds())));
return array_map(strval(...), array_unique(array_merge(array_keys($this->getDefinitions()), array_keys($this->aliasDefinitions), parent::getServiceIds())));
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -449,7 +449,7 @@ private function processAnonymousServices(\DOMDocument $xml, string $file, \DOMN
}

// resolve definitions
uksort($definitions, 'strnatcmp');
uksort($definitions, strnatcmp(...));
foreach (array_reverse($definitions) as $id => [$domElement, $file]) {
if (null !== $definition = $this->parseDefinition($domElement, $file, new Definition())) {
$this->setDefinition($id, $definition);
Expand Down Expand Up @@ -668,7 +668,7 @@ public function validateSchema(\DOMDocument $dom): bool
$locationstart = '';
}
$drive = '\\' === \DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
$location = $locationstart.$drive.implode('/', array_map('rawurlencode', $parts));
$location = $locationstart.$drive.implode('/', array_map(rawurlencode(...), $parts));

$imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ public function get(string $name): array|bool|string|int|float|\UnitEnum|null

$nonNestedAlternative = null;
if (!\count($alternatives) && str_contains($name, '.')) {
$namePartsLength = array_map('strlen', explode('.', $name));
$namePartsLength = array_map(strlen(...), explode('.', $name));
$key = substr($name, 0, -1 * (1 + array_pop($namePartsLength)));
while (\count($namePartsLength)) {
if ($this->has($key)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@ public function testPrototype()
sort($ids);
$this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids);

$resources = array_map('strval', $container->getResources());
$resources = array_map(strval(...), $container->getResources());

$fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR;
$this->assertContains((string) new FileResource($fixturesDir.'xml'.\DIRECTORY_SEPARATOR.'services_prototype.xml'), $resources);
Expand Down Expand Up @@ -802,7 +802,7 @@ public function testPrototypeExcludeWithArray(string $fileName)
sort($ids);
$this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids);

$resources = array_map('strval', $container->getResources());
$resources = array_map(strval(...), $container->getResources());

$fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR;
$this->assertContains((string) new FileResource($fixturesDir.'xml'.\DIRECTORY_SEPARATOR.$fileName), $resources);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ public function testPrototype()
sort($ids);
$this->assertSame([Prototype\Foo::class, Prototype\Sub\Bar::class, 'service_container'], $ids);

$resources = array_map('strval', $container->getResources());
$resources = array_map(strval(...), $container->getResources());

$fixturesDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR;
$this->assertContains((string) new FileResource($fixturesDir.'yaml'.\DIRECTORY_SEPARATOR.'services_prototype.yml'), $resources);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function testEnhance(string $originalMessage, string $enhancedMessage, $a
// Unregister all autoloaders to ensure the custom provided
// autoloader is the only one to be used during the test run.
$autoloaders = spl_autoload_functions();
array_map('spl_autoload_unregister', $autoloaders);
array_map(spl_autoload_unregister(...), $autoloaders);
spl_autoload_register($autoloader);
}

Expand All @@ -62,7 +62,7 @@ public function testEnhance(string $originalMessage, string $enhancedMessage, $a
} finally {
if ($autoloader) {
spl_autoload_unregister($autoloader);
array_map('spl_autoload_register', $autoloaders);
array_map(spl_autoload_register(...), $autoloaders);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
}

$operators = ['not', '!', 'or', '||', '&&', 'and', '|', '^', '&', '==', '===', '!=', '!==', '<', '>', '>=', '<=', 'not in', 'in', '..', '+', '-', '~', '*', '/', '%', 'contains', 'starts with', 'ends with', 'matches', '**'];
$operators = array_combine($operators, array_map('strlen', $operators));
$operators = array_combine($operators, array_map(strlen(...), $operators));
arsort($operators);

$regex = [];
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Component/Finder/Tests/FinderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1138,7 +1138,7 @@ public function testGetIterator()

$finder = $this->buildFinder();
$a = iterator_to_array($finder->directories()->in(self::$tmpDir));
$a = array_values(array_map('strval', $a));
$a = array_values(array_map(strval(...), $a));
sort($a);
$this->assertEquals($expected, $a, 'implements the \IteratorAggregate interface');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public function getChoices(): array

public function getValues(): array
{
return array_map('strval', array_keys($this->choices));
return array_map(strval(...), array_keys($this->choices));
}

public function getStructuredValues(): array
Expand Down
Loading