Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Leverage arrow function syntax for closure #48793

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
Jan 13, 2023
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,12 @@ public function getEntitiesByIds(string $identifier, array $values): array

// Filter out non-integer values (e.g. ""). If we don't, some
// databases such as PostgreSQL fail.
$values = array_values(array_filter($values, function ($v) {
return (string) $v === (string) (int) $v || ctype_digit($v);
}));
$values = array_values(array_filter($values, fn ($v) => (string) $v === (string) (int) $v || ctype_digit($v)));
} elseif (\in_array($type, ['ulid', 'uuid', 'guid'])) {
$parameterType = Connection::PARAM_STR_ARRAY;

// Like above, but we just filter out empty strings.
$values = array_values(array_filter($values, function ($v) {
return '' !== (string) $v;
}));
$values = array_values(array_filter($values, fn ($v) => '' !== (string) $v));

// Convert values into right type
if (Type::hasType($type)) {
Expand Down
16 changes: 7 additions & 9 deletions src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,15 +193,13 @@ public function configureOptions(OptionsResolver $resolver)

// Set the "id_reader" option via the normalizer. This option is not
// supposed to be set by the user.
$idReaderNormalizer = function (Options $options) {
// The ID reader is a utility that is needed to read the object IDs
// when generating the field values. The callback generating the
// field values has no access to the object manager or the class
// of the field, so we store that information in the reader.
// The reader is cached so that two choice lists for the same class
// (and hence with the same reader) can successfully be cached.
return $this->getCachedIdReader($options['em'], $options['class']);
};
// The ID reader is a utility that is needed to read the object IDs
// when generating the field values. The callback generating the
// field values has no access to the object manager or the class
// of the field, so we store that information in the reader.
// The reader is cached so that two choice lists for the same class
// (and hence with the same reader) can successfully be cached.
$idReaderNormalizer = fn (Options $options) => $this->getCachedIdReader($options['em'], $options['class']);

$resolver->setDefaults([
'em' => null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ public function getProperties(string $class, array $context = []): ?array
$properties = array_merge($metadata->getFieldNames(), $metadata->getAssociationNames());

if ($metadata instanceof ClassMetadataInfo && class_exists(Embedded::class) && $metadata->embeddedClasses) {
$properties = array_filter($properties, function ($property) {
return !str_contains($property, '.');
});
$properties = array_filter($properties, fn ($property) => !str_contains($property, '.'));

$properties = array_merge($properties, array_keys($metadata->embeddedClasses));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,7 @@ protected function setUp(): void

$this->extension->expects($this->any())
->method('getObjectManagerElementName')
->willReturnCallback(function ($name) {
return 'doctrine.orm.'.$name;
});
->willReturnCallback(fn ($name) => 'doctrine.orm.'.$name);

$this->extension
->method('getMappingObjectDefaultName')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ public function testLoadValuesForChoicesDoesNotLoadIfSingleIntIdAndValueGiven()
);

$choices = [$this->obj1, $this->obj2, $this->obj3];
$value = function (\stdClass $object) { return $object->name; };
$value = fn (\stdClass $object) => $object->name;

$this->repository->expects($this->never())
->method('findAll')
Expand Down Expand Up @@ -367,7 +367,7 @@ public function testLoadChoicesForValuesLoadsAllIfSingleIntIdAndValueGiven()
);

$choices = [$this->obj1, $this->obj2, $this->obj3];
$value = function (\stdClass $object) { return $object->name; };
$value = fn (\stdClass $object) => $object->name;

$this->repository->expects($this->once())
->method('findAll')
Expand Down
36 changes: 10 additions & 26 deletions src/Symfony/Bridge/Doctrine/Tests/Form/Type/EntityTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,7 @@ public function testConfigureQueryBuilderWithClosureReturningNonQueryBuilder()
$field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'query_builder' => function () {
return new \stdClass();
},
'query_builder' => fn () => new \stdClass(),
]);

$field->submit('2');
Expand Down Expand Up @@ -1078,10 +1076,8 @@ public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureSingle
$field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'query_builder' => function (EntityRepository $repository) {
return $repository->createQueryBuilder('e')
->where('e.id IN (1, 2)');
},
'query_builder' => fn (EntityRepository $repository) => $repository->createQueryBuilder('e')
->where('e.id IN (1, 2)'),
'choice_label' => 'name',
]);

