From 23dc0985f8fb2f5e2b2533d51321517fbabde3ff Mon Sep 17 00:00:00 2001 From: Wouter de Jong Date: Sat, 21 Nov 2020 17:47:51 +0100 Subject: [PATCH] [Console][Mailer][Security] Added PHP type declarations --- console.rst | 18 ++++----- console/calling_commands.rst | 44 +++++++++++---------- console/command_in_controller.rst | 4 +- console/commands_as_services.rst | 6 +-- console/hide_commands.rst | 2 +- console/input.rst | 6 ++- console/lockable_trait.rst | 2 +- console/style.rst | 6 +-- console/verbosity.rst | 4 +- mailer.rst | 3 +- security.rst | 12 +++--- security/access_denied_handler.rst | 2 +- security/csrf.rst | 7 ++-- security/custom_authentication_provider.rst | 24 +++++------ security/expressions.rst | 4 +- security/form_login.rst | 4 +- security/form_login_setup.rst | 17 ++++---- security/guard_authentication.rst | 20 +++++----- security/impersonating_user.rst | 8 ++-- security/json_login_setup.rst | 2 +- security/named_encoders.rst | 2 +- security/remember_me.rst | 4 +- security/user_checkers.rst | 4 +- security/user_provider.rst | 3 +- security/voters.rst | 16 ++++---- 25 files changed, 119 insertions(+), 105 deletions(-) diff --git a/console.rst b/console.rst index e980cea046a..ad47c0c6879 100644 --- a/console.rst +++ b/console.rst @@ -38,12 +38,12 @@ want a command to create a user:: // the name of the command (the part after "bin/console") protected static $defaultName = 'app:create-user'; - protected function configure() + protected function configure(): void { // ... } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { // ... put here the code to create the user @@ -65,7 +65,7 @@ You can optionally define a description, help message and the :doc:`input options and arguments `:: // ... - protected function configure() + protected function configure(): void { $this // the short description shown while running "php bin/console list" @@ -100,7 +100,7 @@ available in the ``configure()`` method:: parent::__construct(); } - protected function configure() + protected function configure(): void { $this // ... @@ -136,7 +136,7 @@ The ``execute()`` method has access to the output stream to write messages to the console:: // ... - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { // outputs multiple lines to the console (adding "\n" at the end of each line) $output->writeln([ @@ -189,7 +189,7 @@ method, which returns an instance of class MyCommand extends Command { - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { if (!$output instanceof ConsoleOutputInterface) { throw new \LogicException('This command accepts only an instance of "ConsoleOutputInterface".'); @@ -236,7 +236,7 @@ Use input options or arguments to pass information to the command:: use Symfony\Component\Console\Input\InputArgument; // ... - protected function configure() + protected function configure(): void { $this // configure an argument @@ -246,7 +246,7 @@ Use input options or arguments to pass information to the command:: } // ... - public function execute(InputInterface $input, OutputInterface $output) + public function execute(InputInterface $input, OutputInterface $output): int { $output->writeln([ 'User Creator', @@ -300,7 +300,7 @@ as a service, you can use normal dependency injection. Imagine you have a // ... - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { // ... diff --git a/console/calling_commands.rst b/console/calling_commands.rst index 0b3919973e5..2defb04d49a 100644 --- a/console/calling_commands.rst +++ b/console/calling_commands.rst @@ -8,36 +8,40 @@ or if you want to create a "meta" command that runs a bunch of other commands changed on the production servers: clearing the cache, generating Doctrine proxies, dumping web assets, ...). -Calling a command from another one is straightforward:: +Use the :method:`Symfony\\Component\\Console\\Application::find` method to +find the command you want to run by passing the command name. Then, create a +new :class:`Symfony\\Component\\Console\\Input\\ArrayInput` with the +arguments and options you want to pass to the command. +Eventually, calling the ``run()`` method actually runs the command and returns +the returned code from the command (return value from command's ``execute()`` +method):: + + // ... + use Symfony\Component\Console\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; - // ... - protected function execute(InputInterface $input, OutputInterface $output) + class CreateUserCommand extends Command { - $command = $this->getApplication()->find('demo:greet'); - - $arguments = [ - 'name' => 'Fabien', - '--yell' => true, - ]; + // ... - $greetInput = new ArrayInput($arguments); - $returnCode = $command->run($greetInput, $output); + protected function execute(InputInterface $input, OutputInterface $output): void + { + $command = $this->getApplication()->find('demo:greet'); - // ... - } + $arguments = [ + 'name' => 'Fabien', + '--yell' => true, + ]; -First, you :method:`Symfony\\Component\\Console\\Application::find` the -command you want to run by passing the command name. Then, you need to create -a new :class:`Symfony\\Component\\Console\\Input\\ArrayInput` with the arguments -and options you want to pass to the command. + $greetInput = new ArrayInput($arguments); + $returnCode = $command->run($greetInput, $output); -Eventually, calling the ``run()`` method actually runs the command and returns -the returned code from the command (return value from command's ``execute()`` -method). + // ... + } + } .. tip:: diff --git a/console/command_in_controller.rst b/console/command_in_controller.rst index 190584bfbda..74cd6b09cbe 100644 --- a/console/command_in_controller.rst +++ b/console/command_in_controller.rst @@ -36,7 +36,7 @@ Run this command from inside your controller via:: class SpoolController extends AbstractController { - public function sendSpool($messages = 10, KernelInterface $kernel) + public function sendSpool(int $messages = 10, KernelInterface $kernel): Response { $application = new Application($kernel); $application->setAutoExit(false); @@ -87,7 +87,7 @@ Now, use it in your controller:: class SpoolController extends AbstractController { - public function sendSpool($messages = 10) + public function sendSpool(int $messages = 10): Response { // ... $output = new BufferedOutput( diff --git a/console/commands_as_services.rst b/console/commands_as_services.rst index fb5e7ff70eb..794ec8f46cb 100644 --- a/console/commands_as_services.rst +++ b/console/commands_as_services.rst @@ -35,17 +35,17 @@ For example, suppose you want to log something from within your command:: parent::__construct(); } - protected function configure() + protected function configure(): void { $this ->setDescription('Good morning!'); } - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $this->logger->info('Waking up the sun'); // ... - + return 0; } } diff --git a/console/hide_commands.rst b/console/hide_commands.rst index db39ca824f8..2f9d2819873 100644 --- a/console/hide_commands.rst +++ b/console/hide_commands.rst @@ -20,7 +20,7 @@ In those cases, you can define the command as **hidden** by setting the { protected static $defaultName = 'app:legacy'; - protected function configure() + protected function configure(): void { $this ->setHidden(true) diff --git a/console/input.rst b/console/input.rst index 0813bad58c5..926a89604cd 100644 --- a/console/input.rst +++ b/console/input.rst @@ -21,7 +21,7 @@ and make the ``name`` argument required:: { // ... - protected function configure() + protected function configure(): void { $this // ... @@ -42,7 +42,7 @@ You now have access to a ``last_name`` argument in your command:: { // ... - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $text = 'Hi '.$input->getArgument('name'); @@ -52,6 +52,8 @@ You now have access to a ``last_name`` argument in your command:: } $output->writeln($text.'!'); + + return 0; } } diff --git a/console/lockable_trait.rst b/console/lockable_trait.rst index 36cd393907c..98c94d82c57 100644 --- a/console/lockable_trait.rst +++ b/console/lockable_trait.rst @@ -22,7 +22,7 @@ that adds two convenient methods to lock and release commands:: // ... - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { if (!$this->lock()) { $output->writeln('The command is already running in another process.'); diff --git a/console/style.rst b/console/style.rst index dd981436e50..79a4971b2c8 100644 --- a/console/style.rst +++ b/console/style.rst @@ -21,7 +21,7 @@ Consider for example the code used to display the title of the following command { // ... - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $output->writeln([ 'Lorem Ipsum Dolor Sit Amet', @@ -62,7 +62,7 @@ title of the command:: { // ... - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { $io = new SymfonyStyle($input, $output); $io->title('Lorem Ipsum Dolor Sit Amet'); @@ -399,7 +399,7 @@ of your commands to change their appearance:: { // ... - protected function execute(InputInterface $input, OutputInterface $output) + protected function execute(InputInterface $input, OutputInterface $output): int { // Before $io = new SymfonyStyle($input, $output); diff --git a/console/verbosity.rst b/console/verbosity.rst index c16737c2b61..7df68d30f23 100644 --- a/console/verbosity.rst +++ b/console/verbosity.rst @@ -49,7 +49,7 @@ level. For example:: { // ... - public function execute(InputInterface $input, OutputInterface $output) + public function execute(InputInterface $input, OutputInterface $output): int { $user = new User(...); @@ -68,6 +68,8 @@ level. For example:: 'Will only be printed in verbose mode or higher', OutputInterface::VERBOSITY_VERBOSE ); + + return 0; } } diff --git a/mailer.rst b/mailer.rst index 42ec190574a..ec13d48e4ba 100644 --- a/mailer.rst +++ b/mailer.rst @@ -226,6 +226,7 @@ and create an :class:`Symfony\\Component\\Mime\\Email` object:: namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Mailer\MailerInterface; use Symfony\Component\Mime\Email; @@ -234,7 +235,7 @@ and create an :class:`Symfony\\Component\\Mime\\Email` object:: /** * @Route("/email") */ - public function sendEmail(MailerInterface $mailer) + public function sendEmail(MailerInterface $mailer): Response { $email = (new Email()) ->from('hello@example.com') diff --git a/security.rst b/security.rst index c0439086b76..490ccef1ce9 100644 --- a/security.rst +++ b/security.rst @@ -644,7 +644,7 @@ You can deny access from inside a controller:: // src/Controller/AdminController.php // ... - public function adminDashboard() + public function adminDashboard(): Response { $this->denyAccessUnlessGranted('ROLE_ADMIN'); @@ -688,7 +688,7 @@ using annotations: + * + * @IsGranted("ROLE_ADMIN") + */ - public function adminDashboard() + public function adminDashboard(): Response { // ... } @@ -735,7 +735,7 @@ role:: // ... - public function adminDashboard() + public function adminDashboard(): Response { $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); @@ -770,7 +770,7 @@ like this: After authentication, the ``User`` object of the current user can be accessed via the ``getUser()`` shortcut:: - public function index() + public function index(): Response { // usually you'll want to make sure the user is authenticated first $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY'); @@ -811,6 +811,8 @@ If you need to get the logged in user from a service, use the { // returns User object or null if not authenticated $user = $this->security->getUser(); + + // ... } } @@ -901,7 +903,7 @@ Next, you'll need to create a route for this URL (but not a controller): /** * @Route("/logout", name="app_logout", methods={"GET"}) */ - public function logout() + public function logout(): void { // controller can be blank: it will never be executed! throw new \Exception('Don\'t forget to activate logout in security.yaml'); diff --git a/security/access_denied_handler.rst b/security/access_denied_handler.rst index 8db53e89421..8492ff24bef 100644 --- a/security/access_denied_handler.rst +++ b/security/access_denied_handler.rst @@ -123,7 +123,7 @@ response):: class AccessDeniedHandler implements AccessDeniedHandlerInterface { - public function handle(Request $request, AccessDeniedException $accessDeniedException) + public function handle(Request $request, AccessDeniedException $accessDeniedException): ?Response { // ... diff --git a/security/csrf.rst b/security/csrf.rst index 9da64168379..d79bb25e7fb 100644 --- a/security/csrf.rst +++ b/security/csrf.rst @@ -85,7 +85,7 @@ this can be customized on a form-by-form basis:: // src/Form/TaskType.php namespace App\Form; - + // ... use App\Entity\Task; use Symfony\Component\OptionsResolver\OptionsResolver; @@ -94,7 +94,7 @@ this can be customized on a form-by-form basis:: { // ... - public function configureOptions(OptionsResolver $resolver) + public function configureOptions(OptionsResolver $resolver): void { $resolver->setDefaults([ 'data_class' => Task::class, @@ -154,9 +154,10 @@ Then, get the value of the CSRF token in the controller action and use the to check its validity:: use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; // ... - public function delete(Request $request) + public function delete(Request $request): Response { $submittedToken = $request->request->get('token'); diff --git a/security/custom_authentication_provider.rst b/security/custom_authentication_provider.rst index d1bdcd564c0..5acd7333f38 100644 --- a/security/custom_authentication_provider.rst +++ b/security/custom_authentication_provider.rst @@ -78,7 +78,7 @@ provider:: $this->setAuthenticated(count($roles) > 0); } - public function getCredentials() + public function getCredentials(): string { return ''; } @@ -123,7 +123,7 @@ set an authenticated token in the token storage if successful:: $this->authenticationManager = $authenticationManager; } - public function __invoke(RequestEvent $event) + public function __invoke(RequestEvent $event): void { $request = $event->getRequest(); @@ -216,7 +216,7 @@ the ``PasswordDigest`` header value matches with the user's password:: $this->cachePool = $cachePool; } - public function authenticate(TokenInterface $token) + public function authenticate(TokenInterface $token): WsseUserToken { $user = $this->userProvider->loadUserByUsername($token->getUsername()); @@ -236,7 +236,7 @@ the ``PasswordDigest`` header value matches with the user's password:: * For more information specific to the logic here, see * https://github.com/symfony/symfony-docs/pull/3134#issuecomment-27699129 */ - protected function validateDigest($digest, $nonce, $created, $secret) + protected function validateDigest($digest, $nonce, $created, $secret): bool { // Check created time is not in the future if (strtotime($created) > time()) { @@ -269,7 +269,7 @@ the ``PasswordDigest`` header value matches with the user's password:: return hash_equals($expected, $digest); } - public function supports(TokenInterface $token) + public function supports(TokenInterface $token): bool { return $token instanceof WsseUserToken; } @@ -307,7 +307,7 @@ create a class which implements class WsseFactory implements SecurityFactoryInterface { - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint): array { $providerId = 'security.authentication.provider.wsse.'.$id; $container @@ -321,17 +321,17 @@ create a class which implements return [$providerId, $listenerId, $defaultEntryPoint]; } - public function getPosition() + public function getPosition(): string { return 'pre_auth'; } - public function getKey() + public function getKey(): string { return 'wsse'; } - public function addConfiguration(NodeDefinition $node) + public function addConfiguration(NodeDefinition $node): void { } } @@ -455,7 +455,7 @@ factory in the kernel:: class Kernel extends BaseKernel { - public function build(ContainerBuilder $container) + public function build(ContainerBuilder $container): void { $extension = $container->getExtension('security'); $extension->addSecurityListenerFactory(new WsseFactory()); @@ -547,7 +547,7 @@ the ``addConfiguration()`` method:: { // ... - public function addConfiguration(NodeDefinition $node) + public function addConfiguration(NodeDefinition $node): void { $node ->children() @@ -568,7 +568,7 @@ in order to put it to use:: class WsseFactory implements SecurityFactoryInterface { - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint): array { $providerId = 'security.authentication.provider.wsse.'.$id; $container diff --git a/security/expressions.rst b/security/expressions.rst index 2ed16878ff2..a74fbb58eaf 100644 --- a/security/expressions.rst +++ b/security/expressions.rst @@ -15,7 +15,7 @@ accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression` object:: use Symfony\Component\ExpressionLanguage\Expression; // ... - public function index() + public function index(): Response { $this->denyAccessUnlessGranted(new Expression( '"ROLE_ADMIN" in roles or (not is_anonymous() and user.isSuperAdmin())' @@ -86,7 +86,7 @@ Additionally, you have access to a number of functions inside the expression: use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; // ... - public function index(AuthorizationCheckerInterface $authorizationChecker) + public function index(AuthorizationCheckerInterface $authorizationChecker): Response { $access1 = $authorizationChecker->isGranted('IS_AUTHENTICATED_REMEMBERED'); diff --git a/security/form_login.rst b/security/form_login.rst index 6cc958fc9eb..46a1c8ee049 100644 --- a/security/form_login.rst +++ b/security/form_login.rst @@ -103,7 +103,7 @@ configuration (``login``): /** * @Route("/login", name="login", methods={"GET", "POST"}) */ - public function login() + public function login(): Response { } } @@ -146,7 +146,7 @@ Great! Next, add the logic to ``login()`` that displays the login form:: // src/Controller/SecurityController.php use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; - public function login(AuthenticationUtils $authenticationUtils) + public function login(AuthenticationUtils $authenticationUtils): Response { // get the login error if there is one $error = $authenticationUtils->getLastAuthenticationError(); diff --git a/security/form_login_setup.rst b/security/form_login_setup.rst index 0e48913a2d9..0725ff3815d 100644 --- a/security/form_login_setup.rst +++ b/security/form_login_setup.rst @@ -80,7 +80,7 @@ class that processes the login submit and 4) updates the main security config fi /** * @Route("/logout", name="app_logout") */ - public function logout() + public function logout(): void { throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.'); } @@ -197,6 +197,7 @@ a traditional HTML form that submits to ``/login``: use Doctrine\ORM\EntityManagerInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; @@ -230,7 +231,7 @@ a traditional HTML form that submits to ``/login``: $this->passwordEncoder = $passwordEncoder; } - public function supports(Request $request) + public function supports(Request $request): bool { return self::LOGIN_ROUTE === $request->attributes->get('_route') && $request->isMethod('POST'); @@ -251,7 +252,7 @@ a traditional HTML form that submits to ``/login``: return $credentials; } - public function getUser($credentials, UserProviderInterface $userProvider) + public function getUser($credentials, UserProviderInterface $userProvider): ?User { $token = new CsrfToken('authenticate', $credentials['csrf_token']); if (!$this->csrfTokenManager->isTokenValid($token)) { @@ -268,7 +269,7 @@ a traditional HTML form that submits to ``/login``: return $user; } - public function checkCredentials($credentials, UserInterface $user) + public function checkCredentials($credentials, UserInterface $user): bool { return $this->passwordEncoder->isPasswordValid($user, $credentials['password']); } @@ -281,7 +282,7 @@ a traditional HTML form that submits to ``/login``: return $credentials['password']; } - public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) + public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): ?Response { if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) { return new RedirectResponse($targetPath); @@ -291,7 +292,7 @@ a traditional HTML form that submits to ``/login``: throw new \Exception('TODO: provide a valid redirect inside '.__FILE__); } - protected function getLoginUrl() + protected function getLoginUrl(): string { return $this->urlGenerator->generate(self::LOGIN_ROUTE); } @@ -380,7 +381,7 @@ be redirected after success: // src/Security/LoginFormAuthenticator.php // ... - public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) + public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): Response { // ... @@ -503,7 +504,7 @@ whenever the user browses a page:: $this->saveTargetPath($this->session, 'main', $request->getUri()); } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ KernelEvents::REQUEST => ['onKernelRequest'] diff --git a/security/guard_authentication.rst b/security/guard_authentication.rst index de4285a653a..11d85732d5d 100644 --- a/security/guard_authentication.rst +++ b/security/guard_authentication.rst @@ -145,7 +145,7 @@ This requires you to implement several methods:: * used for the request. Returning `false` will cause this authenticator * to be skipped. */ - public function supports(Request $request) + public function supports(Request $request): bool { return $request->headers->has('X-AUTH-TOKEN'); } @@ -159,7 +159,7 @@ This requires you to implement several methods:: return $request->headers->get('X-AUTH-TOKEN'); } - public function getUser($credentials, UserProviderInterface $userProvider) + public function getUser($credentials, UserProviderInterface $userProvider): ?UserInterface { if (null === $credentials) { // The token header was empty, authentication fails with HTTP Status @@ -173,7 +173,7 @@ This requires you to implement several methods:: return $userProvider->loadUserByUsername($credentials); } - public function checkCredentials($credentials, UserInterface $user) + public function checkCredentials($credentials, UserInterface $user): bool { // Check credentials - e.g. make sure the password is valid. // In case of an API token, no credential check is needed. @@ -182,13 +182,13 @@ This requires you to implement several methods:: return true; } - public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey) + public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey): ?Response { // on success, let the request continue return null; } - public function onAuthenticationFailure(Request $request, AuthenticationException $exception) + public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { $data = [ // you may want to customize or obfuscate the message first @@ -204,7 +204,7 @@ This requires you to implement several methods:: /** * Called when authentication is needed, but it's not sent */ - public function start(Request $request, AuthenticationException $authException = null) + public function start(Request $request, AuthenticationException $authException = null): Response { $data = [ // you might translate this message @@ -214,7 +214,7 @@ This requires you to implement several methods:: return new JsonResponse($data, Response::HTTP_UNAUTHORIZED); } - public function supportsRememberMe() + public function supportsRememberMe(): bool { return false; } @@ -466,7 +466,7 @@ completes registration. To do that, use your authenticator and a service called class RegistrationController extends AbstractController { - public function register(LoginFormAuthenticator $authenticator, GuardAuthenticatorHandler $guardHandler, Request $request) + public function register(LoginFormAuthenticator $authenticator, GuardAuthenticatorHandler $guardHandler, Request $request): Response { // ... @@ -496,7 +496,7 @@ the user's session is "migrated" to a new session id. This is an edge-case, and unless you're having session or CSRF token issues, you can ignore this. Here is an example of good and bad behavior:: - public function supports(Request $request) + public function supports(Request $request): bool { // GOOD behavior: only authenticate (i.e. return true) on a specific route return 'login_route' === $request->attributes->get('_route') && $request->isMethod('POST'); @@ -532,7 +532,7 @@ are two possible fixes: + $this->security = $security; + } - public function supports(Request $request) + public function supports(Request $request): bool { + // if there is already an authenticated user (likely due to the session) + // then return false and skip authentication: there is no need. diff --git a/security/impersonating_user.rst b/security/impersonating_user.rst index d7c1692ba80..246fc458525 100644 --- a/security/impersonating_user.rst +++ b/security/impersonating_user.rst @@ -276,13 +276,13 @@ logic you want:: $this->security = $security; } - protected function supports($attribute, $subject) + protected function supports($attribute, $subject): bool { return in_array($attribute, ['CAN_SWITCH_USER']) && $subject instanceof UserInterface; } - protected function voteOnAttribute($attribute, $subject, TokenInterface $token) + protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool { $user = $token->getUser(); // if the user is anonymous or if the subject is not a user, do not grant access @@ -334,7 +334,7 @@ you switch users, add an event subscriber on this event:: class SwitchUserSubscriber implements EventSubscriberInterface { - public function onSwitchUser(SwitchUserEvent $event) + public function onSwitchUser(SwitchUserEvent $event): void { $request = $event->getRequest(); @@ -347,7 +347,7 @@ you switch users, add an event subscriber on this event:: } } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ // constant for security.switch_user diff --git a/security/json_login_setup.rst b/security/json_login_setup.rst index d61b82287bc..d30f878bfb3 100644 --- a/security/json_login_setup.rst +++ b/security/json_login_setup.rst @@ -77,7 +77,7 @@ The next step is to configure a route in your app matching this path: /** * @Route("/login", name="login", methods={"POST"}) */ - public function login(Request $request) + public function login(Request $request): Response { $user = $this->getUser(); diff --git a/security/named_encoders.rst b/security/named_encoders.rst index 0cf58d2e53d..381e4a5f27b 100644 --- a/security/named_encoders.rst +++ b/security/named_encoders.rst @@ -125,7 +125,7 @@ the name of the encoder to use:: class User implements UserInterface, EncoderAwareInterface { - public function getEncoderName() + public function getEncoderName(): ?string { if ($this->isAdmin()) { return 'harsh'; diff --git a/security/remember_me.rst b/security/remember_me.rst index 631a6528e43..0f42b792b07 100644 --- a/security/remember_me.rst +++ b/security/remember_me.rst @@ -173,7 +173,7 @@ users to change their password. You can do this by leveraging a few special "rol // src/Controller/AccountController.php // ... - public function accountInfo() + public function accountInfo(): Response { // allow any authenticated user - we don't care if they just // logged in, or are logged in via a remember me cookie @@ -182,7 +182,7 @@ users to change their password. You can do this by leveraging a few special "rol // ... } - public function resetPassword() + public function resetPassword(): Response { // require the user to log in during *this* session // if they were only logged in via a remember me cookie, they diff --git a/security/user_checkers.rst b/security/user_checkers.rst index 068816440ce..ade87408b09 100644 --- a/security/user_checkers.rst +++ b/security/user_checkers.rst @@ -29,7 +29,7 @@ or :class:`Symfony\\Component\\Security\\Core\\Exception\\AuthenticationExceptio class UserChecker implements UserCheckerInterface { - public function checkPreAuth(UserInterface $user) + public function checkPreAuth(UserInterface $user): void { if (!$user instanceof AppUser) { return; @@ -41,7 +41,7 @@ or :class:`Symfony\\Component\\Security\\Core\\Exception\\AuthenticationExceptio } } - public function checkPostAuth(UserInterface $user) + public function checkPostAuth(UserInterface $user): void { if (!$user instanceof AppUser) { return; diff --git a/security/user_provider.rst b/security/user_provider.rst index 05b1215a77c..cdc36be8d85 100644 --- a/security/user_provider.rst +++ b/security/user_provider.rst @@ -129,6 +129,7 @@ interface only requires one method: ``loadUserByUsername($username)``:: // src/Repository/UserRepository.php namespace App\Repository; + use App\Entity\User; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface; @@ -136,7 +137,7 @@ interface only requires one method: ``loadUserByUsername($username)``:: { // ... - public function loadUserByUsername($usernameOrEmail) + public function loadUserByUsername($usernameOrEmail): ?User { $entityManager = $this->getEntityManager(); diff --git a/security/voters.rst b/security/voters.rst index c8daae7ba38..84cbb446704 100644 --- a/security/voters.rst +++ b/security/voters.rst @@ -70,14 +70,14 @@ user can *edit* or *view* the object. In your controller, you'll check access wi code like this:: // src/Controller/PostController.php - // ... + // ... class PostController extends AbstractController { /** * @Route("/posts/{id}", name="post_show") */ - public function show($id) + public function show($id): Response { // get a Post object - e.g. query for it $post = ...; @@ -91,7 +91,7 @@ code like this:: /** * @Route("/posts/{id}/edit", name="post_edit") */ - public function edit($id) + public function edit($id): Response { // get a Post object - e.g. query for it $post = ...; @@ -130,7 +130,7 @@ would look like this:: const VIEW = 'view'; const EDIT = 'edit'; - protected function supports($attribute, $subject) + protected function supports($attribute, $subject): bool { // if the attribute isn't one we support, return false if (!in_array($attribute, [self::VIEW, self::EDIT])) { @@ -145,7 +145,7 @@ would look like this:: return true; } - protected function voteOnAttribute($attribute, $subject, TokenInterface $token) + protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool { $user = $token->getUser(); @@ -168,7 +168,7 @@ would look like this:: throw new \LogicException('This code should not be reached!'); } - private function canView(Post $post, User $user) + private function canView(Post $post, User $user): bool { // if they can edit, they can view if ($this->canEdit($post, $user)) { @@ -179,7 +179,7 @@ would look like this:: return !$post->isPrivate(); } - private function canEdit(Post $post, User $user) + private function canEdit(Post $post, User $user): bool { // this assumes that the Post object has a `getOwner()` method return $user === $post->getOwner(); @@ -243,7 +243,7 @@ with ``ROLE_SUPER_ADMIN``:: $this->security = $security; } - protected function voteOnAttribute($attribute, $subject, TokenInterface $token) + protected function voteOnAttribute($attribute, $subject, TokenInterface $token): bool { // ...