From 0a00d17c6c879bbdf385ae4b0a5a383bb1f2e050 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Thu, 13 Jul 2023 11:34:31 +0200 Subject: [PATCH] Add return types and parameter types --- best_practices.rst | 4 +- bundles/configuration.rst | 14 ++--- bundles/extension.rst | 6 +-- bundles/prepend_extension.rst | 4 +- cache.rst | 5 +- components/asset.rst | 4 +- components/browser_kit.rst | 2 +- components/config/definition.rst | 8 +-- components/config/resources.rst | 4 +- .../console/changing_default_command.rst | 6 ++- components/console/console_arguments.rst | 4 +- components/console/helpers/questionhelper.rst | 2 +- components/console/logger.rst | 6 ++- components/dependency_injection.rst | 2 +- .../dependency_injection/compilation.rst | 24 ++++----- components/event_dispatcher.rst | 14 ++--- components/event_dispatcher/generic_event.rst | 6 +-- components/expression_language.rst | 2 +- components/form.rst | 15 ++++-- components/http_foundation.rst | 2 +- components/http_kernel.rst | 2 +- components/messenger.rst | 2 +- components/options_resolver.rst | 52 +++++++++---------- components/phpunit_bridge.rst | 24 ++++----- components/property_access.rst | 12 ++--- components/serializer.rst | 34 ++++++------ components/string.rst | 2 +- components/validator/metadata.rst | 10 ++-- components/var_dumper.rst | 8 +-- configuration.rst | 2 +- configuration/env_var_processors.rst | 4 +- configuration/micro_kernel_trait.rst | 2 +- configuration/using_parameters_in_dic.rst | 4 +- console.rst | 2 +- console/input.rst | 2 +- contributing/code/standards.rst | 2 +- contributing/documentation/standards.rst | 2 +- controller/upload_file.rst | 5 +- create_framework/event_dispatcher.rst | 14 ++--- create_framework/http_foundation.rst | 2 +- .../http_kernel_controller_resolver.rst | 14 ++--- .../http_kernel_httpkernel_class.rst | 8 +-- .../http_kernel_httpkernelinterface.rst | 2 +- create_framework/separation_of_concerns.rst | 6 +-- create_framework/templating.rst | 6 +-- create_framework/unit_testing.rst | 8 +-- event_dispatcher.rst | 4 +- form/data_mappers.rst | 2 +- form/embedded.rst | 2 +- form/unit_testing.rst | 10 ++-- frontend/custom_version_strategy.rst | 6 +-- http_cache.rst | 3 +- http_cache/cache_vary.rst | 2 +- http_cache/esi.rst | 4 +- http_cache/expiration.rst | 4 +- lock.rst | 9 ++-- logging.rst | 3 +- logging/monolog_console.rst | 8 ++- mailer.rst | 4 +- mercure.rst | 2 +- messenger.rst | 19 +++---- messenger/dispatch_after_current_bus.rst | 4 +- messenger/handler_results.rst | 2 +- migration.rst | 2 +- notifier.rst | 13 +++-- performance.rst | 2 +- profiler.rst | 13 ++--- quick_tour/the_architecture.rst | 2 +- rate_limiter.rst | 8 +-- reference/configuration/doctrine.rst | 2 +- reference/constraints/Callback.rst | 6 +-- reference/constraints/Choice.rst | 2 +- reference/constraints/Expression.rst | 10 ++-- reference/constraints/Json.rst | 2 +- reference/constraints/Traverse.rst | 2 +- reference/constraints/Ulid.rst | 2 +- reference/constraints/When.rst | 8 +-- reference/dic_tags.rst | 14 ++--- reference/events.rst | 12 ++--- reference/formats/expression_language.rst | 2 +- reference/forms/types/file.rst | 2 +- routing.rst | 4 +- routing/custom_route_loader.rst | 10 ++-- security.rst | 2 +- security/impersonating_user.rst | 2 +- security/login_link.rst | 11 ++-- security/passwords.rst | 5 +- serializer/custom_context_builders.rst | 4 +- serializer/custom_encoders.rst | 8 +-- serializer/custom_normalizer.rst | 4 +- service_container/autowiring.rst | 2 +- service_container/request.rst | 2 +- .../service_subscribers_locators.rst | 12 ++--- session.rst | 12 ++--- templates.rst | 16 +++--- testing.rst | 10 ++-- testing/database.rst | 6 +-- testing/profiling.rst | 2 +- translation.rst | 11 ++-- validation/custom_constraint.rst | 9 ++-- validation/groups.rst | 2 +- validation/raw_values.rst | 2 +- validation/sequence_provider.rst | 10 ++-- web_link.rst | 3 +- workflow/workflow-and-state-machine.rst | 2 +- 105 files changed, 370 insertions(+), 338 deletions(-) diff --git a/best_practices.rst b/best_practices.rst index 403c9920018..d500cfc34e0 100644 --- a/best_practices.rst +++ b/best_practices.rst @@ -411,7 +411,7 @@ checks that all application URLs load successfully:: /** * @dataProvider urlProvider */ - public function testPageIsSuccessful($url) + public function testPageIsSuccessful($url): void { $client = self::createClient(); $client->request('GET', $url); @@ -419,7 +419,7 @@ checks that all application URLs load successfully:: $this->assertResponseIsSuccessful(); } - public function urlProvider() + public function urlProvider(): \Generator { yield ['/']; yield ['/posts']; diff --git a/bundles/configuration.rst b/bundles/configuration.rst index bc9efc1e0b9..4a2224429ed 100644 --- a/bundles/configuration.rst +++ b/bundles/configuration.rst @@ -183,7 +183,7 @@ The ``Configuration`` class to handle the sample configuration looks like:: class Configuration implements ConfigurationInterface { - public function getConfigTreeBuilder() + public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('acme_social'); @@ -217,7 +217,7 @@ force validation (e.g. if an additional option was passed, an exception will be thrown):: // src/Acme/SocialBundle/DependencyInjection/AcmeSocialExtension.php - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); @@ -259,7 +259,7 @@ In your extension, you can load this and dynamically set its arguments:: use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config')); $loader->load('services.xml'); @@ -288,7 +288,7 @@ In your extension, you can load this and dynamically set its arguments:: class AcmeHelloExtension extends ConfigurableExtension { // note that this method is called loadInternal and not load - protected function loadInternal(array $mergedConfig, ContainerBuilder $container) + protected function loadInternal(array $mergedConfig, ContainerBuilder $container): void { // ... } @@ -304,7 +304,7 @@ In your extension, you can load this and dynamically set its arguments:: (e.g. by overriding configurations and using :phpfunction:`isset` to check for the existence of a value). Be aware that it'll be very hard to support XML:: - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $config = []; // let resources override the previous set value @@ -458,7 +458,7 @@ the extension. You might want to change this to a more professional URL:: { // ... - public function getNamespace() + public function getNamespace(): string { return 'http://acme_company.com/schema/dic/hello'; } @@ -490,7 +490,7 @@ can place it anywhere you like. You should return this path as the base path:: { // ... - public function getXsdValidationBasePath() + public function getXsdValidationBasePath(): string { return __DIR__.'/../Resources/config/schema'; } diff --git a/bundles/extension.rst b/bundles/extension.rst index f831efdaf5b..ff873f2ab14 100644 --- a/bundles/extension.rst +++ b/bundles/extension.rst @@ -34,7 +34,7 @@ This is how the extension of an AcmeHelloBundle should look like:: class AcmeHelloExtension extends Extension { - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { // ... you'll load the files here later } @@ -90,7 +90,7 @@ For instance, assume you have a file called ``services.xml`` in the use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; // ... - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $loader = new XmlFileLoader( $container, @@ -167,7 +167,7 @@ they are compiled when generating the application cache to improve the overall performance. Define the list of annotated classes to compile in the ``addAnnotatedClassesToCompile()`` method:: - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { // ... diff --git a/bundles/prepend_extension.rst b/bundles/prepend_extension.rst index 8d28080470f..fcad249124e 100644 --- a/bundles/prepend_extension.rst +++ b/bundles/prepend_extension.rst @@ -31,7 +31,7 @@ To give an Extension the power to do this, it needs to implement { // ... - public function prepend(ContainerBuilder $container) + public function prepend(ContainerBuilder $container): void { // ... } @@ -52,7 +52,7 @@ a configuration setting in multiple bundles as well as disable a flag in multipl in case a specific other bundle is not registered:: // src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php - public function prepend(ContainerBuilder $container) + public function prepend(ContainerBuilder $container): void { // get all bundles $bundles = $container->getParameter('kernel.bundles'); diff --git a/cache.rst b/cache.rst index e739d27f4d4..f0bde04114f 100644 --- a/cache.rst +++ b/cache.rst @@ -307,9 +307,10 @@ with either :class:`Symfony\\Contracts\\Cache\\CacheInterface` or ``Psr\Cache\CacheItemPoolInterface``:: use Symfony\Contracts\Cache\CacheInterface; + // ... // from a controller method - public function listProducts(CacheInterface $customThingCache) + public function listProducts(CacheInterface $customThingCache): Response { // ... } @@ -555,7 +556,7 @@ the same key could be invalidated with one function call:: ) { } - public function someMethod() + public function someMethod(): void { $value0 = $this->myCachePool->get('item_0', function (ItemInterface $item): string { $item->tag(['foo', 'bar']); diff --git a/components/asset.rst b/components/asset.rst index 8ffdbd7e41d..5fa966bb85b 100644 --- a/components/asset.rst +++ b/components/asset.rst @@ -210,12 +210,12 @@ every day:: $this->version = date('Ymd'); } - public function getVersion(string $path) + public function getVersion(string $path): \DateTimeInterface { return $this->version; } - public function applyVersion(string $path) + public function applyVersion(string $path): string { return sprintf('%s?v=%s', $path, $this->getVersion($path)); } diff --git a/components/browser_kit.rst b/components/browser_kit.rst index fe90031f31f..85aaf88a520 100644 --- a/components/browser_kit.rst +++ b/components/browser_kit.rst @@ -38,7 +38,7 @@ This method accepts a request and should return a response:: class Client extends AbstractBrowser { - protected function doRequest($request) + protected function doRequest($request): Response { // ... convert request into a response diff --git a/components/config/definition.rst b/components/config/definition.rst index 8dab6d2163e..f784048f233 100644 --- a/components/config/definition.rst +++ b/components/config/definition.rst @@ -54,7 +54,7 @@ implements the :class:`Symfony\\Component\\Config\\Definition\\ConfigurationInte class DatabaseConfiguration implements ConfigurationInterface { - public function getConfigTreeBuilder() + public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('database'); @@ -540,7 +540,9 @@ be large and you may want to split it up into sections. You can do this by making a section a separate node and then appending it into the main tree with ``append()``:: - public function getConfigTreeBuilder() + use Symfony\Component\Config\Definition\Builder\NodeDefinition; + + public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('database'); @@ -569,7 +571,7 @@ tree with ``append()``:: return $treeBuilder; } - public function addParametersNode() + public function addParametersNode(): NodeDefinition { $treeBuilder = new TreeBuilder('parameters'); diff --git a/components/config/resources.rst b/components/config/resources.rst index 22bdd2b34e9..22f66e74332 100644 --- a/components/config/resources.rst +++ b/components/config/resources.rst @@ -43,7 +43,7 @@ which allows for recursively importing other resources:: class YamlUserLoader extends FileLoader { - public function load($resource, $type = null) + public function load($resource, $type = null): void { $configValues = Yaml::parse(file_get_contents($resource)); @@ -54,7 +54,7 @@ which allows for recursively importing other resources:: // $this->import('extra_users.yaml'); } - public function supports($resource, $type = null) + public function supports($resource, $type = null): bool { return is_string($resource) && 'yaml' === pathinfo( $resource, diff --git a/components/console/changing_default_command.rst b/components/console/changing_default_command.rst index f8b100993a9..b739e3b39ba 100644 --- a/components/console/changing_default_command.rst +++ b/components/console/changing_default_command.rst @@ -15,14 +15,16 @@ name to the ``setDefaultCommand()`` method:: #[AsCommand(name: 'hello:world')] class HelloWorldCommand extends Command { - protected function configure() + protected function configure(): void { $this->setDescription('Outputs "Hello World"'); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln('Hello World'); + + return Command::SUCCESS; } } diff --git a/components/console/console_arguments.rst b/components/console/console_arguments.rst index d7bf141f4ce..da538ac78f1 100644 --- a/components/console/console_arguments.rst +++ b/components/console/console_arguments.rst @@ -22,7 +22,7 @@ Have a look at the following command that has three options:: #[AsCommand(name: 'demo:args', description: 'Describe args behaviors')] class DemoArgsCommand extends Command { - protected function configure() + protected function configure(): void { $this ->setDefinition( @@ -34,7 +34,7 @@ Have a look at the following command that has three options:: ); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { // ... } diff --git a/components/console/helpers/questionhelper.rst b/components/console/helpers/questionhelper.rst index 5729c112af1..0f8aa5f08c3 100644 --- a/components/console/helpers/questionhelper.rst +++ b/components/console/helpers/questionhelper.rst @@ -488,7 +488,7 @@ from the command line, you need to set the inputs that the command expects:: use Symfony\Component\Console\Tester\CommandTester; // ... - public function testExecute() + public function testExecute(): void { // ... $commandTester = new CommandTester($command); diff --git a/components/console/logger.rst b/components/console/logger.rst index afeab7dd0cb..4af0b9a3f2f 100644 --- a/components/console/logger.rst +++ b/components/console/logger.rst @@ -21,7 +21,7 @@ PSR-3 compliant logger:: ) { } - public function doStuff() + public function doStuff(): void { $this->logger->info('I love Tony Vairelles\' hairdresser.'); } @@ -44,12 +44,14 @@ You can rely on the logger to use this dependency inside a command:: )] class MyCommand extends Command { - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $logger = new ConsoleLogger($output); $myDependency = new MyDependency($logger); $myDependency->doStuff(); + + // ... } } diff --git a/components/dependency_injection.rst b/components/dependency_injection.rst index 45ecc6dc194..79b35bf312e 100644 --- a/components/dependency_injection.rst +++ b/components/dependency_injection.rst @@ -126,7 +126,7 @@ it was only optional then you could use setter injection instead:: { private \Mailer $mailer; - public function setMailer(\Mailer $mailer) + public function setMailer(\Mailer $mailer): void { $this->mailer = $mailer; } diff --git a/components/dependency_injection/compilation.rst b/components/dependency_injection/compilation.rst index edaa8be8f47..a085f76b5e5 100644 --- a/components/dependency_injection/compilation.rst +++ b/components/dependency_injection/compilation.rst @@ -61,7 +61,7 @@ A very simple extension may just load configuration files into the container:: class AcmeDemoExtension implements ExtensionInterface { - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $loader = new XmlFileLoader( $container, @@ -90,7 +90,7 @@ The Extension must specify a ``getAlias()`` method to implement the interface:: { // ... - public function getAlias() + public function getAlias(): string { return 'acme_demo'; } @@ -132,7 +132,7 @@ are loaded:: The values from those sections of the config files are passed into the first argument of the ``load()`` method of the extension:: - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $foo = $configs[0]['foo']; //fooValue $bar = $configs[0]['bar']; //barValue @@ -158,7 +158,7 @@ you could access the config value this way:: use Symfony\Component\Config\Definition\Processor; // ... - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); $processor = new Processor(); @@ -175,12 +175,12 @@ namespace so that the relevant parts of an XML config file are passed to the extension. The other to specify the base path to XSD files to validate the XML configuration:: - public function getXsdValidationBasePath() + public function getXsdValidationBasePath(): string { return __DIR__.'/../Resources/config/'; } - public function getNamespace() + public function getNamespace(): string { return 'http://www.example.com/symfony/schema/'; } @@ -219,7 +219,7 @@ The processed config value can now be added as container parameters as if it were listed in a ``parameters`` section of the config file but with the additional benefit of merging multiple files and validation of the configuration:: - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); $processor = new Processor(); @@ -234,7 +234,7 @@ More complex configuration requirements can be catered for in the Extension classes. For example, you may choose to load a main service configuration file but also load a secondary one only if a certain parameter is set:: - public function load(array $configs, ContainerBuilder $container) + public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); $processor = new Processor(); @@ -292,7 +292,7 @@ method is called by implementing { // ... - public function prepend(ContainerBuilder $container) + public function prepend(ContainerBuilder $container): void { // ... @@ -323,7 +323,7 @@ compilation:: class AcmeDemoExtension implements ExtensionInterface, CompilerPassInterface { - public function process(ContainerBuilder $container) + public function process(ContainerBuilder $container): void { // ... do something during the compilation } @@ -377,7 +377,7 @@ class implementing the ``CompilerPassInterface``:: class CustomPass implements CompilerPassInterface { - public function process(ContainerBuilder $container) + public function process(ContainerBuilder $container): void { // ... do something during the compilation } @@ -475,7 +475,7 @@ serves at dumping the compiled container:: the :ref:`dumpFile() method ` from Symfony Filesystem component or other methods provided by Symfony (e.g. ``$containerConfigCache->write()``) which are atomic. - + ``ProjectServiceContainer`` is the default name given to the dumped container class. However, you can change this with the ``class`` option when you dump it:: diff --git a/components/event_dispatcher.rst b/components/event_dispatcher.rst index 68d7a5f39e6..9ecce61a4f1 100644 --- a/components/event_dispatcher.rst +++ b/components/event_dispatcher.rst @@ -162,7 +162,7 @@ the ``Event`` object as the single argument:: { // ... - public function onFooAction(Event $event) + public function onFooAction(Event $event): void { // ... do something } @@ -349,7 +349,7 @@ Take the following example of a subscriber that subscribes to the class StoreSubscriber implements EventSubscriberInterface { - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ KernelEvents::RESPONSE => [ @@ -360,17 +360,17 @@ Take the following example of a subscriber that subscribes to the ]; } - public function onKernelResponsePre(ResponseEvent $event) + public function onKernelResponsePre(ResponseEvent $event): void { // ... } - public function onKernelResponsePost(ResponseEvent $event) + public function onKernelResponsePost(ResponseEvent $event): void { // ... } - public function onStoreOrder(OrderPlacedEvent $event) + public function onStoreOrder(OrderPlacedEvent $event): void { // ... } @@ -415,7 +415,7 @@ inside a listener via the use Acme\Store\Event\OrderPlacedEvent; - public function onStoreOrder(OrderPlacedEvent $event) + public function onStoreOrder(OrderPlacedEvent $event): void { // ... @@ -458,7 +458,7 @@ is dispatched, are passed as arguments to the listener:: class MyListener { - public function myEventListener(Event $event, string $eventName, EventDispatcherInterface $dispatcher) + public function myEventListener(Event $event, string $eventName, EventDispatcherInterface $dispatcher): void { // ... do something with the event name } diff --git a/components/event_dispatcher/generic_event.rst b/components/event_dispatcher/generic_event.rst index dbc37cbe752..d0d2673db09 100644 --- a/components/event_dispatcher/generic_event.rst +++ b/components/event_dispatcher/generic_event.rst @@ -54,7 +54,7 @@ Passing a subject:: class FooListener { - public function handler(GenericEvent $event) + public function handler(GenericEvent $event): void { if ($event->getSubject() instanceof Foo) { // ... @@ -75,7 +75,7 @@ access the event arguments:: class FooListener { - public function handler(GenericEvent $event) + public function handler(GenericEvent $event): void { if (isset($event['type']) && 'foo' === $event['type']) { // ... do something @@ -94,7 +94,7 @@ Filtering data:: class FooListener { - public function filter(GenericEvent $event) + public function filter(GenericEvent $event): void { $event['data'] = strtolower($event['data']); } diff --git a/components/expression_language.rst b/components/expression_language.rst index f936efdb112..8d075425c26 100644 --- a/components/expression_language.rst +++ b/components/expression_language.rst @@ -322,7 +322,7 @@ register:: class StringExpressionLanguageProvider implements ExpressionFunctionProviderInterface { - public function getFunctions() + public function getFunctions(): array { return [ new ExpressionFunction('lowercase', function ($str): string { diff --git a/components/form.rst b/components/form.rst index 79763fcacbe..33dfb37ad52 100644 --- a/components/form.rst +++ b/components/form.rst @@ -392,10 +392,11 @@ is created from the form factory. use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; class TaskController extends AbstractController { - public function new(Request $request) + public function new(Request $request): Response { // createFormBuilder is a shortcut to get the "form factory" // and then call "createBuilder()" on it @@ -451,10 +452,11 @@ an "edit" form), pass in the default data when creating your form builder: use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\TextType; + use Symfony\Component\HttpFoundation\Response; class DefaultController extends AbstractController { - public function new(Request $request) + public function new(Request $request): Response { $defaults = [ 'dueDate' => new \DateTime('tomorrow'), @@ -536,10 +538,11 @@ by :method:`Symfony\\Component\\Form\\Form::handleRequest` to determine whether use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\FormType; + use Symfony\Component\HttpFoundation\Response; class DefaultController extends AbstractController { - public function search() + public function search(): Response { $formBuilder = $this->createFormBuilder(null, [ 'action' => '/search', @@ -581,10 +584,11 @@ method: use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\TextType; + use Symfony\Component\HttpFoundation\Response; class TaskController extends AbstractController { - public function new(Request $request) + public function new(Request $request): Response { $form = $this->createFormBuilder() ->add('task', TextType::class) @@ -676,12 +680,13 @@ option when building each field: use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\TextType; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Validator\Constraints\NotBlank; use Symfony\Component\Validator\Constraints\Type; class DefaultController extends AbstractController { - public function new(Request $request) + public function new(Request $request): Response { $form = $this->createFormBuilder() ->add('task', TextType::class, [ diff --git a/components/http_foundation.rst b/components/http_foundation.rst index ee1ae532f87..6a3719f008d 100644 --- a/components/http_foundation.rst +++ b/components/http_foundation.rst @@ -790,7 +790,7 @@ methods. You can inject this as a service anywhere in your application:: ) { } - public function normalize($user) + public function normalize($user): array { return [ 'avatar' => $this->urlHelper->getAbsoluteUrl($user->avatar()->path()), diff --git a/components/http_kernel.rst b/components/http_kernel.rst index 2c3e5266a20..be3a723984e 100644 --- a/components/http_kernel.rst +++ b/components/http_kernel.rst @@ -706,7 +706,7 @@ look like this:: use Symfony\Component\HttpKernel\Event\RequestEvent; // ... - public function onKernelRequest(RequestEvent $event) + public function onKernelRequest(RequestEvent $event): void { if (!$event->isMainRequest()) { return; diff --git a/components/messenger.rst b/components/messenger.rst index 14f220623e2..f52ca72e40d 100644 --- a/components/messenger.rst +++ b/components/messenger.rst @@ -111,7 +111,7 @@ that will do the required processing for your message:: class MyMessageHandler { - public function __invoke(MyMessage $message) + public function __invoke(MyMessage $message): void { // Message processing... } diff --git a/components/options_resolver.rst b/components/options_resolver.rst index 050e7d0acc2..a71a08f7b77 100644 --- a/components/options_resolver.rst +++ b/components/options_resolver.rst @@ -121,7 +121,7 @@ code:: { // ... - public function sendMail($from, $to) + public function sendMail($from, $to): void { $mail = ...; $mail->setHost($this->options['host']); @@ -147,7 +147,7 @@ It's a good practice to split the option configuration into a separate method:: $this->options = $resolver->resolve($options); } - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'host' => 'smtp.example.org', @@ -166,7 +166,7 @@ than processing options. Second, sub-classes may now override the // ... class GoogleMailer extends Mailer { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -189,7 +189,7 @@ For example, to make the ``host`` option required, you can do:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setRequired('host'); @@ -213,7 +213,7 @@ one required option:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setRequired(['host', 'username', 'password']); @@ -228,7 +228,7 @@ retrieve the names of all required options:: // ... class GoogleMailer extends Mailer { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -251,7 +251,7 @@ been set:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setRequired('host'); @@ -261,7 +261,7 @@ been set:: // ... class GoogleMailer extends Mailer { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -296,7 +296,7 @@ correctly. To validate the types of the options, call { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... @@ -347,7 +347,7 @@ to verify that the passed option contains one of these values:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setDefault('transport', 'sendmail'); @@ -408,7 +408,7 @@ option. You can configure a normalizer by calling { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... @@ -430,7 +430,7 @@ if you need to use other options during normalization:: class Mailer { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setNormalizer('host', function (Options $options, string $value): string { @@ -470,7 +470,7 @@ these options, you can return the desired default value:: class Mailer { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setDefault('encryption', null); @@ -502,7 +502,7 @@ the closure:: class Mailer { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setDefaults([ @@ -514,7 +514,7 @@ the closure:: class GoogleMailer extends Mailer { - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -545,14 +545,14 @@ from the default:: class Mailer { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setDefault('port', 25); } // ... - public function sendMail($from, $to) + public function sendMail(string $from, string $to): void { // Is this the default value or did the caller of the class really // set the port to 25? @@ -572,14 +572,14 @@ be included in the resolved options if it was actually passed to { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setDefined('port'); } // ... - public function sendMail($from, $to) + public function sendMail(string from, string $to): void { if (array_key_exists('port', $this->options)) { echo 'Set!'; @@ -606,7 +606,7 @@ options in one go:: class Mailer { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->setDefined(['port', 'encryption']); @@ -622,7 +622,7 @@ let you find out which options are defined:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { parent::configureOptions($resolver); @@ -652,7 +652,7 @@ default value:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('spool', function (OptionsResolver $spoolResolver): void { $spoolResolver->setDefaults([ @@ -664,7 +664,7 @@ default value:: }); } - public function sendMail($from, $to) + public function sendMail(string $from, string $to): void { if ('memory' === $this->options['spool']['type']) { // ... @@ -687,7 +687,7 @@ to the closure to access to them:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('sandbox', false); $resolver->setDefault('spool', function (OptionsResolver $spoolResolver, Options $parent): void { @@ -711,7 +711,7 @@ In same way, parent options can access to the nested options as normal arrays:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefault('spool', function (OptionsResolver $spoolResolver): void { $spoolResolver->setDefaults([ @@ -856,7 +856,7 @@ method:: class InvoiceMailer { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { // ... $resolver->define('host') diff --git a/components/phpunit_bridge.rst b/components/phpunit_bridge.rst index 4a4411fbe1a..cdc99497892 100644 --- a/components/phpunit_bridge.rst +++ b/components/phpunit_bridge.rst @@ -418,7 +418,7 @@ times (order matters):: /** * @group legacy */ - public function testDeprecatedCode() + public function testDeprecatedCode(): void { // test some code that triggers the following deprecation: // trigger_deprecation('vendor-name/package-name', '5.1', 'This "Foo" method is deprecated.'); @@ -504,7 +504,7 @@ If you have this kind of time-related tests:: class MyTest extends TestCase { - public function testSomething() + public function testSomething(): void { $stopwatch = new Stopwatch(); @@ -575,7 +575,7 @@ test:: */ class MyTest extends TestCase { - public function testSomething() + public function testSomething(): void { $stopwatch = new Stopwatch(); @@ -603,7 +603,7 @@ different class, do it explicitly using ``ClockMock::register(MyClass::class)``: class MyClass { - public function getTimeInHours() + public function getTimeInHours(): void { return time() / 3600; } @@ -621,7 +621,7 @@ different class, do it explicitly using ``ClockMock::register(MyClass::class)``: */ class MyTest extends TestCase { - public function testGetTimeInHours() + public function testGetTimeInHours(): void { ClockMock::register(MyClass::class); @@ -669,7 +669,7 @@ associated to a valid host:: class MyTest extends TestCase { - public function testEmail() + public function testEmail(): void { $validator = new DomainValidator(['checkDnsRecord' => true]); $isValid = $validator->validate('example.com'); @@ -691,7 +691,7 @@ the data you expect to get for the given hosts:: */ class DomainValidatorTest extends TestCase { - public function testEmails() + public function testEmails(): void { DnsMock::withMockedHosts([ 'example.com' => [['type' => 'A', 'ip' => '1.2.3.4']], @@ -761,7 +761,7 @@ are installed during tests) would look like:: class MyClassTest extends TestCase { - public function testHello() + public function testHello(): void { $class = new MyClass(); $result = $class->hello(); // "The dependency behavior." @@ -782,7 +782,7 @@ classes, interfaces and/or traits for the code to run:: { // ... - public function testHelloDefault() + public function testHelloDefault(): void { ClassExistsMock::register(MyClass::class); ClassExistsMock::withMockedClasses([DependencyClass::class => false]); @@ -940,7 +940,7 @@ Consider the following example:: class Bar { - public function barMethod() + public function barMethod(): string { return 'bar'; } @@ -953,7 +953,7 @@ Consider the following example:: ) { } - public function fooMethod() + public function fooMethod(): string { $this->bar->barMethod(); @@ -963,7 +963,7 @@ Consider the following example:: class FooTest extends PHPUnit\Framework\TestCase { - public function test() + public function test(): void { $bar = new Bar(); $foo = new Foo($bar); diff --git a/components/property_access.rst b/components/property_access.rst index bf1453d17ee..dcaf1576128 100644 --- a/components/property_access.rst +++ b/components/property_access.rst @@ -120,7 +120,7 @@ it with ``get``. So the actual method becomes ``getFirstName()``:: { private string $firstName = 'Wouter'; - public function getFirstName() + public function getFirstName(): string { return $this->firstName; } @@ -143,12 +143,12 @@ getters, this means that you can do something like this:: private bool $author = true; private array $children = []; - public function isAuthor() + public function isAuthor(): bool { return $this->author; } - public function hasChildren() + public function hasChildren(): bool { return 0 !== count($this->children); } @@ -237,7 +237,7 @@ The ``getValue()`` method can also use the magic ``__get()`` method:: 'Wouter' => [...], ]; - public function __get($id) + public function __get($id): mixed { return $this->children[$id]; } @@ -267,7 +267,7 @@ enable this feature by using :class:`Symfony\\Component\\PropertyAccess\\Propert 'wouter' => [...], ]; - public function __call($name, $args) + public function __call($name, $args): mixed { $property = lcfirst(substr($name, 3)); if ('get' === substr($name, 0, 3)) { @@ -364,7 +364,7 @@ see `Enable other Features`_:: { private array $children = []; - public function __call($name, $args) + public function __call($name, $args): mixed { $property = lcfirst(substr($name, 3)); if ('get' === substr($name, 0, 3)) { diff --git a/components/serializer.rst b/components/serializer.rst index 33fc71e4b69..d285cb56fa1 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -86,7 +86,7 @@ exists in your project:: return $this->name; } - public function getCreatedAt() + public function getCreatedAt(): ?\DateTimeInterface { return $this->createdAt; } @@ -248,12 +248,12 @@ Assume you have the following plain-old-PHP object:: private string $bar; - public function getBar() + public function getBar(): string { return $this->bar; } - public function setBar($bar) + public function setBar($bar): string { return $this->bar = $bar; } @@ -1308,22 +1308,22 @@ Circular references are common when dealing with entity relations:: private string $name; private array $members; - public function setName($name) + public function setName($name): void { $this->name = $name; } - public function getName() + public function getName(): string { return $this->name; } - public function setMembers(array $members) + public function setMembers(array $members): void { $this->members = $members; } - public function getMembers() + public function getMembers(): array { return $this->members; } @@ -1334,22 +1334,22 @@ Circular references are common when dealing with entity relations:: private string $name; private Organization $organization; - public function setName(string $name) + public function setName(string $name): void { $this->name = $name; } - public function getName() + public function getName(): string { return $this->name; } - public function setOrganization(Organization $organization) + public function setOrganization(Organization $organization): void { $this->organization = $organization; } - public function getOrganization() + public function getOrganization(): Organization { return $this->organization; } @@ -1641,24 +1641,24 @@ parameter of the ``ObjectNormalizer``:: private ObjectInner $inner; private \DateTimeInterface $date; - public function getInner() + public function getInner(): ObjectInner { return $this->inner; } - public function setInner(ObjectInner $inner) + public function setInner(ObjectInner $inner): void { $this->inner = $inner; } - public function setDate(\DateTimeInterface $date) + public function getDate(): \DateTimeInterface { - $this->date = $date; + return $this->date; } - public function getDate() + public function setDate(\DateTimeInterface $date): void { - return $this->date; + $this->date = $date; } } diff --git a/components/string.rst b/components/string.rst index bea4705ff05..5af19fc617d 100644 --- a/components/string.rst +++ b/components/string.rst @@ -554,7 +554,7 @@ the injected slugger is the same as the request locale:: ) { } - public function someMethod() + public function someMethod(): void { $slug = $this->slugger->slug('...'); } diff --git a/components/validator/metadata.rst b/components/validator/metadata.rst index 5a88dab76ed..e7df42413bc 100755 --- a/components/validator/metadata.rst +++ b/components/validator/metadata.rst @@ -19,7 +19,7 @@ the ``Author`` class has at least 3 characters:: { private string $firstName; - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('firstName', new Assert\NotBlank()); $metadata->addPropertyConstraint( @@ -40,7 +40,7 @@ Suppose that, for security reasons, you want to validate that a password field doesn't match the first name of the user. First, create a public method called ``isPasswordSafe()`` to define this custom validation logic:: - public function isPasswordSafe() + public function isPasswordSafe(): bool { return $this->firstName !== $this->password; } @@ -53,7 +53,7 @@ Then, add the Validator component configuration to the class:: class Author { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addGetterConstraint('passwordSafe', new Assert\IsTrue([ 'message' => 'The password cannot match your first name', @@ -74,7 +74,7 @@ validation logic:: // ... use Symfony\Component\Validator\Context\ExecutionContextInterface; - public function validate(ExecutionContextInterface $context) + public function validate(ExecutionContextInterface $context): void { // ... } @@ -87,7 +87,7 @@ Then, add the Validator component configuration to the class:: class Author { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addConstraint(new Assert\Callback('validate')); } diff --git a/components/var_dumper.rst b/components/var_dumper.rst index 5557fbdc24d..24e6f022e70 100644 --- a/components/var_dumper.rst +++ b/components/var_dumper.rst @@ -294,7 +294,7 @@ Example:: { use VarDumperTestTrait; - protected function setUp() + protected function setUp(): void { $casters = [ \DateTimeInterface::class => static function (\DateTimeInterface $date, array $a, Stub $stub): array { @@ -311,7 +311,7 @@ Example:: $this->setUpVarDumper($casters, $flags); } - public function testWithDumpEquals() + public function testWithDumpEquals(): void { $testedVar = [123, 'foo']; @@ -797,7 +797,7 @@ Here is a simple caster not doing anything:: use Symfony\Component\VarDumper\Cloner\Stub; - function myCaster($object, $array, Stub $stub, $isNested, $filter) + function myCaster(mixed $object, array $array, Stub $stub, bool $isNested, int $filter): array { // ... populate/alter $array to your needs @@ -861,7 +861,7 @@ that holds a file name or a URL, you can wrap them in a ``LinkStub`` to tell use Symfony\Component\VarDumper\Caster\LinkStub; use Symfony\Component\VarDumper\Cloner\Stub; - function ProductCaster(Product $object, $array, Stub $stub, $isNested, $filter = 0) + function ProductCaster(Product $object, array $array, Stub $stub, bool $isNested, int $filter = 0): array { $array['brochure'] = new LinkStub($array['brochure']); diff --git a/configuration.rst b/configuration.rst index 8cb078a88f7..ee645c0aa21 100644 --- a/configuration.rst +++ b/configuration.rst @@ -1068,7 +1068,7 @@ parameters at once by type-hinting any of its constructor arguments with the ) { } - public function someMethod() + public function someMethod(): void { // get any container parameter from $this->params, which stores all of them $sender = $this->params->get('mailer_sender'); diff --git a/configuration/env_var_processors.rst b/configuration/env_var_processors.rst index 937c0e341f6..3da4ed6b1c1 100644 --- a/configuration/env_var_processors.rst +++ b/configuration/env_var_processors.rst @@ -848,14 +848,14 @@ create a class that implements class LowercasingEnvVarProcessor implements EnvVarProcessorInterface { - public function getEnv(string $prefix, string $name, \Closure $getEnv) + public function getEnv(string $prefix, string $name, \Closure $getEnv): string { $env = $getEnv($name); return strtolower($env); } - public static function getProvidedTypes() + public static function getProvidedTypes(): array { return [ 'lowercase' => 'string', diff --git a/configuration/micro_kernel_trait.rst b/configuration/micro_kernel_trait.rst index ac0d50e1671..feda47d5f16 100644 --- a/configuration/micro_kernel_trait.rst +++ b/configuration/micro_kernel_trait.rst @@ -247,7 +247,7 @@ Now it looks like this:: return $bundles; } - protected function build(ContainerBuilder $containerBuilder) + protected function build(ContainerBuilder $containerBuilder): void { $containerBuilder->registerExtension(new AppExtension()); } diff --git a/configuration/using_parameters_in_dic.rst b/configuration/using_parameters_in_dic.rst index 852b06506ce..3cac5d5049c 100644 --- a/configuration/using_parameters_in_dic.rst +++ b/configuration/using_parameters_in_dic.rst @@ -107,7 +107,7 @@ be injected with this parameter via the extension as follows:: { } - public function getConfigTreeBuilder() + public function getConfigTreeBuilder(): TreeBuilder { $treeBuilder = new TreeBuilder('my_bundle'); @@ -134,7 +134,7 @@ And set it in the constructor of ``Configuration`` via the ``Extension`` class:: { // ... - public function getConfiguration(array $config, ContainerBuilder $container) + public function getConfiguration(array $config, ContainerBuilder $container): Configuration { return new Configuration($container->getParameter('kernel.debug')); } diff --git a/console.rst b/console.rst index 77a0a3ee605..2ab065cedbb 100644 --- a/console.rst +++ b/console.rst @@ -489,7 +489,7 @@ console:: class CreateUserCommandTest extends KernelTestCase { - public function testExecute() + public function testExecute(): void { $kernel = self::bootKernel(); $application = new Application($kernel); diff --git a/console/input.rst b/console/input.rst index 2e6d9a1a438..cd5f8f71586 100644 --- a/console/input.rst +++ b/console/input.rst @@ -386,7 +386,7 @@ to help you unit test the completion logic:: class GreetCommandTest extends TestCase { - public function testComplete() + public function testComplete(): void { $application = new Application(); $application->add(new GreetCommand()); diff --git a/contributing/code/standards.rst b/contributing/code/standards.rst index 7d16e0f9d0b..39d96d9e247 100644 --- a/contributing/code/standards.rst +++ b/contributing/code/standards.rst @@ -111,7 +111,7 @@ short example containing most features described below:: /** * Performs some basic operations for a given value. */ - private function performOperations(mixed $value = null, bool $theSwitch = false) + private function performOperations(mixed $value = null, bool $theSwitch = false): void { if (!$theSwitch) { return; diff --git a/contributing/documentation/standards.rst b/contributing/documentation/standards.rst index 4a5d3c43a31..46d152fe844 100644 --- a/contributing/documentation/standards.rst +++ b/contributing/documentation/standards.rst @@ -109,7 +109,7 @@ Example { // ... - public function foo($bar) + public function foo($bar): mixed { // set foo with a value of bar $foo = ...; diff --git a/controller/upload_file.rst b/controller/upload_file.rst index dc132e3d021..56148422aed 100644 --- a/controller/upload_file.rst +++ b/controller/upload_file.rst @@ -58,7 +58,7 @@ so Symfony doesn't try to get/set its value from the related entity:: class ProductType extends AbstractType { - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { $builder // ... @@ -327,9 +327,10 @@ Now you're ready to use this service in the controller:: use App\Service\FileUploader; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; // ... - public function new(Request $request, FileUploader $fileUploader) + public function new(Request $request, FileUploader $fileUploader): Response { // ... diff --git a/create_framework/event_dispatcher.rst b/create_framework/event_dispatcher.rst index e4921097a33..650e4c7554e 100644 --- a/create_framework/event_dispatcher.rst +++ b/create_framework/event_dispatcher.rst @@ -53,7 +53,7 @@ the Response instance:: ) { } - public function handle(Request $request) + public function handle(Request $request): Response { $this->matcher->getContext()->fromRequest($request); @@ -95,12 +95,12 @@ now dispatched:: ) { } - public function getResponse() + public function getResponse(): Response { return $this->response; } - public function getRequest() + public function getRequest(): Request { return $this->request; } @@ -195,7 +195,7 @@ Let's refactor the code a bit by moving the Google listener to its own class:: class GoogleListener { - public function onResponse(ResponseEvent $event) + public function onResponse(ResponseEvent $event): void { $response = $event->getResponse(); @@ -217,7 +217,7 @@ And do the same with the other listener:: class ContentLengthListener { - public function onResponse(ResponseEvent $event) + public function onResponse(ResponseEvent $event): void { $response = $event->getResponse(); $headers = $response->headers; @@ -259,7 +259,7 @@ look at the new version of the ``GoogleListener``:: { // ... - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return ['response' => 'onResponse']; } @@ -276,7 +276,7 @@ And here is the new version of ``ContentLengthListener``:: { // ... - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return ['response' => ['onResponse', -255]]; } diff --git a/create_framework/http_foundation.rst b/create_framework/http_foundation.rst index 2859c18553b..53c86ebb8b9 100644 --- a/create_framework/http_foundation.rst +++ b/create_framework/http_foundation.rst @@ -61,7 +61,7 @@ unit test for the above code:: class IndexTest extends TestCase { - public function testHello() + public function testHello(): void { $_GET['name'] = 'Fabien'; diff --git a/create_framework/http_kernel_controller_resolver.rst b/create_framework/http_kernel_controller_resolver.rst index 12d9efead6e..1c2857c9ed9 100644 --- a/create_framework/http_kernel_controller_resolver.rst +++ b/create_framework/http_kernel_controller_resolver.rst @@ -10,7 +10,7 @@ class:: class LeapYearController { - public function index($request) + public function index($request): Response { if (is_leap_year($request->attributes->get('year'))) { return new Response('Yep, this is a leap year!'); @@ -112,26 +112,26 @@ More interesting, ``getArguments()`` is also able to inject any Request attribute; if the argument has the same name as the corresponding attribute:: - public function index($year) + public function index(int $year) You can also inject the Request and some attributes at the same time (as the matching is done on the argument name or a type hint, the arguments order does not matter):: - public function index(Request $request, $year) + public function index(Request $request, int $year) - public function index($year, Request $request) + public function index(int $year, Request $request) Finally, you can also define default values for any argument that matches an optional attribute of the Request:: - public function index($year = 2012) + public function index(int $year = 2012) Let's inject the ``$year`` request attribute for our controller:: class LeapYearController { - public function index($year) + public function index(int $year): Response { if (is_leap_year($year)) { return new Response('Yep, this is a leap year!'); @@ -165,7 +165,7 @@ Let's conclude with the new version of our framework:: use Symfony\Component\HttpKernel; use Symfony\Component\Routing; - function render_template(Request $request) + function render_template(Request $request): Response { extract($request->attributes->all(), EXTR_SKIP); ob_start(); diff --git a/create_framework/http_kernel_httpkernel_class.rst b/create_framework/http_kernel_httpkernel_class.rst index fdb2a0b3f5d..fa673f9ba57 100644 --- a/create_framework/http_kernel_httpkernel_class.rst +++ b/create_framework/http_kernel_httpkernel_class.rst @@ -96,7 +96,7 @@ The error controller reads as follows:: class ErrorController { - public function exception(FlattenException $exception) + public function exception(FlattenException $exception): Response { $msg = 'Something went wrong! ('.$exception->getMessage().')'; @@ -133,7 +133,7 @@ instead of a full Response object:: class LeapYearController { - public function index($year) + public function index(int $year): string { $leapYear = new LeapYear(); if ($leapYear->isLeapYear($year)) { @@ -158,7 +158,7 @@ only if needed:: class StringResponseListener implements EventSubscriberInterface { - public function onView(ViewEvent $event) + public function onView(ViewEvent $event): void { $response = $event->getControllerResult(); @@ -167,7 +167,7 @@ only if needed:: } } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return ['kernel.view' => 'onView']; } diff --git a/create_framework/http_kernel_httpkernelinterface.rst b/create_framework/http_kernel_httpkernelinterface.rst index f883b4a2e1d..4f9e1c731bf 100644 --- a/create_framework/http_kernel_httpkernelinterface.rst +++ b/create_framework/http_kernel_httpkernelinterface.rst @@ -76,7 +76,7 @@ to cache a response for 10 seconds, use the ``Response::setTtl()`` method:: // example.com/src/Calendar/Controller/LeapYearController.php // ... - public function index(Request $request, $year) + public function index(Request $request, int $year): Response { $leapYear = new LeapYear(); if ($leapYear->isLeapYear($year)) { diff --git a/create_framework/separation_of_concerns.rst b/create_framework/separation_of_concerns.rst index 76098683226..e0937fbdf45 100644 --- a/create_framework/separation_of_concerns.rst +++ b/create_framework/separation_of_concerns.rst @@ -34,7 +34,7 @@ request handling logic into its own ``Simplex\Framework`` class:: ) { } - public function handle(Request $request) + public function handle(Request $request): Response { $this->matcher->getContext()->fromRequest($request); @@ -102,7 +102,7 @@ Move the controller to ``Calendar\Controller\LeapYearController``:: class LeapYearController { - public function index(Request $request, $year) + public function index(Request $request, int $year): Response { $leapYear = new LeapYear(); if ($leapYear->isLeapYear($year)) { @@ -120,7 +120,7 @@ And move the ``is_leap_year()`` function to its own class too:: class LeapYear { - public function isLeapYear($year = null) + public function isLeapYear(int $year = null): bool { if (null === $year) { $year = date('Y'); diff --git a/create_framework/templating.rst b/create_framework/templating.rst index 908a17f2a8e..0261496e1b4 100644 --- a/create_framework/templating.rst +++ b/create_framework/templating.rst @@ -38,7 +38,7 @@ that renders a template when there is no specific logic. To keep the same template as before, request attributes are extracted before the template is rendered:: - function render_template($request) + function render_template(Request $request): Response { extract($request->attributes->all(), EXTR_SKIP); ob_start(); @@ -106,7 +106,7 @@ Here is the updated and improved version of our framework:: use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing; - function render_template($request) + function render_template(Request $request): Response { extract($request->attributes->all(), EXTR_SKIP); ob_start(); @@ -145,7 +145,7 @@ framework does not need to be modified in any way, create a new use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing; - function is_leap_year($year = null) + function is_leap_year(int $year = null): bool { if (null === $year) { $year = date('Y'); diff --git a/create_framework/unit_testing.rst b/create_framework/unit_testing.rst index 6eec1e91333..5c783c5279a 100644 --- a/create_framework/unit_testing.rst +++ b/create_framework/unit_testing.rst @@ -87,7 +87,7 @@ We are now ready to write our first test:: class FrameworkTest extends TestCase { - public function testNotFoundHandling() + public function testNotFoundHandling(): void { $framework = $this->getFrameworkForException(new ResourceNotFoundException()); @@ -96,7 +96,7 @@ We are now ready to write our first test:: $this->assertEquals(404, $response->getStatusCode()); } - private function getFrameworkForException($exception) + private function getFrameworkForException($exception): Framework { $matcher = $this->createMock(Routing\Matcher\UrlMatcherInterface::class); @@ -137,7 +137,7 @@ either in the test or in the framework code! Adding a unit test for any exception thrown in a controller:: - public function testErrorHandling() + public function testErrorHandling(): void { $framework = $this->getFrameworkForException(new \RuntimeException()); @@ -154,7 +154,7 @@ Response:: use Symfony\Component\HttpKernel\Controller\ControllerResolver; // ... - public function testControllerResponse() + public function testControllerResponse(): void { $matcher = $this->createMock(Routing\Matcher\UrlMatcherInterface::class); diff --git a/event_dispatcher.rst b/event_dispatcher.rst index 896dff71d29..ef9f74c4ae9 100644 --- a/event_dispatcher.rst +++ b/event_dispatcher.rst @@ -732,7 +732,7 @@ this:: return $this->message; } - public function setMessage(string $message) + public function setMessage(string $message): void { $this->message = $message; } @@ -757,7 +757,7 @@ And the ``AfterSendMailEvent`` even like this:: return $this->returnValue; } - public function setReturnValue(mixed $returnValue) + public function setReturnValue(mixed $returnValue): void { $this->returnValue = $returnValue; } diff --git a/form/data_mappers.rst b/form/data_mappers.rst index b5936ccec2c..cb5c7936701 100644 --- a/form/data_mappers.rst +++ b/form/data_mappers.rst @@ -189,7 +189,7 @@ fields and only one of them needs to be mapped in some special way or you only need to change how it's written into the underlying object. In that case, register a PHP callable that is able to write or read to/from that specific object:: - public function buildForm(FormBuilderInterface $builder, array $options) + public function buildForm(FormBuilderInterface $builder, array $options): void { // ... diff --git a/form/embedded.rst b/form/embedded.rst index 4263bb42b5d..dd163235f03 100644 --- a/form/embedded.rst +++ b/form/embedded.rst @@ -44,7 +44,7 @@ Next, add a new ``category`` property to the ``Task`` class:: return $this->category; } - public function setCategory(?Category $category) + public function setCategory(?Category $category): void { $this->category = $category; } diff --git a/form/unit_testing.rst b/form/unit_testing.rst index 048a3c7c0d0..3c38bbbaf17 100644 --- a/form/unit_testing.rst +++ b/form/unit_testing.rst @@ -44,7 +44,7 @@ The simplest ``TypeTestCase`` implementation looks like the following:: class TestedTypeTest extends TypeTestCase { - public function testSubmitValidData() + public function testSubmitValidData(): void { $formData = [ 'test' => 'test', @@ -68,7 +68,7 @@ The simplest ``TypeTestCase`` implementation looks like the following:: $this->assertEquals($expected, $model); } - public function testCustomFormView() + public function testCustomFormView(): void { $formData = new TestObject(); // ... prepare the data as you need @@ -164,7 +164,7 @@ make sure the ``FormRegistry`` uses the created instance:: parent::setUp(); } - protected function getExtensions() + protected function getExtensions(): array { // create a type instance with the mocked dependencies $type = new TestedType($this->objectManager); @@ -175,7 +175,7 @@ make sure the ``FormRegistry`` uses the created instance:: ]; } - public function testSubmitValidData() + public function testSubmitValidData(): void { // ... @@ -210,7 +210,7 @@ allows you to return a list of extensions to register:: class TestedTypeTest extends TypeTestCase { - protected function getExtensions() + protected function getExtensions(): array { $validator = Validation::createValidator(); diff --git a/frontend/custom_version_strategy.rst b/frontend/custom_version_strategy.rst index 0bbcf934e58..f41d6f578fc 100644 --- a/frontend/custom_version_strategy.rst +++ b/frontend/custom_version_strategy.rst @@ -63,7 +63,7 @@ version string:: $this->format = $format ?: '%s?%s'; } - public function getVersion(string $path) + public function getVersion(string $path): string { if (!is_array($this->hashes)) { $this->hashes = $this->loadManifest(); @@ -72,7 +72,7 @@ version string:: return $this->hashes[$path] ?? ''; } - public function applyVersion(string $path) + public function applyVersion(string $path): string { $version = $this->getVersion($path); @@ -83,7 +83,7 @@ version string:: return sprintf($this->format, $path, $version); } - private function loadManifest() + private function loadManifest(): array { return json_decode(file_get_contents($this->manifestPath), true); } diff --git a/http_cache.rst b/http_cache.rst index 71a05bfad41..e1f1a57399c 100644 --- a/http_cache.rst +++ b/http_cache.rst @@ -213,9 +213,8 @@ The *easiest* way to cache a response is by caching it for a specific amount of // src/Controller/BlogController.php use Symfony\Component\HttpFoundation\Response; - // ... - public function index() + public function index(): Response { // somehow create a Response object, like by rendering a template $response = $this->render('blog/index.html.twig', []); diff --git a/http_cache/cache_vary.rst b/http_cache/cache_vary.rst index 6d0254f4510..cb0db8c674d 100644 --- a/http_cache/cache_vary.rst +++ b/http_cache/cache_vary.rst @@ -42,7 +42,7 @@ attribute:: #[Cache(vary: ['Accept-Encoding'])] #[Cache(vary: ['Accept-Encoding', 'User-Agent'])] - public function index() + public function index(): Response { // ... } diff --git a/http_cache/esi.rst b/http_cache/esi.rst index 166672d2c05..aaf1de564c1 100644 --- a/http_cache/esi.rst +++ b/http_cache/esi.rst @@ -189,8 +189,10 @@ of the main page:: // ... class NewsController extends AbstractController { - public function latest($maxPerPage) + public function latest(int $maxPerPage): Response { + // ... + // sets to public and adds some expiration $response->setSharedMaxAge(60); diff --git a/http_cache/expiration.rst b/http_cache/expiration.rst index e6d05311662..692c3db7622 100644 --- a/http_cache/expiration.rst +++ b/http_cache/expiration.rst @@ -25,7 +25,7 @@ is used to specify many different cache directives:: // ... #[Cache(public: true, maxage: 600)] - public function index() + public function index(): Response { // ... } @@ -72,7 +72,7 @@ the ``setExpires()`` ``Response`` method:: // ... #[Cache(expires: '+600 seconds')] - public function index() + public function index(): Response { // ... } diff --git a/lock.rst b/lock.rst index de976f1cfb0..35c3dc5be3c 100644 --- a/lock.rst +++ b/lock.rst @@ -174,12 +174,13 @@ To lock the default resource, autowire the lock factory using namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Lock\LockFactory; class PdfController extends AbstractController { #[Route('/download/terms-of-use.pdf')] - public function downloadPdf(LockFactory $factory, MyPdfGeneratorService $pdf) + public function downloadPdf(LockFactory $factory, MyPdfGeneratorService $pdf): Response { $lock = $factory->createLock('pdf-creation'); $lock->acquire(true); @@ -213,12 +214,13 @@ processes asking for the same ``$version``:: namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Lock\LockFactory; class PdfController extends AbstractController { #[Route('/download/{version}/terms-of-use.pdf')] - public function downloadPdf($version, LockFactory $lockFactory, MyPdfGeneratorService $pdf) + public function downloadPdf($version, LockFactory $lockFactory, MyPdfGeneratorService $pdf): Response { $lock = $lockFactory->createLock('pdf-creation-'.$version); $lock->acquire(true); @@ -293,12 +295,13 @@ For instance, the ``invoice`` lock can be injected by naming the argument namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Lock\LockFactory; class PdfController extends AbstractController { #[Route('/download/terms-of-use.pdf')] - public function downloadPdf(LockFactory $invoiceLockFactory, MyPdfGeneratorService $pdf) + public function downloadPdf(LockFactory $invoiceLockFactory, MyPdfGeneratorService $pdf): Response { // ... } diff --git a/logging.rst b/logging.rst index ecc14a9b8b0..ffa967962e5 100644 --- a/logging.rst +++ b/logging.rst @@ -26,8 +26,9 @@ Logging a Message To log a message, inject the default logger in your controller or service:: use Psr\Log\LoggerInterface; + // ... - public function index(LoggerInterface $logger) + public function index(LoggerInterface $logger): Response { $logger->info('I just got the logger'); $logger->error('An error occurred'); diff --git a/logging/monolog_console.rst b/logging/monolog_console.rst index ad06cfabbff..fabccc72e62 100644 --- a/logging/monolog_console.rst +++ b/logging/monolog_console.rst @@ -13,7 +13,7 @@ calls need to be wrapped in conditions. For example:: use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { if ($output->isDebug()) { $output->writeln('Some info'); @@ -22,6 +22,8 @@ calls need to be wrapped in conditions. For example:: if ($output->isVerbose()) { $output->writeln('Some more info'); } + + // ... } Instead of using these semantic methods to test for each of the verbosity @@ -47,10 +49,12 @@ The example above could then be rewritten as:: ) { } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->logger->debug('Some info'); $this->logger->notice('Some more info'); + + // ... } } diff --git a/mailer.rst b/mailer.rst index 205d4abbc3f..63a91977c2e 100644 --- a/mailer.rst +++ b/mailer.rst @@ -1354,7 +1354,7 @@ render the email before calling ``$mailer->send($email)``:: use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\BodyRendererInterface; - public function action(MailerInterface $mailer, BodyRendererInterface $bodyRenderer) + public function action(MailerInterface $mailer, BodyRendererInterface $bodyRenderer): void { $email = (new TemplatedEmail()) ->htmlTemplate($template) @@ -1781,7 +1781,7 @@ the :class:`Symfony\\Bundle\\FrameworkBundle\\Test\\MailerAssertionsTrait`:: class MailControllerTest extends WebTestCase { - public function testMailIsSentAndContentIsOk() + public function testMailIsSentAndContentIsOk(): void { $client = static::createClient(); $client->request('GET', '/mail/send'); diff --git a/mercure.rst b/mercure.rst index 34f5f0c4b70..55889a33ff7 100644 --- a/mercure.rst +++ b/mercure.rst @@ -628,7 +628,7 @@ You can instead make use of the ``MockHub`` class:: class MessageControllerTest extends TestCase { - public function testPublishing() + public function testPublishing(): void { $hub = new MockHub('https://internal/.well-known/mercure', new StaticTokenProvider('foo'), function(Update $update): string { // $this->assertTrue($update->isPrivate()); diff --git a/messenger.rst b/messenger.rst index b1349f476d9..8e6648f9dcb 100644 --- a/messenger.rst +++ b/messenger.rst @@ -96,11 +96,12 @@ You're ready! To dispatch the message (and call the handler), inject the use App\Message\SmsNotification; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Messenger\MessageBusInterface; class DefaultController extends AbstractController { - public function index(MessageBusInterface $bus) + public function index(MessageBusInterface $bus): Response { // will cause the SmsNotificationHandler to be called $bus->dispatch(new SmsNotification('Look! I created a message!')); @@ -392,7 +393,7 @@ Then, in your handler, you can query for a fresh object:: ) { } - public function __invoke(NewUserWelcomeEmail $welcomeEmail) + public function __invoke(NewUserWelcomeEmail $welcomeEmail): void { $user = $this->userRepository->find($welcomeEmail->getUserId()); @@ -1697,7 +1698,7 @@ during a request:: class DefaultControllerTest extends WebTestCase { - public function testSomething() + public function testSomething(): void { $client = static::createClient(); // ... @@ -1900,7 +1901,7 @@ You can configure your handler by passing options to the attribute:: #[AsMessageHandler(fromTransport: 'async', priority: 10)] class SmsNotificationHandler { - public function __invoke(SmsNotification $message) + public function __invoke(SmsNotification $message): void { // ... } @@ -1994,13 +1995,13 @@ A single handler class can handle multiple messages. For that add the class SmsNotificationHandler { #[AsMessageHandler] - public function handleSmsNotification(SmsNotification $message) + public function handleSmsNotification(SmsNotification $message): void { // ... } #[AsMessageHandler] - public function handleOtherSmsNotification(OtherSmsNotification $message) + public function handleOtherSmsNotification(OtherSmsNotification $message): void { // ... } @@ -2039,7 +2040,7 @@ To do this, add the ``from_transport`` option to each handler. For example:: #[AsMessageHandler(fromTransport: 'image_transport')] class ThumbnailUploadedImageHandler { - public function __invoke(UploadedImage $uploadedImage) + public function __invoke(UploadedImage $uploadedImage): void { // do some thumbnailing } @@ -2146,7 +2147,7 @@ provided in order to ease the declaration of these special handlers:: { use BatchHandlerTrait; - public function __invoke(MyMessage $message, Acknowledger $ack = null) + public function __invoke(MyMessage $message, Acknowledger $ack = null): mixed { return $this->handle($message, $ack); } @@ -2201,7 +2202,7 @@ to your message:: use Symfony\Component\Messenger\MessageBusInterface; use Symfony\Component\Messenger\Stamp\DelayStamp; - public function index(MessageBusInterface $bus) + public function index(MessageBusInterface $bus): void { $bus->dispatch(new SmsNotification('...'), [ // wait 5 seconds before processing diff --git a/messenger/dispatch_after_current_bus.rst b/messenger/dispatch_after_current_bus.rst index 28a449d70cb..ae810a7fee1 100644 --- a/messenger/dispatch_after_current_bus.rst +++ b/messenger/dispatch_after_current_bus.rst @@ -60,7 +60,7 @@ using the ``DispatchAfterCurrentBusMiddleware`` and adding a ) { } - public function __invoke(RegisterUser $command) + public function __invoke(RegisterUser $command): void { $user = new User($command->getUuid(), $command->getName(), $command->getEmail()); $this->em->persist($user); @@ -97,7 +97,7 @@ using the ``DispatchAfterCurrentBusMiddleware`` and adding a ) { } - public function __invoke(UserRegistered $event) + public function __invoke(UserRegistered $event): void { $user = $this->em->getRepository(User::class)->find($event->getUuid()); diff --git a/messenger/handler_results.rst b/messenger/handler_results.rst index e7bae04cbea..39bab140a58 100644 --- a/messenger/handler_results.rst +++ b/messenger/handler_results.rst @@ -50,7 +50,7 @@ handler is registered. The ``HandleTrait`` can be used in any class that has a ) { } - public function __invoke() + public function __invoke(): void { $result = $this->query(new ListItemsQuery(/* ... */)); diff --git a/migration.rst b/migration.rst index 4c1286125da..5be3ea51834 100644 --- a/migration.rst +++ b/migration.rst @@ -410,7 +410,7 @@ component:: { // ... - public function load($resource, $type = null) + public function load($resource, $type = null): RouteCollection { $collection = new RouteCollection(); $finder = new Finder(); diff --git a/notifier.rst b/notifier.rst index 84b74d7bcf1..887909824ca 100644 --- a/notifier.rst +++ b/notifier.rst @@ -163,6 +163,7 @@ send SMS messages:: // src/Controller/SecurityController.php namespace App\Controller; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Notifier\Message\SmsMessage; use Symfony\Component\Notifier\TexterInterface; use Symfony\Component\Routing\Annotation\Route; @@ -170,7 +171,7 @@ send SMS messages:: class SecurityController { #[Route('/login/success')] - public function loginSuccess(TexterInterface $texter) + public function loginSuccess(TexterInterface $texter): Response { $sms = new SmsMessage( // the phone number to send the SMS message to @@ -294,6 +295,7 @@ you to send messages to chat services:: namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Notifier\ChatterInterface; use Symfony\Component\Notifier\Message\ChatMessage; use Symfony\Component\Routing\Annotation\Route; @@ -303,7 +305,7 @@ you to send messages to chat services:: /** * @Route("/checkout/thankyou") */ - public function thankyou(ChatterInterface $chatter) + public function thankyou(ChatterInterface $chatter): Response { $message = (new ChatMessage('You got a new invoice for 15 EUR.')) // if not set explicitly, the message is sent to the @@ -543,6 +545,7 @@ To send a notification, autowire the // src/Controller/InvoiceController.php namespace App\Controller; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Notifier\Notification\Notification; use Symfony\Component\Notifier\NotifierInterface; use Symfony\Component\Notifier\Recipient\Recipient; @@ -550,7 +553,7 @@ To send a notification, autowire the class InvoiceController extends AbstractController { #[Route('/invoice/create')] - public function create(NotifierInterface $notifier) + public function create(NotifierInterface $notifier): Response { // ... @@ -677,7 +680,7 @@ sent using the Slack transport:: class InvoiceController extends AbstractController { #[Route('/invoice/create')] - public function invoice(NotifierInterface $notifier) + public function invoice(NotifierInterface $notifier): Response { // ... @@ -712,7 +715,7 @@ very high and the recipient has a phone number:: ) { } - public function getChannels(RecipientInterface $recipient) + public function getChannels(RecipientInterface $recipient): array { if ( $this->price > 10000 diff --git a/performance.rst b/performance.rst index a0a7847dcd3..eb52a796515 100644 --- a/performance.rst +++ b/performance.rst @@ -250,7 +250,7 @@ and Symfony will inject the ``debug.stopwatch`` service:: ) { } - public function export() + public function export(): void { // the argument is the name of the "profiling event" $this->stopwatch->start('export-data'); diff --git a/profiler.rst b/profiler.rst index 772a01d21c3..caae5993093 100644 --- a/profiler.rst +++ b/profiler.rst @@ -126,7 +126,7 @@ class in your controllers to manage the profiler programmatically:: { // ... - public function someMethod(?Profiler $profiler) + public function someMethod(?Profiler $profiler): Response { // $profiler won't be set if your environment doesn't have the profiler (like prod, by default) if (null !== $profiler) { @@ -230,7 +230,7 @@ event:: // ... - public function onKernelResponse(ResponseEvent $event) + public function onKernelResponse(ResponseEvent $event): void { if (!$this->kernel->isDebug()) { return; @@ -274,7 +274,7 @@ request:: class RequestCollector extends AbstractDataCollector { - public function collect(Request $request, Response $response, \Throwable $exception = null) + public function collect(Request $request, Response $response, \Throwable $exception = null): void { $this->data = [ 'method' => $request->getMethod(), @@ -341,6 +341,7 @@ template access to the collected information:: namespace App\DataCollector; use Symfony\Bundle\FrameworkBundle\DataCollector\AbstractDataCollector; + use Symfony\Component\VarDumper\Cloner\Data; class RequestCollector extends AbstractDataCollector { @@ -351,17 +352,17 @@ template access to the collected information:: return 'data_collector/template.html.twig'; } - public function getMethod() + public function getMethod(): string { return $this->data['method']; } - public function getAcceptableContentTypes() + public function getAcceptableContentTypes(): array { return $this->data['acceptable_content_types']; } - public function getSomeObject() + public function getSomeObject(): Data { // use the cloneVar() method to dump collected data in the profiler return $this->cloneVar($this->data['method']); diff --git a/quick_tour/the_architecture.rst b/quick_tour/the_architecture.rst index 34413aec55e..a91cb8dc616 100644 --- a/quick_tour/the_architecture.rst +++ b/quick_tour/the_architecture.rst @@ -175,7 +175,7 @@ that extends ``AbstractExtension``:: ) { } - public function getFilters() + public function getFilters(): array { return [ new TwigFilter('greet', [$this, 'greetUser']), diff --git a/rate_limiter.rst b/rate_limiter.rst index 0ce381fb9b5..d89b17c9f46 100644 --- a/rate_limiter.rst +++ b/rate_limiter.rst @@ -222,6 +222,7 @@ the number of requests to the API:: use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException; use Symfony\Component\RateLimiter\RateLimiterFactory; @@ -229,7 +230,7 @@ the number of requests to the API:: { // if you're using service autowiring, the variable name must be: // "rate limiter name" (in camelCase) + "Limiter" suffix - public function index(Request $request, RateLimiterFactory $anonymousApiLimiter) + public function index(Request $request, RateLimiterFactory $anonymousApiLimiter): Response { // create a limiter based on a unique identifier of the client // (e.g. the client's IP address, a username/email, an API key, etc.) @@ -271,11 +272,12 @@ using the ``reserve()`` method:: use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\RateLimiter\RateLimiterFactory; class ApiController extends AbstractController { - public function registerUser(Request $request, RateLimiterFactory $authenticatedApiLimiter) + public function registerUser(Request $request, RateLimiterFactory $authenticatedApiLimiter): Response { $apiKey = $request->headers->get('apikey'); $limiter = $authenticatedApiLimiter->create($apiKey); @@ -334,7 +336,7 @@ the :class:`Symfony\\Component\\RateLimiter\\Reservation` object returned by the class ApiController extends AbstractController { - public function index(Request $request, RateLimiterFactory $anonymousApiLimiter) + public function index(Request $request, RateLimiterFactory $anonymousApiLimiter): Response { $limiter = $anonymousApiLimiter->create($request->getClientIp()); $limit = $limiter->consume(); diff --git a/reference/configuration/doctrine.rst b/reference/configuration/doctrine.rst index d7ee188f9a4..56c3f1ca1bb 100644 --- a/reference/configuration/doctrine.rst +++ b/reference/configuration/doctrine.rst @@ -157,7 +157,7 @@ you can access it using the ``getConnection()`` method and the name of the conne class SomeController { - public function someMethod(ManagerRegistry $doctrine) + public function someMethod(ManagerRegistry $doctrine): void { $connection = $doctrine->getConnection('customer'); $result = $connection->fetchAll('SELECT name FROM customer'); diff --git a/reference/constraints/Callback.rst b/reference/constraints/Callback.rst index 2a14eff4531..2b6b855eded 100644 --- a/reference/constraints/Callback.rst +++ b/reference/constraints/Callback.rst @@ -39,7 +39,7 @@ Configuration class Author { #[Assert\Callback] - public function validate(ExecutionContextInterface $context, $payload) + public function validate(ExecutionContextInterface $context, $payload): void { // ... } @@ -75,12 +75,12 @@ Configuration class Author { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addConstraint(new Assert\Callback('validate')); } - public function validate(ExecutionContextInterface $context, $payload) + public function validate(ExecutionContextInterface $context, $payload): void { // ... } diff --git a/reference/constraints/Choice.rst b/reference/constraints/Choice.rst index 2ec882298ec..8e3b11a01ce 100644 --- a/reference/constraints/Choice.rst +++ b/reference/constraints/Choice.rst @@ -119,7 +119,7 @@ you can access those choices for validation or for building a select form elemen class Author { - public static function getGenres() + public static function getGenres(): array { return ['fiction', 'non-fiction']; } diff --git a/reference/constraints/Expression.rst b/reference/constraints/Expression.rst index 26192069a8c..593aa4b8ba7 100644 --- a/reference/constraints/Expression.rst +++ b/reference/constraints/Expression.rst @@ -32,12 +32,12 @@ properties:: // ... - public function getCategory() + public function getCategory(): string { return $this->category; } - public function setIsTechnicalPost($isTechnicalPost) + public function setIsTechnicalPost(bool $isTechnicalPost): void { $this->isTechnicalPost = $isTechnicalPost; } @@ -109,7 +109,7 @@ One way to accomplish this is with the Expression constraint: class BlogPost { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addConstraint(new Assert\Expression([ 'expression' => 'this.getCategory() in ["php", "symfony"] or !this.isTechnicalPost()', @@ -202,7 +202,7 @@ assert that the expression must return ``true`` for validation to fail. class BlogPost { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('isTechnicalPost', new Assert\Expression([ 'expression' => 'this.getCategory() in ["php", "symfony"] or value == false', @@ -346,7 +346,7 @@ type (numeric, boolean, strings, null, etc.) class Analysis { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('metric', new Assert\Expression([ 'expression' => 'value + error_margin < threshold', diff --git a/reference/constraints/Json.rst b/reference/constraints/Json.rst index 04cd4d1c1e1..28e15976f3c 100644 --- a/reference/constraints/Json.rst +++ b/reference/constraints/Json.rst @@ -67,7 +67,7 @@ The ``Json`` constraint can be applied to a property or a "getter" method: class Book { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('chapters', new Assert\Json([ 'message' => 'You\'ve entered an invalid Json.', diff --git a/reference/constraints/Traverse.rst b/reference/constraints/Traverse.rst index 0f92c9cce54..56d400fb964 100644 --- a/reference/constraints/Traverse.rst +++ b/reference/constraints/Traverse.rst @@ -194,7 +194,7 @@ disable validating: { // ... - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addConstraint(new Assert\Traverse(false)); } diff --git a/reference/constraints/Ulid.rst b/reference/constraints/Ulid.rst index 59b481b3175..67e4cb35377 100644 --- a/reference/constraints/Ulid.rst +++ b/reference/constraints/Ulid.rst @@ -62,7 +62,7 @@ Basic Usage { // ... - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('identifier', new Assert\Ulid()); } diff --git a/reference/constraints/When.rst b/reference/constraints/When.rst index ed855857b1d..cb5b4c935b2 100644 --- a/reference/constraints/When.rst +++ b/reference/constraints/When.rst @@ -128,7 +128,7 @@ One way to accomplish this is with the When constraint: class Discount { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('value', new Assert\GreaterThan(0)); $metadata->addPropertyConstraint('value', new Assert\When([ @@ -198,7 +198,7 @@ validation based on its value: private ?string $type; // ... - public function doComplexValidation(ExecutionContextInterface $context, $payload) + public function doComplexValidation(ExecutionContextInterface $context, $payload): void { // ... } @@ -250,7 +250,7 @@ validation based on its value: { // ... - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('type', new Assert\When([ 'expression' => 'value == "percent"', @@ -260,7 +260,7 @@ validation based on its value: ])); } - public function doComplexValidation(ExecutionContextInterface $context, $payload) + public function doComplexValidation(ExecutionContextInterface $context, $payload): void { // ... } diff --git a/reference/dic_tags.rst b/reference/dic_tags.rst index 7b953e20e3c..28f79bd7905 100644 --- a/reference/dic_tags.rst +++ b/reference/dic_tags.rst @@ -423,7 +423,7 @@ service class:: class MyClearer implements CacheClearerInterface { - public function clear(string $cacheDirectory) + public function clear(string $cacheDirectory): void { // clear your cache } @@ -490,7 +490,7 @@ the :class:`Symfony\\Component\\HttpKernel\\CacheWarmer\\CacheWarmerInterface` i class MyCustomWarmer implements CacheWarmerInterface { - public function warmUp($cacheDirectory) + public function warmUp($cacheDirectory): array { // ... do some sort of operations to "warm" your cache @@ -506,7 +506,7 @@ the :class:`Symfony\\Component\\HttpKernel\\CacheWarmer\\CacheWarmerInterface` i return $filesAndClassesToPreload; } - public function isOptional() + public function isOptional(): bool { return true; } @@ -642,12 +642,12 @@ the :class:`Symfony\\Contracts\\Translation\\LocaleAwareInterface` interface:: class MyCustomLocaleHandler implements LocaleAwareInterface { - public function setLocale($locale) + public function setLocale(string $locale): void { $this->locale = $locale; } - public function getLocale() + public function getLocale(): string { return $this->locale; } @@ -1106,7 +1106,7 @@ required option: ``alias``, which defines the name of the extractor:: /** * Extracts translation messages from a template directory to the catalog. */ - public function extract(string $directory, MessageCatalogue $catalog) + public function extract(string $directory, MessageCatalogue $catalog): void { // ... } @@ -1114,7 +1114,7 @@ required option: ``alias``, which defines the name of the extractor:: /** * Sets the prefix that should be used for new found messages. */ - public function setPrefix(string $prefix) + public function setPrefix(string $prefix): void { $this->prefix = $prefix; } diff --git a/reference/events.rst b/reference/events.rst index 19678449386..92f917f9115 100644 --- a/reference/events.rst +++ b/reference/events.rst @@ -61,7 +61,7 @@ entirely:: use Symfony\Component\HttpKernel\Event\ControllerEvent; - public function onKernelController(ControllerEvent $event) + public function onKernelController(ControllerEvent $event): void { // ... @@ -93,7 +93,7 @@ found:: use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent; - public function onKernelControllerArguments(ControllerArgumentsEvent $event) + public function onKernelControllerArguments(ControllerArgumentsEvent $event): void { // ... @@ -125,7 +125,7 @@ HTML contents) into the ``Response`` object needed by Symfony:: use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\ViewEvent; - public function onKernelView(ViewEvent $event) + public function onKernelView(ViewEvent $event): void { $value = $event->getControllerResult(); $response = new Response(); @@ -157,7 +157,7 @@ before sending it back (e.g. add/modify HTTP headers, add cookies, etc.):: use Symfony\Component\HttpKernel\Event\ResponseEvent; - public function onKernelResponse(ResponseEvent $event) + public function onKernelResponse(ResponseEvent $event): void { $response = $event->getResponse(); @@ -186,7 +186,7 @@ the translator's locale to the one of the parent request):: use Symfony\Component\HttpKernel\Event\FinishRequestEvent; - public function onKernelFinishRequest(FinishRequestEvent $event) + public function onKernelFinishRequest(FinishRequestEvent $event): void { if (null === $parentRequest = $this->requestStack->getParentRequest()) { return; @@ -238,7 +238,7 @@ sent as response:: use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\ExceptionEvent; - public function onKernelException(ExceptionEvent $event) + public function onKernelException(ExceptionEvent $event): void { $exception = $event->getThrowable(); $response = new Response(); diff --git a/reference/formats/expression_language.rst b/reference/formats/expression_language.rst index a3f3d970419..a7aec281a46 100644 --- a/reference/formats/expression_language.rst +++ b/reference/formats/expression_language.rst @@ -77,7 +77,7 @@ JavaScript:: class Robot { - public function sayHi($times) + public function sayHi(int $times): string { $greetings = []; for ($i = 0; $i < $times; $i++) { diff --git a/reference/forms/types/file.rst b/reference/forms/types/file.rst index 29601e860f8..34230659aff 100644 --- a/reference/forms/types/file.rst +++ b/reference/forms/types/file.rst @@ -33,7 +33,7 @@ be used to move the ``attachment`` file to a permanent location:: use Symfony\Component\HttpFoundation\File\UploadedFile; - public function upload() + public function upload(): Response { // ... diff --git a/routing.rst b/routing.rst index 9047511e719..ff0d4a53c5c 100644 --- a/routing.rst +++ b/routing.rst @@ -2289,7 +2289,7 @@ the :class:`Symfony\\Component\\Routing\\Generator\\UrlGeneratorInterface` class ) { } - public function someMethod() + public function someMethod(): void { // ... @@ -2639,7 +2639,7 @@ service, which you can inject in your services or controllers:: ) { } - public function someMethod() + public function someMethod(): void { // ... diff --git a/routing/custom_route_loader.rst b/routing/custom_route_loader.rst index ec3b5efcb1b..d4ab6880c2e 100644 --- a/routing/custom_route_loader.rst +++ b/routing/custom_route_loader.rst @@ -280,7 +280,7 @@ you do. The resource name itself is not actually used in the example:: { private bool $isLoaded = false; - public function load($resource, string $type = null) + public function load($resource, string $type = null): RouteCollection { if (true === $this->isLoaded) { throw new \RuntimeException('Do not add the "extra" loader twice'); @@ -307,7 +307,7 @@ you do. The resource name itself is not actually used in the example:: return $routes; } - public function supports($resource, string $type = null) + public function supports($resource, string $type = null): bool { return 'extra' === $type; } @@ -324,7 +324,7 @@ have to create an ``extra()`` method in the ``ExtraController``:: class ExtraController extends AbstractController { - public function extra($parameter) + public function extra(mixed $parameter): Response { return new Response($parameter); } @@ -452,7 +452,7 @@ configuration file - you can call the class AdvancedLoader extends Loader { - public function load($resource, string $type = null) + public function load($resource, string $type = null): RouteCollection { $routes = new RouteCollection(); @@ -466,7 +466,7 @@ configuration file - you can call the return $routes; } - public function supports($resource, string $type = null) + public function supports($resource, string $type = null): bool { return 'advanced_extra' === $type; } diff --git a/security.rst b/security.rst index 1daa0325788..e6abdff0696 100644 --- a/security.rst +++ b/security.rst @@ -2362,7 +2362,7 @@ want to include extra details only for users that have a ``ROLE_SALES_ADMIN`` ro + ) { + } - public function generateReport() + public function generateReport(): void { $salesData = []; diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index ec18491005a..b801b5570c1 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -168,7 +168,7 @@ the impersonator user:: ) { } - public function someMethod() + public function someMethod(): void { // ... diff --git a/security/login_link.rst b/security/login_link.rst index 14affeb47cd..4bb9dc28074 100644 --- a/security/login_link.rst +++ b/security/login_link.rst @@ -93,7 +93,7 @@ intercept requests to this route: class SecurityController extends AbstractController { #[Route('/login_check', name: 'login_check')] - public function check() + public function check(): never { throw new \LogicException('This code should never be reached'); } @@ -149,13 +149,14 @@ this interface:: use App\Repository\UserRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\Security\Http\LoginLink\LoginLinkHandlerInterface; class SecurityController extends AbstractController { #[Route('/login', name: 'login')] - public function requestLoginLink(LoginLinkHandlerInterface $loginLinkHandler, UserRepository $userRepository, Request $request) + public function requestLoginLink(LoginLinkHandlerInterface $loginLinkHandler, UserRepository $userRepository, Request $request): Response { // check if login form is submitted if ($request->isMethod('POST')) { @@ -226,7 +227,7 @@ number:: class SecurityController extends AbstractController { #[Route('/login', name: 'login')] - public function requestLoginLink(NotifierInterface $notifier, LoginLinkHandlerInterface $loginLinkHandler, UserRepository $userRepository, Request $request) + public function requestLoginLink(NotifierInterface $notifier, LoginLinkHandlerInterface $loginLinkHandler, UserRepository $userRepository, Request $request): Response { if ($request->isMethod('POST')) { $email = $request->request->get('email'); @@ -615,7 +616,7 @@ user create this POST request (e.g. by clicking a button):: class SecurityController extends AbstractController { #[Route('/login_check', name: 'login_check')] - public function check(Request $request) + public function check(Request $request): Response { // get the login link query parameters $expires = $request->query->get('expires'); @@ -773,7 +774,7 @@ features such as the locale used to generate the link:: class SecurityController extends AbstractController { #[Route('/login', name: 'login')] - public function requestLoginLink(LoginLinkHandlerInterface $loginLinkHandler, Request $request) + public function requestLoginLink(LoginLinkHandlerInterface $loginLinkHandler, Request $request): Response { // check if login form is submitted if ($request->isMethod('POST')) { diff --git a/security/passwords.rst b/security/passwords.rst index c4248ee4eea..6807785a29f 100644 --- a/security/passwords.rst +++ b/security/passwords.rst @@ -209,13 +209,12 @@ After configuring the correct algorithm, you can use the namespace App\Controller; // ... - use - Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; + use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface; class UserController extends AbstractController { - public function registration(UserPasswordHasherInterface $passwordHasher) + public function registration(UserPasswordHasherInterface $passwordHasher): Response { // ... e.g. get the user data from a registration form $user = new User(...); diff --git a/serializer/custom_context_builders.rst b/serializer/custom_context_builders.rst index 77116333384..b40e432286d 100644 --- a/serializer/custom_context_builders.rst +++ b/serializer/custom_context_builders.rst @@ -33,7 +33,7 @@ value is ``0000-00-00``. To do that you'll first have to create your normalizer: { use DenormalizerAwareTrait; - public function denormalize($data, string $type, string $format = null, array $context = []) + public function denormalize($data, string $type, string $format = null, array $context = []): mixed { if ('0000-00-00' === $data) { return null; @@ -44,7 +44,7 @@ value is ``0000-00-00``. To do that you'll first have to create your normalizer: return $this->denormalizer->denormalize($data, $type, $format, $context); } - public function supportsDenormalization($data, string $type, string $format = null, array $context = []) + public function supportsDenormalization($data, string $type, string $format = null, array $context = []): bool { return true === ($context['zero_datetime_to_null'] ?? false) && is_a($type, \DateTimeInterface::class, true); diff --git a/serializer/custom_encoders.rst b/serializer/custom_encoders.rst index 20df58ccb67..6bad3823e9d 100644 --- a/serializer/custom_encoders.rst +++ b/serializer/custom_encoders.rst @@ -25,22 +25,22 @@ create your own encoder that uses the class YamlEncoder implements EncoderInterface, DecoderInterface { - public function encode($data, string $format, array $context = []) + public function encode($data, string $format, array $context = []): string { return Yaml::dump($data); } - public function supportsEncoding(string $format, array $context = []) + public function supportsEncoding(string $format, array $context = []): bool { return 'yaml' === $format; } - public function decode(string $data, string $format, array $context = []) + public function decode(string $data, string $format, array $context = []): array { return Yaml::parse($data); } - public function supportsDecoding(string $format, array $context = []) + public function supportsDecoding(string $format, array $context = []): bool { return 'yaml' === $format; } diff --git a/serializer/custom_normalizer.rst b/serializer/custom_normalizer.rst index bc94772b2a5..74f73461833 100644 --- a/serializer/custom_normalizer.rst +++ b/serializer/custom_normalizer.rst @@ -30,7 +30,7 @@ to customize the normalized data. To do that, leverage the ``ObjectNormalizer``: ) { } - public function normalize($topic, string $format = null, array $context = []) + public function normalize($topic, string $format = null, array $context = []): array { $data = $this->normalizer->normalize($topic, $format, $context); @@ -42,7 +42,7 @@ to customize the normalized data. To do that, leverage the ``ObjectNormalizer``: return $data; } - public function supportsNormalization($data, string $format = null, array $context = []) + public function supportsNormalization($data, string $format = null, array $context = []): bool { return $data instanceof Topic; } diff --git a/service_container/autowiring.rst b/service_container/autowiring.rst index 72bb7851965..722df00215b 100644 --- a/service_container/autowiring.rst +++ b/service_container/autowiring.rst @@ -689,7 +689,7 @@ typed properties: #[Required] public LoggerInterface $logger; - public function transform($value) + public function transform($value): void { $this->logger->info('Transforming '.$value); // ... diff --git a/service_container/request.rst b/service_container/request.rst index 379d065acb2..1abb289983f 100644 --- a/service_container/request.rst +++ b/service_container/request.rst @@ -19,7 +19,7 @@ method:: ) { } - public function anyMethod() + public function anyMethod(): void { $request = $this->requestStack->getCurrentRequest(); // ... do something with the request diff --git a/service_container/service_subscribers_locators.rst b/service_container/service_subscribers_locators.rst index 30dbace8e30..6c3f9d09b8b 100644 --- a/service_container/service_subscribers_locators.rst +++ b/service_container/service_subscribers_locators.rst @@ -34,7 +34,7 @@ to handle their respective command when it is asked for:: ) { } - public function handle(Command $command) + public function handle(Command $command): mixed { $commandClass = get_class($command); @@ -92,7 +92,7 @@ in the service subscriber:: ]; } - public function handle(Command $command) + public function handle(Command $command): mixed { $commandClass = get_class($command); @@ -638,7 +638,7 @@ Inside this locator you can retrieve services by index using the value of the class HandlerCollection { - public function getHandlerTwo(ContainerInterface $locator) + public function getHandlerTwo(ContainerInterface $locator): mixed { return $locator->get('handler_two'); } @@ -757,7 +757,7 @@ services based on type-hinted helper methods:: { use ServiceSubscriberTrait; - public function doSomething() + public function doSomething(): void { // $this->router() ... // $this->logger() ... @@ -819,7 +819,7 @@ and compose your services with them:: { use ServiceSubscriberTrait, LoggerAware, RouterAware; - public function doSomething() + public function doSomething(): void { // $this->router() ... // $this->logger() ... @@ -865,7 +865,7 @@ Here's an example:: { use ServiceSubscriberTrait; - public function doSomething() + public function doSomething(): void { // $this->environment() ... // $this->router() ... diff --git a/session.rst b/session.rst index ed7ca1fb7b9..85f3d5542c8 100644 --- a/session.rst +++ b/session.rst @@ -49,7 +49,7 @@ if you type-hint an argument with :class:`Symfony\\Component\\HttpFoundation\\Re // $this->session = $requestStack->getSession(); } - public function someMethod() + public function someMethod(): void { $session = $this->requestStack->getSession(); @@ -1319,7 +1319,7 @@ can determine the correct locale however you want:: ) { } - public function onKernelRequest(RequestEvent $event) + public function onKernelRequest(RequestEvent $event): void { $request = $event->getRequest(); if (!$request->hasPreviousSession()) { @@ -1335,7 +1335,7 @@ can determine the correct locale however you want:: } } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ // must be registered before (i.e. with a higher priority than) the default Locale listener @@ -1410,7 +1410,7 @@ Remember, to get the user's locale, always use the :method:`Request::getLocale // from a controller... use Symfony\Component\HttpFoundation\Request; - public function index(Request $request) + public function index(Request $request): void { $locale = $request->getLocale(); } @@ -1451,7 +1451,7 @@ event:: ) { } - public function onInteractiveLogin(InteractiveLoginEvent $event) + public function onInteractiveLogin(InteractiveLoginEvent $event): void { $user = $event->getAuthenticationToken()->getUser(); @@ -1460,7 +1460,7 @@ event:: } } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin', diff --git a/templates.rst b/templates.rst index 182f3d759a6..9e927161155 100644 --- a/templates.rst +++ b/templates.rst @@ -580,7 +580,7 @@ to define the template to render:: class ProductController extends AbstractController { #[Template('product/index.html.twig')] - public function index() + public function index(): array { // ... @@ -618,7 +618,7 @@ the :class:`Twig\\Environment` class:: ) { } - public function someMethod() + public function someMethod(): void { // ... @@ -1449,14 +1449,14 @@ Create a class that extends ``AbstractExtension`` and fill in the logic:: class AppExtension extends AbstractExtension { - public function getFilters() + public function getFilters(): array { return [ new TwigFilter('price', [$this, 'formatPrice']), ]; } - public function formatPrice($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',') + public function formatPrice(float $number, int $decimals = 0, string $decPoint = '.', string $thousandsSep = ','): string { $price = number_format($number, $decimals, $decPoint, $thousandsSep); $price = '$'.$price; @@ -1476,14 +1476,14 @@ If you want to create a function instead of a filter, define the class AppExtension extends AbstractExtension { - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('area', [$this, 'calculateArea']), ]; } - public function calculateArea(int $width, int $length) + public function calculateArea(int $width, int $length): int { return $width * $length; } @@ -1541,7 +1541,7 @@ callable defined in ``getFilters()``:: class AppExtension extends AbstractExtension { - public function getFilters() + public function getFilters(): array { return [ // the logic of this filter is now implemented in a different class @@ -1567,7 +1567,7 @@ previous ``formatPrice()`` method:: // extensions, you'll need to inject services using this constructor } - public function formatPrice($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',') + public function formatPrice(float $number, int $decimals = 0, string $decPoint = '.', string $thousandsSep = ','): string { $price = number_format($number, $decimals, $decPoint, $thousandsSep); $price = '$'.$price; diff --git a/testing.rst b/testing.rst index a2e10e8938c..a41d789cc76 100644 --- a/testing.rst +++ b/testing.rst @@ -120,7 +120,7 @@ class to help you creating and booting the kernel in your tests using class NewsletterGeneratorTest extends KernelTestCase { - public function testSomething() + public function testSomething(): void { self::bootKernel(); @@ -254,7 +254,7 @@ the container is returned by ``static::getContainer()``:: class NewsletterGeneratorTest extends KernelTestCase { - public function testSomething() + public function testSomething(): void { // (1) boot the Symfony kernel self::bootKernel(); @@ -295,7 +295,7 @@ concrete one:: class NewsletterGeneratorTest extends KernelTestCase { - public function testSomething() + public function testSomething(): void { // ... same bootstrap as the section above @@ -473,7 +473,7 @@ instance, to load ``Product`` objects into Doctrine, use:: class ProductFixture extends Fixture { - public function load(ObjectManager $manager) + public function load(ObjectManager $manager): void { $product = new Product(); $product->setName('Priceless widget'); @@ -690,7 +690,7 @@ to simulate a login request:: { // ... - public function testVisitingWhileLoggedIn() + public function testVisitingWhileLoggedIn(): void { $client = static::createClient(); $userRepository = static::getContainer()->get(UserRepository::class); diff --git a/testing/database.rst b/testing/database.rst index bce96353da8..97b2f3fdfd5 100644 --- a/testing/database.rst +++ b/testing/database.rst @@ -29,7 +29,7 @@ Suppose the class you want to test looks like this:: ) { } - public function calculateTotalSalary($id) + public function calculateTotalSalary(int $id): int { $employeeRepository = $this->objectManager ->getRepository(Employee::class); @@ -53,7 +53,7 @@ constructor, you can pass a mock object within a test:: class SalaryCalculatorTest extends TestCase { - public function testCalculateTotalSalary() + public function testCalculateTotalSalary(): void { $employee = new Employee(); $employee->setSalary(1000); @@ -109,7 +109,7 @@ so, get the entity manager via the service container as follows:: ->getManager(); } - public function testSearchByName() + public function testSearchByName(): void { $product = $this->entityManager ->getRepository(Product::class) diff --git a/testing/profiling.rst b/testing/profiling.rst index 3c0184b604c..085cd100c2d 100644 --- a/testing/profiling.rst +++ b/testing/profiling.rst @@ -73,7 +73,7 @@ provided by the collectors obtained through the ``$client->getProfile()`` call:: class LuckyControllerTest extends WebTestCase { - public function testRandomNumber() + public function testRandomNumber(): void { $client = static::createClient(); diff --git a/translation.rst b/translation.rst index fea7e865cf4..ae885eb69ca 100644 --- a/translation.rst +++ b/translation.rst @@ -120,7 +120,7 @@ controller:: // ... use Symfony\Contracts\Translation\TranslatorInterface; - public function index(TranslatorInterface $translator) + public function index(TranslatorInterface $translator): Response { $translated = $translator->trans('Symfony is great'); @@ -749,7 +749,7 @@ is stored in the request and is accessible via the ``Request`` object:: use Symfony\Component\HttpFoundation\Request; - public function index(Request $request) + public function index(Request $request): void { $locale = $request->getLocale(); } @@ -758,7 +758,7 @@ To set the user's locale, you may want to create a custom event listener so that it's set before any other parts of the system (i.e. the translator) need it:: - public function onKernelRequest(RequestEvent $event) + public function onKernelRequest(RequestEvent $event): void { $request = $event->getRequest(); @@ -819,8 +819,9 @@ A better policy is to include the locale in the URL using the '_locale' => 'en|fr|de', ], )] - public function contact() + public function contact(): Response { + // ... } } @@ -1021,7 +1022,7 @@ of: ) { } - public function someMethod() + public function someMethod(): void { // you can get the current application locale like this: $currentLocale = $this->localeSwitcher->getLocale(); diff --git a/validation/custom_constraint.rst b/validation/custom_constraint.rst index 105a6b5afdc..b1c50f0511d 100644 --- a/validation/custom_constraint.rst +++ b/validation/custom_constraint.rst @@ -67,7 +67,7 @@ class is specified by the constraint's ``validatedBy()`` method, which has this default logic:: // in the base Symfony\Component\Validator\Constraint class - public function validatedBy() + public function validatedBy(): string { return static::class.'Validator'; } @@ -359,16 +359,17 @@ class to simplify writing unit tests for your custom constraints:: use App\Validator\ContainsAlphanumeric; use App\Validator\ContainsAlphanumericValidator; + use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; class ContainsAlphanumericValidatorTest extends ConstraintValidatorTestCase { - protected function createValidator() + protected function createValidator(): ConstraintValidatorInterface { return new ContainsAlphanumericValidator(); } - public function testNullIsValid() + public function testNullIsValid(): void { $this->validator->validate(null, new ContainsAlphanumeric()); @@ -378,7 +379,7 @@ class to simplify writing unit tests for your custom constraints:: /** * @dataProvider provideInvalidConstraints */ - public function testTrueIsInvalid(ContainsAlphanumeric $constraint) + public function testTrueIsInvalid(ContainsAlphanumeric $constraint): void { $this->validator->validate('...', $constraint); diff --git a/validation/groups.rst b/validation/groups.rst index 22af24473be..3842c781969 100644 --- a/validation/groups.rst +++ b/validation/groups.rst @@ -99,7 +99,7 @@ user registers and when a user updates their contact information later: class User { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('email', new Assert\Email([ 'groups' => ['registration'], diff --git a/validation/raw_values.rst b/validation/raw_values.rst index b863d9ee3ed..9c900ff2b36 100644 --- a/validation/raw_values.rst +++ b/validation/raw_values.rst @@ -10,7 +10,7 @@ address. From inside a controller, it looks like this:: use Symfony\Component\Validator\Validator\ValidatorInterface; // ... - public function addEmail($email, ValidatorInterface $validator) + public function addEmail(string $email, ValidatorInterface $validator): void { $emailConstraint = new Assert\Email(); // all constraint "options" can be set this way diff --git a/validation/sequence_provider.rst b/validation/sequence_provider.rst index d409b1a203a..2a06e661034 100644 --- a/validation/sequence_provider.rst +++ b/validation/sequence_provider.rst @@ -32,7 +32,7 @@ username and the password are different only if all other validation passes message: 'The password cannot match your username', groups: ['Strict'], )] - public function isPasswordSafe() + public function isPasswordSafe(): bool { return ($this->username !== $this->password); } @@ -99,7 +99,7 @@ username and the password are different only if all other validation passes class User { - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('username', new Assert\NotBlank()); $metadata->addPropertyConstraint('password', new Assert\NotBlank()); @@ -151,7 +151,7 @@ You can also define a group sequence in the ``validation_groups`` form option:: class MyType extends AbstractType { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'validation_groups' => new GroupSequence(['First', 'Second']), @@ -246,7 +246,7 @@ entity and a new constraint group called ``Premium``: // ... - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->addPropertyConstraint('name', new Assert\NotBlank()); $metadata->addPropertyConstraint('creditCard', new Assert\CardScheme([ @@ -337,7 +337,7 @@ provides a sequence of groups to be validated: { // ... - public static function loadValidatorMetadata(ClassMetadata $metadata) + public static function loadValidatorMetadata(ClassMetadata $metadata): void { $metadata->setGroupSequenceProvider(true); // ... diff --git a/web_link.rst b/web_link.rst index fb81376cba3..757821094e3 100644 --- a/web_link.rst +++ b/web_link.rst @@ -155,12 +155,13 @@ You can also add links to the HTTP response directly from controllers and servic use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\WebLink\GenericLinkProvider; use Symfony\Component\WebLink\Link; class BlogController extends AbstractController { - public function index(Request $request) + public function index(Request $request): Response { // using the addLink() shortcut provided by AbstractController $this->addLink($request, new Link('preload', '/app.css')); diff --git a/workflow/workflow-and-state-machine.rst b/workflow/workflow-and-state-machine.rst index f30d26397d1..12ee935cd8a 100644 --- a/workflow/workflow-and-state-machine.rst +++ b/workflow/workflow-and-state-machine.rst @@ -268,7 +268,7 @@ machine type, use ``camelCased workflow name + StateMachine``:: ) { } - public function someMethod(PullRequest $pullRequest) + public function someMethod(PullRequest $pullRequest): void { $this->pullRequestWorkflow->apply($pullRequest, 'wait_for_review', [ 'log_comment' => 'My logging comment for the wait for review transition.',