Expand All @@ -1102,10 +1098,8 @@ public function testDisallowChoicesThatAreNotIncludedQueryBuilderAsClosureCompos
$field = $this->factory->createNamed('name', static::TESTED_TYPE, null, [
'em' => 'default',
'class' => self::COMPOSITE_IDENT_CLASS,
'query_builder' => function (EntityRepository $repository) {
return $repository->createQueryBuilder('e')
->where('e.id1 IN (10, 50)');
},
'query_builder' => fn (EntityRepository $repository) => $repository->createQueryBuilder('e')
->where('e.id1 IN (10, 50)'),
'choice_label' => 'name',
]);

Expand Down Expand Up @@ -1220,17 +1214,13 @@ public function testLoaderCaching()
$formBuilder->add('property2', static::TESTED_TYPE, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'query_builder' => function (EntityRepository $repo) {
return $repo->createQueryBuilder('e')->where('e.id IN (1, 2)');
},
'query_builder' => fn (EntityRepository $repo) => $repo->createQueryBuilder('e')->where('e.id IN (1, 2)'),
]);

$formBuilder->add('property3', static::TESTED_TYPE, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'query_builder' => function (EntityRepository $repo) {
return $repo->createQueryBuilder('e')->where('e.id IN (1, 2)');
},
'query_builder' => fn (EntityRepository $repo) => $repo->createQueryBuilder('e')->where('e.id IN (1, 2)'),
]);

$form = $formBuilder->getForm();
Expand Down Expand Up @@ -1280,17 +1270,13 @@ public function testLoaderCachingWithParameters()
$formBuilder->add('property2', static::TESTED_TYPE, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'query_builder' => function (EntityRepository $repo) {
return $repo->createQueryBuilder('e')->where('e.id = :id')->setParameter('id', 1);
},
'query_builder' => fn (EntityRepository $repo) => $repo->createQueryBuilder('e')->where('e.id = :id')->setParameter('id', 1),
]);

$formBuilder->add('property3', static::TESTED_TYPE, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'query_builder' => function (EntityRepository $repo) {
return $repo->createQueryBuilder('e')->where('e.id = :id')->setParameter('id', 1);
},
'query_builder' => fn (EntityRepository $repo) => $repo->createQueryBuilder('e')->where('e.id = :id')->setParameter('id', 1),
]);

$form = $formBuilder->getForm();
Expand Down Expand Up @@ -1791,9 +1777,7 @@ public function testWithSameLoaderAndDifferentChoiceValueCallbacks()
->add('entity_two', self::TESTED_TYPE, [
'em' => 'default',
'class' => self::SINGLE_IDENT_CLASS,
'choice_value' => function ($choice) {
return $choice ? $choice->name : '';
},
'choice_value' => fn ($choice) => $choice ? $choice->name : '',
])
->createView()
;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function testPostGenerateSchemaPdo()
$pdoSessionHandler = $this->createMock(PdoSessionHandler::class);
$pdoSessionHandler->expects($this->once())
->method('configureSchema')
->with($schema, fn() => true);
->with($schema, fn () => true);

$subscriber = new PdoSessionHandlerSchemaSubscriber([$pdoSessionHandler]);
$subscriber->postGenerateSchema($event);
Expand Down
12 changes: 3 additions & 9 deletions src/Symfony/Bridge/Monolog/Tests/Handler/MailerHandlerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,7 @@ public function testHandle()
$this->mailer
->expects($this->once())
->method('send')
->with($this->callback(function (Email $email) {
return 'Alert: WARNING message' === $email->getSubject() && null === $email->getHtmlBody();
}))
->with($this->callback(fn (Email $email) => 'Alert: WARNING message' === $email->getSubject() && null === $email->getHtmlBody()))
;
$handler->handle($this->getRecord(Logger::WARNING, 'message'));
}
Expand All @@ -53,9 +51,7 @@ public function testHandleBatch()
$this->mailer
->expects($this->once())
->method('send')
->with($this->callback(function (Email $email) {
return 'Alert: ERROR error' === $email->getSubject() && null === $email->getHtmlBody();
}))
->with($this->callback(fn (Email $email) => 'Alert: ERROR error' === $email->getSubject() && null === $email->getHtmlBody()))
;
$handler->handleBatch($this->getMultipleRecords());
}
Expand Down Expand Up @@ -86,9 +82,7 @@ public function testHtmlContent()
$this->mailer
->expects($this->once())
->method('send')
->with($this->callback(function (Email $email) {
return 'Alert: WARNING message' === $email->getSubject() && null === $email->getTextBody();
}))
->with($this->callback(fn (Email $email) => 'Alert: WARNING message' === $email->getSubject() && null === $email->getTextBody()))
;
$handler->handle($this->getRecord(Logger::WARNING, 'message'));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,7 @@ public function testInstantiateProxy()
$instance = new \stdClass();
$container = $this->createMock(ContainerInterface::class);
$definition = new Definition('stdClass');
$instantiator = function () use ($instance) {
return $instance;
};
$instantiator = fn () => $instance;

/* @var $proxy LazyLoadingInterface|ValueHolderInterface */
$proxy = $this->instantiator->instantiateProxy($container, $definition, 'foo', $instantiator);
Expand Down
6 changes: 2 additions & 4 deletions src/Symfony/Bridge/Twig/Command/DebugCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,7 @@ private function displayPathsText(SymfonyStyle $io, string $name)
[$namespace, $shortname] = $this->parseTemplateName($name);
$alternatives = $this->findAlternatives($shortname, $shortnames);
if (FilesystemLoader::MAIN_NAMESPACE !== $namespace) {
$alternatives = array_map(function ($shortname) use ($namespace) {
return '@'.$namespace.'/'.$shortname;
}, $alternatives);
$alternatives = array_map(fn ($shortname) => '@'.$namespace.'/'.$shortname, $alternatives);
}
}

Expand Down Expand Up @@ -543,7 +541,7 @@ private function findAlternatives(string $name, array $collection): array
}

$threshold = 1e3;
$alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
$alternatives = array_filter($alternatives, fn ($lev) => $lev < 2 * $threshold);
ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE);

return array_keys($alternatives);
Expand Down
8 changes: 2 additions & 6 deletions src/Symfony/Bridge/Twig/Extension/CodeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,9 +120,7 @@ public function fileExcerpt(string $file, int $line, int $srcContext = 3): ?stri
// remove main code/span tags
$code = preg_replace('#^<code.*?>\s*<span.*?>(.*)</span>\s*</code>#s', '\\1', $code);
// split multiline spans
$code = preg_replace_callback('#<span ([^>]++)>((?:[^<]*+<br \/>)++[^<]*+)</span>#', function ($m) {
return "<span $m[1]>".str_replace('<br />', "</span><br /><span $m[1]>", $m[2]).'</span>';
}, $code);
$code = preg_replace_callback('#<span ([^>]++)>((?:[^<]*+<br \/>)++[^<]*+)</span>#', fn ($m) => "<span $m[1]>".str_replace('<br />', "</span><br /><span $m[1]>", $m[2]).'</span>', $code);
$content = explode('<br />', $code);

$lines = [];
Expand Down Expand Up @@ -188,9 +186,7 @@ public function getFileRelative(string $file): ?string

public function formatFileFromText(string $text): string
{
return preg_replace_callback('/in ("|&quot;)?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', function ($match) {
return 'in '.$this->formatFile($match[2], $match[3]);
}, $text);
return preg_replace_callback('/in ("|&quot;)?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', fn ($match) => 'in '.$this->formatFile($match[2], $match[3]), $text);
}

/**
Expand Down
4 changes: 1 addition & 3 deletions src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,7 @@ private function createCommandTester(): CommandTester
private function createCommand(): Command
{
$environment = new Environment(new FilesystemLoader(\dirname(__DIR__).'/Fixtures/templates/'));
$environment->addFilter(new TwigFilter('deprecated_filter', function ($v) {
return $v;
}, ['deprecated' => true]));
$environment->addFilter(new TwigFilter('deprecated_filter', fn ($v) => $v, ['deprecated' => true]));

$command = new LintCommand($environment);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1039,9 +1039,7 @@ public function testSingleChoiceExpandedWithLabelsSetFalseByCallable()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', '&a', [
'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'],
'choice_label' => function () {
return false;
},
'choice_label' => fn () => false,
'multiple' => false,
'expanded' => true,
]);
Expand Down Expand Up @@ -1404,9 +1402,7 @@ public function testMultipleChoiceExpandedWithLabelsSetFalseByCallable()
{
$form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\ChoiceType', ['&a'], [
'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'],
'choice_label' => function () {
return false;
},
'choice_label' => fn () => false,
'multiple' => true,
'expanded' => true,
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -580,9 +580,7 @@ public function testSingleChoiceExpandedWithLabelsSetFalseByCallable()
{
$form = $this->factory->createNamed('name', ChoiceType::class, '&a', [
'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'],
'choice_label' => function () {
return false;
},
'choice_label' => fn () => false,
'multiple' => false,
'expanded' => true,
]);
Expand Down Expand Up @@ -901,9 +899,7 @@ public function testMultipleChoiceExpandedWithLabelsSetFalseByCallable()
{
$form = $this->factory->createNamed('name', ChoiceType::class, ['&a'], [
'choices' => ['Choice&A' => '&a', 'Choice&B' => '&b'],
'choice_label' => function () {
return false;
},
'choice_label' => fn () => false,
'multiple' => true,
'expanded' => true,
]);
Expand Down
4 changes: 1 addition & 3 deletions src/Symfony/Bridge/Twig/Tests/Mime/BodyRendererTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,7 @@ public function testRenderedOnceUnserializableContext()
;
$email->textTemplate('text');
$email->context([
'foo' => static function () {
return 'bar';
},
'foo' => static fn () => 'bar',
]);

$renderer->render($email);
Expand Down
2 changes: 1 addition & 1 deletion src/Symfony/Bridge/Twig/UndefinedCallableHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static function onUndefinedFunction(string $name): TwigFunction|false
}

if ('webpack-encore-bundle' === self::FUNCTION_COMPONENTS[$name]) {
return new TwigFunction($name, static function () { return ''; });
return new TwigFunction($name, static fn () => '');
}

throw new SyntaxError(self::onUndefined($name, 'function', self::FUNCTION_COMPONENTS[$name]));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function warmUp(string $cacheDir): array
// the ArrayAdapter stores the values serialized
// to avoid mutation of the data after it was written to the cache
// so here we un-serialize the values first
$values = array_map(function ($val) { return null !== $val ? unserialize($val) : null; }, $arrayAdapter->getValues());
$values = array_map(fn ($val) => null !== $val ? unserialize($val) : null, $arrayAdapter->getValues());

return $this->warmUpPhpArrayAdapter(new PhpArrayAdapter($this->phpArrayFile, new NullAdapter()), $values);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter): bool
protected function warmUpPhpArrayAdapter(PhpArrayAdapter $phpArrayAdapter, array $values): array
{
// make sure we don't cache null values
$values = array_filter($values, function ($val) { return null !== $val; });
$values = array_filter($values, fn ($val) => null !== $val);

return parent::warmUpPhpArrayAdapter($phpArrayAdapter, $values);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter): bool
protected function warmUpPhpArrayAdapter(PhpArrayAdapter $phpArrayAdapter, array $values): array
{
// make sure we don't cache null values
$values = array_filter($values, function ($val) { return null !== $val; });
$values = array_filter($values, fn ($val) => null !== $val);

return parent::warmUpPhpArrayAdapter($phpArrayAdapter, $values);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,7 @@ protected function listBundles(OutputInterface|StyleInterface $output)
$rows = [];

$bundles = $this->getApplication()->getKernel()->getBundles();
usort($bundles, function ($bundleA, $bundleB) {
return strcmp($bundleA->getName(), $bundleB->getName());
});
usort($bundles, fn ($bundleA, $bundleB) => strcmp($bundleA->getName(), $bundleB->getName()));

foreach ($bundles as $bundle) {
$extension = $bundle->getContainerExtension();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);

$io->table(['Pool name'], array_map(function ($pool) {
return [$pool];
}, $this->poolNames));
$io->table(['Pool name'], array_map(fn ($pool) => [$pool], $this->poolNames));

return 0;
}
Expand Down
Loading