Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Specifying no rules or sets still makes changes to codebase #3927

Closed
kbsali opened this issue Aug 7, 2020 · 9 comments
Closed

Specifying no rules or sets still makes changes to codebase #3927

kbsali opened this issue Aug 7, 2020 · 9 comments

Comments

@kbsali
Copy link

kbsali commented Aug 7, 2020

Bug Report

Subject Details
Rector version 0.8.x-dev@49e28b2
Installed as docker rector/rector:latest

I finally managed to get rector to work on our project using docker,
but when processing a subset of our codebase (Doctrine entities) without defining any rule or set, rector still applies changes to annotations, and sometimes break cs style.

Minimal PHP Code Causing Issue

docker run --rm -v $(pwd):/project rector/rector:latest process /project/src/EGB/Bundle/AppBundle/Entity/ --autoload-file=/project/vendor/autoload.php

ends up with changes on all the annotations,
and when dealing with compound indexes it ends up breaking the styling/indentation etc...

diff --git a/src/EGB/Bundle/AppBundle/Entity/Comment.php b/src/EGB/Bundle/AppBundle/Entity/Comment.php
index e08eab2fc6..a5bfed5837 100755
--- a/src/EGB/Bundle/AppBundle/Entity/Comment.php
+++ b/src/EGB/Bundle/AppBundle/Entity/Comment.php
@@ -16,11 +16,11 @@ use EGB\Bundle\AppBundle\Util\StringUtil;
  *     name="Comment",
  *     options={"comment"="Comments about..."},
  *     indexes={
- *         @ORM\Index(name="members", columns={"member_from_id","member_to_id"}),
- *         @ORM\Index(name="created", columns={"created"}),
- *         @ORM\Index(name="approved", columns={"approved"})
- *     },
- * )
+ *         @ORM\Index(name="members", columns={"member_from_id",
+ *         "member_to_id"}), @ORM\Index(name="created",
+ *         columns={"created"}), @ORM\Index(name="approved",
+ *     columns={"approved"})
+ * } )
  * @ORM\Entity(repositoryClass=CommentRepository::class)
  * @ORM\HasLifecycleCallbacks
  */

Expected Behaviour

I would have expected rector to do nothing when no rule or set are defined.

@Aerendir
Copy link
Contributor

Aerendir commented Aug 8, 2020

This is not the case as Rector anyway process files and may change them, also if printing them back with the same content.

But as Rector doesn't take care of styles, the printed code is often ugly.

The best approach would be to apply rector and immediately after the code styles.

You say "breaks cs style": are you speaking of continuous integration? In this case, you should run rector in a job separate than the one that runs style checks.

It is not a good idea to follow a path like this:

  1. Run rector
  2. Fix code styles
  3. Run style cheks

This way, in fact, you miss real style breaks in the code.

The best approach is to rune rector separate from code style.

Another approach would be to run rector after the style checks.

@ostrolucky
Copy link

It gets worse. This issue is not present when you don't specify rules only, but also when you do specify them. Even --only flag doesn't help. This is why Rector is unusable for me. Every time I run it, no matter what I do, it breaks half my codebase with cs rules I never specified to use. Quite contrary, I'm interested only in very few rules (yes, the ones in a set I chose), but this is impossible to setup.

@Aerendir
Copy link
Contributor

You should specify with code examples the changes in code: without them it is impossible to fix the issues.

@ostrolucky
Copy link

I don't want to fix specific cases, I want rector to not apply rules I didn't specify.

@Aerendir
Copy link
Contributor

Yes, I understand.

But to fix those issues we need to know how your code is changed to find what in Rector is doing wrong it’s job.

Post examples from your code, so it is possible to find what is broke in Rector.

@ostrolucky
Copy link

You are probably asking for reproducer? I can give you that.

❯ symfony new --demo demo
* Creating a new Symfony Demo project with Composer
  (running /usr/local/bin/composer create-project symfony/symfony-demo /Users/gabriel.ostrolucky/Documents/demo)

* Setting up the project under Git version control
  (running git init /Users/gabriel.ostrolucky/Documents/demo)


 [OK] Your project is now ready in /Users/gabriel.ostrolucky/Documents/demo


❯ cd demo
❯ docker run -v $(pwd):/project rector/rector:latest process /project/src/ --set symfony50 --autoload-file=/project/vendor/autoload.php --dry-run
Rector 0.8.x-dev@3acacc0
Config file: rector.php

   0/170 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░]   0%
   2/170 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░]   1%
   6/170 [░░░░░░░░░░░░░░░░░░░░░░░░░░░░]   3%
   8/170 [▓░░░░░░░░░░░░░░░░░░░░░░░░░░░]   4%
  15/170 [▓▓░░░░░░░░░░░░░░░░░░░░░░░░░░]   8%
  24/170 [▓▓▓░░░░░░░░░░░░░░░░░░░░░░░░░]  14%
  32/170 [▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░░]  18%
  40/170 [▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░░░░]  23%
  56/170 [▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░░░░]  32%
  72/170 [▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░░░░░░]  42%
  80/170 [▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░░░░]  47%
  96/170 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░░░░]  56%
 112/170 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░░░░]  65%
 128/170 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓░░░░░░░]  75%

29 files with changes
=====================

1) ../project/src/Command/AddUserCommand.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -55,7 +55,7 @@
     /**
      * @var SymfonyStyle
      */
-    private $io;
+    private $symfonyStyle;

     private $entityManager;
     private $passwordEncoder;
@@ -62,14 +62,14 @@
     private $validator;
     private $users;

-    public function __construct(EntityManagerInterface $em, UserPasswordEncoderInterface $encoder, Validator $validator, UserRepository $users)
+    public function __construct(EntityManagerInterface $entityManager, UserPasswordEncoderInterface $userPasswordEncoder, Validator $validator, UserRepository $userRepository)
     {
         parent::__construct();

-        $this->entityManager = $em;
-        $this->passwordEncoder = $encoder;
+        $this->entityManager = $entityManager;
+        $this->passwordEncoder = $userPasswordEncoder;
         $this->validator = $validator;
-        $this->users = $users;
+        $this->users = $userRepository;
     }

     /**
@@ -99,7 +99,7 @@
         // SymfonyStyle is an optional feature that Symfony provides so you can
         // apply a consistent look to the commands of your application.
         // See https://symfony.com/doc/current/console/style.html
-        $this->io = new SymfonyStyle($input, $output);
+        $this->symfonyStyle = new SymfonyStyle($input, $output);
     }

     /**
@@ -118,8 +118,8 @@
             return;
         }

-        $this->io->title('Add User Command Interactive Wizard');
-        $this->io->text([
+        $this->symfonyStyle->title('Add User Command Interactive Wizard');
+        $this->symfonyStyle->text([
             'If you prefer to not use this interactive wizard, provide the',
             'arguments required by this command as follows:',
             '',
@@ -131,9 +131,9 @@
         // Ask for the username if it's not defined
         $username = $input->getArgument('username');
         if (null !== $username) {
-            $this->io->text(' > <info>Username</info>: '.$username);
+            $this->symfonyStyle->text(' > <info>Username</info>: '.$username);
         } else {
-            $username = $this->io->ask('Username', null, [$this->validator, 'validateUsername']);
+            $username = $this->symfonyStyle->ask('Username', null, [$this->validator, 'validateUsername']);
             $input->setArgument('username', $username);
         }

@@ -140,9 +140,9 @@
         // Ask for the password if it's not defined
         $password = $input->getArgument('password');
         if (null !== $password) {
-            $this->io->text(' > <info>Password</info>: '.u('*')->repeat(u($password)->length()));
+            $this->symfonyStyle->text(' > <info>Password</info>: '.u('*')->repeat(u($password)->length()));
         } else {
-            $password = $this->io->askHidden('Password (your type will be hidden)', [$this->validator, 'validatePassword']);
+            $password = $this->symfonyStyle->askHidden('Password (your type will be hidden)', [$this->validator, 'validatePassword']);
             $input->setArgument('password', $password);
         }

@@ -149,9 +149,9 @@
         // Ask for the email if it's not defined
         $email = $input->getArgument('email');
         if (null !== $email) {
-            $this->io->text(' > <info>Email</info>: '.$email);
+            $this->symfonyStyle->text(' > <info>Email</info>: '.$email);
         } else {
-            $email = $this->io->ask('Email', null, [$this->validator, 'validateEmail']);
+            $email = $this->symfonyStyle->ask('Email', null, [$this->validator, 'validateEmail']);
             $input->setArgument('email', $email);
         }

@@ -158,9 +158,9 @@
         // Ask for the full name if it's not defined
         $fullName = $input->getArgument('full-name');
         if (null !== $fullName) {
-            $this->io->text(' > <info>Full Name</info>: '.$fullName);
+            $this->symfonyStyle->text(' > <info>Full Name</info>: '.$fullName);
         } else {
-            $fullName = $this->io->ask('Full Name', null, [$this->validator, 'validateFullName']);
+            $fullName = $this->symfonyStyle->ask('Full Name', null, [$this->validator, 'validateFullName']);
             $input->setArgument('full-name', $fullName);
         }
     }
@@ -197,11 +197,11 @@
         $this->entityManager->persist($user);
         $this->entityManager->flush();

-        $this->io->success(sprintf('%s was successfully created: %s (%s)', $isAdmin ? 'Administrator user' : 'User', $user->getUsername(), $user->getEmail()));
+        $this->symfonyStyle->success(sprintf('%s was successfully created: %s (%s)', $isAdmin ? 'Administrator user' : 'User', $user->getUsername(), $user->getEmail()));

-        $event = $stopwatch->stop('add-user-command');
+        $stopwatchEvent = $stopwatch->stop('add-user-command');
         if ($output->isVerbose()) {
-            $this->io->comment(sprintf('New user database id: %d / Elapsed time: %.2f ms / Consumed memory: %.2f MB', $user->getId(), $event->getDuration(), $event->getMemory() / (1024 ** 2)));
+            $this->symfonyStyle->comment(sprintf('New user database id: %d / Elapsed time: %.2f ms / Consumed memory: %.2f MB', $user->getId(), $stopwatchEvent->getDuration(), $stopwatchEvent->getMemory() / (1024 ** 2)));
         }

         return 0;
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Assign\RenameVariableToMatchGetMethodNameRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


2) ../project/src/Command/DeleteUserCommand.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -42,18 +42,18 @@
     protected static $defaultName = 'app:delete-user';

     /** @var SymfonyStyle */
-    private $io;
+    private $symfonyStyle;
     private $entityManager;
     private $validator;
     private $users;

-    public function __construct(EntityManagerInterface $em, Validator $validator, UserRepository $users)
+    public function __construct(EntityManagerInterface $entityManager, Validator $validator, UserRepository $userRepository)
     {
         parent::__construct();

-        $this->entityManager = $em;
+        $this->entityManager = $entityManager;
         $this->validator = $validator;
-        $this->users = $users;
+        $this->users = $userRepository;
     }

     /**
@@ -82,7 +82,7 @@
         // SymfonyStyle is an optional feature that Symfony provides so you can
         // apply a consistent look to the commands of your application.
         // See https://symfony.com/doc/current/console/style.html
-        $this->io = new SymfonyStyle($input, $output);
+        $this->symfonyStyle = new SymfonyStyle($input, $output);
     }

     protected function interact(InputInterface $input, OutputInterface $output)
@@ -91,8 +91,8 @@
             return;
         }

-        $this->io->title('Delete User Command Interactive Wizard');
-        $this->io->text([
+        $this->symfonyStyle->title('Delete User Command Interactive Wizard');
+        $this->symfonyStyle->text([
             'If you prefer to not use this interactive wizard, provide the',
             'arguments required by this command as follows:',
             '',
@@ -102,7 +102,7 @@
             '',
         ]);

-        $username = $this->io->ask('Username', null, [$this->validator, 'validateUsername']);
+        $username = $this->symfonyStyle->ask('Username', null, [$this->validator, 'validateUsername']);
         $input->setArgument('username', $username);
     }

@@ -125,7 +125,7 @@
         $this->entityManager->remove($user);
         $this->entityManager->flush();

-        $this->io->success(sprintf('User "%s" (ID: %d, email: %s) was successfully deleted.', $user->getUsername(), $userId, $user->getEmail()));
+        $this->symfonyStyle->success(sprintf('User "%s" (ID: %d, email: %s) was successfully deleted.', $user->getUsername(), $userId, $user->getEmail()));

         return 0;
     }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


3) ../project/src/Command/ListUsersCommand.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -46,13 +46,13 @@
     private $emailSender;
     private $users;

-    public function __construct(MailerInterface $mailer, $emailSender, UserRepository $users)
+    public function __construct(MailerInterface $mailer, $emailSender, UserRepository $userRepository)
     {
         parent::__construct();

         $this->mailer = $mailer;
         $this->emailSender = $emailSender;
-        $this->users = $users;
+        $this->users = $userRepository;
     }

     /**
@@ -113,8 +113,8 @@
         // contents before displaying them. This is needed because the command allows
         // to send the list of users via email with the '--send-to' option
         $bufferedOutput = new BufferedOutput();
-        $io = new SymfonyStyle($input, $bufferedOutput);
-        $io->table(
+        $symfonyStyle = new SymfonyStyle($input, $bufferedOutput);
+        $symfonyStyle->table(
             ['ID', 'Full Name', 'Username', 'Email', 'Roles'],
             $usersAsPlainArrays
         );
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


4) ../project/src/Controller/Admin/BlogController.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -50,12 +50,12 @@
      *     could move this annotation to any other controller while maintaining
      *     the route name and therefore, without breaking any existing link.
      *
-     * @Route("/", methods="GET", name="admin_index")
-     * @Route("/", methods="GET", name="admin_post_index")
+     * @Route("/", methods={"GET"}, name="admin_index")
+     * @Route("/", methods={"GET"}, name="admin_post_index")
      */
-    public function index(PostRepository $posts): Response
+    public function index(PostRepository $postRepository): Response
     {
-        $authorPosts = $posts->findBy(['author' => $this->getUser()], ['publishedAt' => 'DESC']);
+        $authorPosts = $postRepository->findBy(['author' => $this->getUser()], ['publishedAt' => 'DESC']);

         return $this->render('admin/blog/index.html.twig', ['posts' => $authorPosts]);
     }
@@ -63,7 +63,7 @@
     /**
      * Creates a new Post entity.
      *
-     * @Route("/new", methods="GET|POST", name="admin_post_new")
+     * @Route("/new", methods={"GET|POST"}, name="admin_post_new")
      *
      * NOTE: the Method annotation is optional, but it's a recommended practice
      * to constraint the HTTP methods each controller responds to (by default
@@ -85,9 +85,9 @@
         // However, we explicitly add it to improve code readability.
         // See https://symfony.com/doc/current/forms.html#processing-forms
         if ($form->isSubmitted() && $form->isValid()) {
-            $em = $this->getDoctrine()->getManager();
-            $em->persist($post);
-            $em->flush();
+            $objectManager = $this->getDoctrine()->getManager();
+            $objectManager->persist($post);
+            $objectManager->flush();

             // Flash messages are used to notify the user about the result of the
             // actions. They are deleted automatically from the session as soon
@@ -111,7 +111,7 @@
     /**
      * Finds and displays a Post entity.
      *
-     * @Route("/{id<\d+>}", methods="GET", name="admin_post_show")
+     * @Route("/{id<\d+>}", methods={"GET"}, name="admin_post_show")
      */
     public function show(Post $post): Response
     {
@@ -127,7 +127,7 @@
     /**
      * Displays a form to edit an existing Post entity.
      *
-     * @Route("/{id<\d+>}/edit", methods="GET|POST", name="admin_post_edit")
+     * @Route("/{id<\d+>}/edit", methods={"GET|POST"}, name="admin_post_edit")
      * @IsGranted("edit", subject="post", message="Posts can only be edited by their authors.")
      */
     public function edit(Request $request, Post $post): Response
@@ -152,7 +152,7 @@
     /**
      * Deletes a Post entity.
      *
-     * @Route("/{id}/delete", methods="POST", name="admin_post_delete")
+     * @Route("/{id}/delete", methods={"POST"}, name="admin_post_delete")
      * @IsGranted("delete", subject="post")
      */
     public function delete(Request $request, Post $post): Response
@@ -166,9 +166,9 @@
         // because foreign key support is not enabled by default in SQLite
         $post->getTags()->clear();

-        $em = $this->getDoctrine()->getManager();
-        $em->remove($post);
-        $em->flush();
+        $objectManager = $this->getDoctrine()->getManager();
+        $objectManager->remove($post);
+        $objectManager->flush();

         $this->addFlash('success', 'post.deleted_successfully');
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Assign\RenameVariableToMatchGetMethodNameRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


5) ../project/src/Controller/BlogController.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -37,9 +37,9 @@
 class BlogController extends AbstractController
 {
     /**
-     * @Route("/", defaults={"page": "1", "_format"="html"}, methods="GET", name="blog_index")
-     * @Route("/rss.xml", defaults={"page": "1", "_format"="xml"}, methods="GET", name="blog_rss")
-     * @Route("/page/{page<[1-9]\d*>}", defaults={"_format"="html"}, methods="GET", name="blog_index_paginated")
+     * @Route("/", defaults={"page"="1", "_format"="html"}, methods={"GET"}, name="blog_index")
+     * @Route("/rss.xml", defaults={"page"="1", "_format"="xml"}, methods={"GET"}, name="blog_rss")
+     * @Route("/page/{page<[1-9]\d*>}", defaults={"_format"="html"}, methods={"GET"}, name="blog_index_paginated")
      * @Cache(smaxage="10")
      *
      * NOTE: For standard formats, Symfony will also automatically choose the best
@@ -46,13 +46,13 @@
      * Content-Type header for the response.
      * See https://symfony.com/doc/current/routing.html#special-parameters
      */
-    public function index(Request $request, int $page, string $_format, PostRepository $posts, TagRepository $tags): Response
+    public function index(Request $request, int $page, string $_format, PostRepository $postRepository, TagRepository $tagRepository): Response
     {
         $tag = null;
         if ($request->query->has('tag')) {
-            $tag = $tags->findOneBy(['name' => $request->query->get('tag')]);
+            $tag = $tagRepository->findOneBy(['name' => $request->query->get('tag')]);
         }
-        $latestPosts = $posts->findLatest($page, $tag);
+        $latestPosts = $postRepository->findLatest($page, $tag);

         // Every template name also has two extensions that specify the format and
         // engine for that template.
@@ -63,7 +63,7 @@
     }

     /**
-     * @Route("/posts/{slug}", methods="GET", name="blog_post")
+     * @Route("/posts/{slug}", methods={"GET"}, name="blog_post")
      *
      * NOTE: The $post controller argument is automatically injected by Symfony
      * after performing a database query looking for a Post with the 'slug'
@@ -83,7 +83,7 @@
     }

     /**
-     * @Route("/comment/{postSlug}/new", methods="POST", name="comment_new")
+     * @Route("/comment/{postSlug}/new", methods={"POST"}, name="comment_new")
      * @IsGranted("IS_AUTHENTICATED_FULLY")
      * @ParamConverter("post", options={"mapping": {"postSlug": "slug"}})
      *
@@ -101,9 +101,9 @@
         $form->handleRequest($request);

         if ($form->isSubmitted() && $form->isValid()) {
-            $em = $this->getDoctrine()->getManager();
-            $em->persist($comment);
-            $em->flush();
+            $objectManager = $this->getDoctrine()->getManager();
+            $objectManager->persist($comment);
+            $objectManager->flush();

             // When an event is dispatched, Symfony notifies it to all the listeners
             // and subscribers registered to it. Listeners can modify the information
@@ -140,9 +140,9 @@
     }

     /**
-     * @Route("/search", methods="GET", name="blog_search")
+     * @Route("/search", methods={"GET"}, name="blog_search")
      */
-    public function search(Request $request, PostRepository $posts): Response
+    public function search(Request $request, PostRepository $postRepository): Response
     {
         if (!$request->isXmlHttpRequest()) {
             return $this->render('blog/search.html.twig');
@@ -150,7 +150,7 @@

         $query = $request->query->get('q', '');
         $limit = $request->query->get('l', 10);
-        $foundPosts = $posts->findBySearchQuery($query, $limit);
+        $foundPosts = $postRepository->findBySearchQuery($query, $limit);

         $results = [];
         foreach ($foundPosts as $post) {
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Assign\RenameVariableToMatchGetMethodNameRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


6) ../project/src/Controller/SecurityController.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Controller;

+use Exception;
 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
@@ -33,7 +34,7 @@
     /**
      * @Route("/login", name="security_login")
      */
-    public function login(Request $request, Security $security, AuthenticationUtils $helper): Response
+    public function login(Request $request, Security $security, AuthenticationUtils $authenticationUtils): Response
     {
         // if user is already logged in, don't display the login page again
         if ($security->isGranted('ROLE_USER')) {
@@ -48,9 +49,9 @@

         return $this->render('security/login.html.twig', [
             // last username entered by the user (if any)
-            'last_username' => $helper->getLastUsername(),
+            'last_username' => $authenticationUtils->getLastUsername(),
             // last authentication error (if any)
-            'error' => $helper->getLastAuthenticationError(),
+            'error' => $authenticationUtils->getLastAuthenticationError(),
         ]);
     }

@@ -64,6 +65,6 @@
      */
     public function logout(): void
     {
-        throw new \Exception('This should never be reached!');
+        throw new Exception('This should never be reached!');
     }
 }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


7) ../project/src/Controller/UserController.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -31,7 +31,7 @@
 class UserController extends AbstractController
 {
     /**
-     * @Route("/edit", methods="GET|POST", name="user_edit")
+     * @Route("/edit", methods={"GET|POST"}, name="user_edit")
      */
     public function edit(Request $request): Response
     {
@@ -55,9 +55,9 @@
     }

     /**
-     * @Route("/change-password", methods="GET|POST", name="user_change_password")
+     * @Route("/change-password", methods={"GET|POST"}, name="user_change_password")
      */
-    public function changePassword(Request $request, UserPasswordEncoderInterface $encoder): Response
+    public function changePassword(Request $request, UserPasswordEncoderInterface $userPasswordEncoder): Response
     {
         $user = $this->getUser();

@@ -65,7 +65,7 @@
         $form->handleRequest($request);

         if ($form->isSubmitted() && $form->isValid()) {
-            $user->setPassword($encoder->encodePassword($user, $form->get('newPassword')->getData()));
+            $user->setPassword($userPasswordEncoder->encodePassword($user, $form->get('newPassword')->getData()));

             $this->getDoctrine()->getManager()->flush();
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


8) ../project/src/DataFixtures/AppFixtures.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\DataFixtures;

+use DateTime;
 use App\Entity\Comment;
 use App\Entity\Post;
 use App\Entity\Tag;
@@ -26,20 +27,20 @@
     private $passwordEncoder;
     private $slugger;

-    public function __construct(UserPasswordEncoderInterface $passwordEncoder, SluggerInterface $slugger)
+    public function __construct(UserPasswordEncoderInterface $userPasswordEncoder, SluggerInterface $slugger)
     {
-        $this->passwordEncoder = $passwordEncoder;
+        $this->passwordEncoder = $userPasswordEncoder;
         $this->slugger = $slugger;
     }

-    public function load(ObjectManager $manager): void
+    public function load(ObjectManager $objectManager): void
     {
-        $this->loadUsers($manager);
-        $this->loadTags($manager);
-        $this->loadPosts($manager);
+        $this->loadUsers($objectManager);
+        $this->loadTags($objectManager);
+        $this->loadPosts($objectManager);
     }

-    private function loadUsers(ObjectManager $manager): void
+    private function loadUsers(ObjectManager $objectManager): void
     {
         foreach ($this->getUserData() as [$fullname, $username, $password, $email, $roles]) {
             $user = new User();
@@ -49,27 +50,27 @@
             $user->setEmail($email);
             $user->setRoles($roles);

-            $manager->persist($user);
+            $objectManager->persist($user);
             $this->addReference($username, $user);
         }

-        $manager->flush();
+        $objectManager->flush();
     }

-    private function loadTags(ObjectManager $manager): void
+    private function loadTags(ObjectManager $objectManager): void
     {
         foreach ($this->getTagData() as $index => $name) {
             $tag = new Tag();
             $tag->setName($name);

-            $manager->persist($tag);
+            $objectManager->persist($tag);
             $this->addReference('tag-'.$name, $tag);
         }

-        $manager->flush();
+        $objectManager->flush();
     }

-    private function loadPosts(ObjectManager $manager): void
+    private function loadPosts(ObjectManager $objectManager): void
     {
         foreach ($this->getPostData() as [$title, $slug, $summary, $content, $publishedAt, $author, $tags]) {
             $post = new Post();
@@ -85,15 +86,15 @@
                 $comment = new Comment();
                 $comment->setAuthor($this->getReference('john_user'));
                 $comment->setContent($this->getRandomText(random_int(255, 512)));
-                $comment->setPublishedAt(new \DateTime('now + '.$i.'seconds'));
+                $comment->setPublishedAt(new DateTime('now + '.$i.'seconds'));

                 $post->addComment($comment);
             }

-            $manager->persist($post);
+            $objectManager->persist($post);
         }

-        $manager->flush();
+        $objectManager->flush();
     }

     private function getUserData(): array
@@ -131,7 +132,7 @@
                 $this->slugger->slug($title)->lower(),
                 $this->getRandomText(),
                 $this->getPostContent(),
-                new \DateTime('now - '.$i.'days'),
+                new DateTime('now - '.$i.'days'),
                 // Ensure that the first post is written by Jane Doe to simplify tests
                 $this->getReference(['jane_admin', 'tom_admin'][0 === $i ? 0 : random_int(0, 1)]),
                 $this->getRandomTags(),
@@ -232,9 +233,9 @@

     private function getRandomTags(): array
     {
-        $tagNames = $this->getTagData();
-        shuffle($tagNames);
-        $selectedTags = \array_slice($tagNames, 0, random_int(2, 4));
+        $tagData = $this->getTagData();
+        shuffle($tagData);
+        $selectedTags = \array_slice($tagData, 0, random_int(2, 4));

         return array_map(function ($tagName) { return $this->getReference('tag-'.$tagName); }, $selectedTags);
     }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Assign\RenameVariableToMatchGetMethodNameRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


9) ../project/src/Entity/Comment.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Entity;

+use DateTime;
 use Doctrine\ORM\Mapping as ORM;
 use function Symfony\Component\String\u;
 use Symfony\Component\Validator\Constraints as Assert;
@@ -62,7 +63,7 @@
     private $content;

     /**
-     * @var \DateTime
+     * @var DateTime
      *
      * @ORM\Column(type="datetime")
      */
@@ -74,11 +75,11 @@
      * @ORM\ManyToOne(targetEntity="App\Entity\User")
      * @ORM\JoinColumn(nullable=false)
      */
-    private $author;
+    private $user;

     public function __construct()
     {
-        $this->publishedAt = new \DateTime();
+        $this->publishedAt = new DateTime();
     }

     /**
@@ -106,12 +107,12 @@
         $this->content = $content;
     }

-    public function getPublishedAt(): \DateTime
+    public function getPublishedAt(): DateTime
     {
         return $this->publishedAt;
     }

-    public function setPublishedAt(\DateTime $publishedAt): void
+    public function setPublishedAt(DateTime $publishedAt): void
     {
         $this->publishedAt = $publishedAt;
     }
@@ -118,12 +119,12 @@

     public function getAuthor(): ?User
     {
-        return $this->author;
+        return $this->user;
     }

-    public function setAuthor(User $author): void
+    public function setAuthor(User $user): void
     {
-        $this->author = $author;
+        $this->user = $user;
     }

     public function getPost(): ?Post
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector


10) ../project/src/Entity/Post.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Entity;

+use DateTime;
 use Doctrine\Common\Collections\ArrayCollection;
 use Doctrine\Common\Collections\Collection;
 use Doctrine\ORM\Mapping as ORM;
@@ -86,7 +87,7 @@
     private $content;

     /**
-     * @var \DateTime
+     * @var DateTime
      *
      * @ORM\Column(type="datetime")
      */
@@ -98,7 +99,7 @@
      * @ORM\ManyToOne(targetEntity="App\Entity\User")
      * @ORM\JoinColumn(nullable=false)
      */
-    private $author;
+    private $user;

     /**
      * @var Comment[]|ArrayCollection
@@ -125,7 +126,7 @@

     public function __construct()
     {
-        $this->publishedAt = new \DateTime();
+        $this->publishedAt = new DateTime();
         $this->comments = new ArrayCollection();
         $this->tags = new ArrayCollection();
     }
@@ -165,12 +166,12 @@
         $this->content = $content;
     }

-    public function getPublishedAt(): \DateTime
+    public function getPublishedAt(): DateTime
     {
         return $this->publishedAt;
     }

-    public function setPublishedAt(\DateTime $publishedAt): void
+    public function setPublishedAt(DateTime $publishedAt): void
     {
         $this->publishedAt = $publishedAt;
     }
@@ -177,12 +178,12 @@

     public function getAuthor(): ?User
     {
-        return $this->author;
+        return $this->user;
     }

-    public function setAuthor(User $author): void
+    public function setAuthor(User $user): void
     {
-        $this->author = $author;
+        $this->user = $user;
     }

     public function getComments(): Collection
@@ -213,9 +214,9 @@
         $this->summary = $summary;
     }

-    public function addTag(Tag ...$tags): void
+    public function addTag(Tag ...$tag): void
     {
-        foreach ($tags as $tag) {
+        foreach ($tag as $tag) {
             if (!$this->tags->contains($tag)) {
                 $this->tags->add($tag);
             }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector


11) ../project/src/Entity/Tag.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Entity;

+use JsonSerializable;
 use Doctrine\ORM\Mapping as ORM;

 /**
@@ -23,7 +24,7 @@
  *
  * @author Yonel Ceruto <[email protected]>
  */
-class Tag implements \JsonSerializable
+class Tag implements JsonSerializable
 {
     /**
      * @var int
    ----------- end diff -----------


12) ../project/src/Entity/User.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Entity;

+use Serializable;
 use Doctrine\ORM\Mapping as ORM;
 use Symfony\Component\Security\Core\User\UserInterface;
 use Symfony\Component\Validator\Constraints as Assert;
@@ -28,7 +29,7 @@
  * @author Ryan Weaver <[email protected]>
  * @author Javier Eguiluz <[email protected]>
  */
-class User implements UserInterface, \Serializable
+class User implements UserInterface, Serializable
 {
     /**
      * @var int
    ----------- end diff -----------


13) ../project/src/EventSubscriber/CheckRequirementsSubscriber.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\EventSubscriber;

+use Exception;
 use Doctrine\DBAL\Exception\DriverException;
 use Doctrine\ORM\EntityManagerInterface;
 use Symfony\Component\Console\ConsoleEvents;
@@ -57,14 +58,14 @@
      * the database and then, it checks if the 'sqlite3' PHP extension is enabled
      * or not to display a better error message.
      */
-    public function handleConsoleError(ConsoleErrorEvent $event): void
+    public function handleConsoleError(ConsoleErrorEvent $consoleErrorEvent): void
     {
         $commandNames = ['doctrine:fixtures:load', 'doctrine:database:create', 'doctrine:schema:create', 'doctrine:database:drop'];

-        if ($event->getCommand() && \in_array($event->getCommand()->getName(), $commandNames, true)) {
+        if ($consoleErrorEvent->getCommand() && \in_array($consoleErrorEvent->getCommand()->getName(), $commandNames, true)) {
             if ($this->isSQLitePlatform() && !\extension_loaded('sqlite3')) {
-                $io = new SymfonyStyle($event->getInput(), $event->getOutput());
-                $io->error('This command requires to have the "sqlite3" PHP extension enabled because, by default, the Symfony Demo application uses SQLite to store its information.');
+                $symfonyStyle = new SymfonyStyle($consoleErrorEvent->getInput(), $consoleErrorEvent->getOutput());
+                $symfonyStyle->error('This command requires to have the "sqlite3" PHP extension enabled because, by default, the Symfony Demo application uses SQLite to store its information.');
             }
         }
     }
@@ -73,9 +74,9 @@
      * This method checks if the triggered exception is related to the database
      * and then, it checks if the required 'sqlite3' PHP extension is enabled.
      */
-    public function handleKernelException(ExceptionEvent $event): void
+    public function handleKernelException(ExceptionEvent $exceptionEvent): void
     {
-        $exception = $event->getThrowable();
+        $exception = $exceptionEvent->getThrowable();
         // Since any exception thrown during a Twig template rendering is wrapped
         // in a Twig_Error_Runtime, we must get the original exception.
         $previousException = $exception->getPrevious();
@@ -85,7 +86,7 @@

         // Check if SQLite is enabled
         if ($isDriverException && $this->isSQLitePlatform() && !\extension_loaded('sqlite3')) {
-            $event->setThrowable(new \Exception('PHP extension "sqlite3" must be enabled because, by default, the Symfony Demo application uses SQLite to store its information.'));
+            $exceptionEvent->setThrowable(new Exception('PHP extension "sqlite3" must be enabled because, by default, the Symfony Demo application uses SQLite to store its information.'));
         }
     }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


14) ../project/src/EventSubscriber/CommentNotificationSubscriber.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -46,10 +46,10 @@
         ];
     }

-    public function onCommentCreated(CommentCreatedEvent $event): void
+    public function onCommentCreated(CommentCreatedEvent $commentCreatedEvent): void
     {
         /** @var Comment $comment */
-        $comment = $event->getComment();
+        $comment = $commentCreatedEvent->getComment();
         $post = $comment->getPost();

         $linkToPost = $this->urlGenerator->generate('blog_post', [
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


15) ../project/src/EventSubscriber/ControllerSubscriber.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -27,9 +27,9 @@
 {
     private $twigExtension;

-    public function __construct(SourceCodeExtension $twigExtension)
+    public function __construct(SourceCodeExtension $sourceCodeExtension)
     {
-        $this->twigExtension = $twigExtension;
+        $this->twigExtension = $sourceCodeExtension;
     }

     public static function getSubscribedEvents(): array
@@ -39,13 +39,13 @@
         ];
     }

-    public function registerCurrentController(ControllerEvent $event): void
+    public function registerCurrentController(ControllerEvent $controllerEvent): void
     {
         // this check is needed because in Symfony a request can perform any
         // number of sub-requests. See
         // https://symfony.com/doc/current/components/http_kernel.html#sub-requests
-        if ($event->isMasterRequest()) {
-            $this->twigExtension->setController($event->getController());
+        if ($controllerEvent->isMasterRequest()) {
+            $this->twigExtension->setController($controllerEvent->getController());
         }
     }
 }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


16) ../project/src/EventSubscriber/RedirectToPreferredLocaleSubscriber.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\EventSubscriber;

+use UnexpectedValueException;
 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
 use Symfony\Component\HttpFoundation\RedirectResponse;
 use Symfony\Component\HttpKernel\Event\RequestEvent;
@@ -38,13 +39,13 @@

         $this->locales = explode('|', trim($locales));
         if (empty($this->locales)) {
-            throw new \UnexpectedValueException('The list of supported locales must not be empty.');
+            throw new UnexpectedValueException('The list of supported locales must not be empty.');
         }

         $this->defaultLocale = $defaultLocale ?: $this->locales[0];

         if (!\in_array($this->defaultLocale, $this->locales, true)) {
-            throw new \UnexpectedValueException(sprintf('The default locale ("%s") must be one of "%s".', $this->defaultLocale, $locales));
+            throw new UnexpectedValueException(sprintf('The default locale ("%s") must be one of "%s".', $this->defaultLocale, $locales));
         }

         // Add the default locale at the first position of the array,
@@ -61,12 +62,12 @@
         ];
     }

-    public function onKernelRequest(RequestEvent $event): void
+    public function onKernelRequest(RequestEvent $requestEvent): void
     {
-        $request = $event->getRequest();
+        $request = $requestEvent->getRequest();

         // Ignore sub-requests and all URLs but the homepage
-        if (!$event->isMasterRequest() || '/' !== $request->getPathInfo()) {
+        if (!$requestEvent->isMasterRequest() || '/' !== $request->getPathInfo()) {
             return;
         }
         // Ignore requests from referrers with the same HTTP host in order to prevent
@@ -79,8 +80,8 @@
         $preferredLanguage = $request->getPreferredLanguage($this->locales);

         if ($preferredLanguage !== $this->defaultLocale) {
-            $response = new RedirectResponse($this->urlGenerator->generate('homepage', ['_locale' => $preferredLanguage]));
-            $event->setResponse($response);
+            $redirectResponse = new RedirectResponse($this->urlGenerator->generate('homepage', ['_locale' => $preferredLanguage]));
+            $requestEvent->setResponse($redirectResponse);
         }
     }
 }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


17) ../project/src/Form/CommentType.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -32,7 +32,7 @@
     /**
      * {@inheritdoc}
      */
-    public function buildForm(FormBuilderInterface $builder, array $options): void
+    public function buildForm(FormBuilderInterface $formBuilder, array $options): void
     {
         // By default, form fields include the 'required' attribute, which enables
         // the client-side form validation. This means that you can't test the
@@ -40,7 +40,7 @@
         // this validation, set the 'required' attribute to 'false':
         // $builder->add('content', null, ['required' => false]);

-        $builder
+        $formBuilder
             ->add('content', TextareaType::class, [
                 'help' => 'help.comment_content',
             ])
@@ -50,9 +50,9 @@
     /**
      * {@inheritdoc}
      */
-    public function configureOptions(OptionsResolver $resolver): void
+    public function configureOptions(OptionsResolver $optionsResolver): void
     {
-        $resolver->setDefaults([
+        $optionsResolver->setDefaults([
             'data_class' => Comment::class,
         ]);
     }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


18) ../project/src/Form/DataTransformer/TagArrayToStringTransformer.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -29,9 +29,9 @@
 {
     private $tags;

-    public function __construct(TagRepository $tags)
+    public function __construct(TagRepository $tagRepository)
     {
-        $this->tags = $tags;
+        $this->tags = $tagRepository;
     }

     /**
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


19) ../project/src/Form/PostType.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -42,7 +42,7 @@
     /**
      * {@inheritdoc}
      */
-    public function buildForm(FormBuilderInterface $builder, array $options): void
+    public function buildForm(FormBuilderInterface $formBuilder, array $options): void
     {
         // For the full reference of options defined by each form field type
         // see https://symfony.com/doc/current/reference/forms/types.html
@@ -53,7 +53,7 @@
         // this validation, set the 'required' attribute to 'false':
         // $builder->add('title', null, ['required' => false, ...]);

-        $builder
+        $formBuilder
             ->add('title', null, [
                 'attr' => ['autofocus' => true],
                 'label' => 'label.title',
@@ -91,9 +91,9 @@
     /**
      * {@inheritdoc}
      */
-    public function configureOptions(OptionsResolver $resolver): void
+    public function configureOptions(OptionsResolver $optionsResolver): void
     {
-        $resolver->setDefaults([
+        $optionsResolver->setDefaults([
             'data_class' => Post::class,
         ]);
     }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


20) ../project/src/Form/Type/ChangePasswordType.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -29,9 +29,9 @@
     /**
      * {@inheritdoc}
      */
-    public function buildForm(FormBuilderInterface $builder, array $options): void
+    public function buildForm(FormBuilderInterface $formBuilder, array $options): void
     {
-        $builder
+        $formBuilder
             ->add('currentPassword', PasswordType::class, [
                 'constraints' => [
                     new UserPassword(),
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


21) ../project/src/Form/Type/DateTimePickerType.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Form\Type;

+use Locale;
 use App\Utils\MomentFormatConverter;
 use Symfony\Component\Form\AbstractType;
 use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
@@ -31,26 +32,26 @@
 {
     private $formatConverter;

-    public function __construct(MomentFormatConverter $converter)
+    public function __construct(MomentFormatConverter $momentFormatConverter)
     {
-        $this->formatConverter = $converter;
+        $this->formatConverter = $momentFormatConverter;
     }

     /**
      * {@inheritdoc}
      */
-    public function buildView(FormView $view, FormInterface $form, array $options): void
+    public function buildView(FormView $formView, FormInterface $form, array $options): void
     {
-        $view->vars['attr']['data-date-format'] = $this->formatConverter->convert($options['format']);
-        $view->vars['attr']['data-date-locale'] = u(\Locale::getDefault())->replace('_', '-')->lower();
+        $formView->vars['attr']['data-date-format'] = $this->formatConverter->convert($options['format']);
+        $formView->vars['attr']['data-date-locale'] = u(Locale::getDefault())->replace('_', '-')->lower();
     }

     /**
      * {@inheritdoc}
      */
-    public function configureOptions(OptionsResolver $resolver): void
+    public function configureOptions(OptionsResolver $optionsResolver): void
     {
-        $resolver->setDefaults([
+        $optionsResolver->setDefaults([
             'widget' => 'single_text',
             // if true, the browser will display the native date picker widget
             // however, this app uses a custom JavaScript widget, so it must be set to false
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


22) ../project/src/Form/Type/TagsInputType.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -32,17 +32,17 @@
 {
     private $tags;

-    public function __construct(TagRepository $tags)
+    public function __construct(TagRepository $tagRepository)
     {
-        $this->tags = $tags;
+        $this->tags = $tagRepository;
     }

     /**
      * {@inheritdoc}
      */
-    public function buildForm(FormBuilderInterface $builder, array $options): void
+    public function buildForm(FormBuilderInterface $formBuilder, array $options): void
     {
-        $builder
+        $formBuilder
             // The Tag collection must be transformed into a comma separated string.
             // We could create a custom transformer to do Collection <-> string in one step,
             // but here we're doing the transformation in two steps (Collection <-> array <-> string)
@@ -55,9 +55,9 @@
     /**
      * {@inheritdoc}
      */
-    public function buildView(FormView $view, FormInterface $form, array $options): void
+    public function buildView(FormView $formView, FormInterface $form, array $options): void
     {
-        $view->vars['tags'] = $this->tags->findAll();
+        $formView->vars['tags'] = $this->tags->findAll();
     }

     /**
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


23) ../project/src/Form/UserType.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -28,7 +28,7 @@
     /**
      * {@inheritdoc}
      */
-    public function buildForm(FormBuilderInterface $builder, array $options): void
+    public function buildForm(FormBuilderInterface $formBuilder, array $options): void
     {
         // For the full reference of options defined by each form field type
         // see https://symfony.com/doc/current/reference/forms/types.html
@@ -39,7 +39,7 @@
         // this validation, set the 'required' attribute to 'false':
         // $builder->add('title', null, ['required' => false, ...]);

-        $builder
+        $formBuilder
             ->add('username', TextType::class, [
                 'label' => 'label.username',
                 'disabled' => true,
@@ -56,9 +56,9 @@
     /**
      * {@inheritdoc}
      */
-    public function configureOptions(OptionsResolver $resolver): void
+    public function configureOptions(OptionsResolver $optionsResolver): void
     {
-        $resolver->setDefaults([
+        $optionsResolver->setDefaults([
             'data_class' => User::class,
         ]);
     }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


24) ../project/src/Kernel.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -20,18 +20,18 @@
 {
     use MicroKernelTrait;

-    protected function configureContainer(ContainerConfigurator $container): void
+    protected function configureContainer(ContainerConfigurator $containerConfigurator): void
     {
-        $container->import('../config/{packages}/*.yaml');
-        $container->import('../config/{packages}/'.$this->environment.'/*.yaml');
-        $container->import('../config/{services}.yaml');
-        $container->import('../config/{services}_'.$this->environment.'.yaml');
+        $containerConfigurator->import('../config/{packages}/*.yaml');
+        $containerConfigurator->import('../config/{packages}/'.$this->environment.'/*.yaml');
+        $containerConfigurator->import('../config/{services}.yaml');
+        $containerConfigurator->import('../config/{services}_'.$this->environment.'.yaml');
     }

-    protected function configureRoutes(RoutingConfigurator $routes): void
+    protected function configureRoutes(RoutingConfigurator $routingConfigurator): void
     {
-        $routes->import('../config/{routes}/'.$this->environment.'/*.yaml');
-        $routes->import('../config/{routes}/*.yaml');
-        $routes->import('../config/{routes}.yaml');
+        $routingConfigurator->import('../config/{routes}/'.$this->environment.'/*.yaml');
+        $routingConfigurator->import('../config/{routes}/*.yaml');
+        $routingConfigurator->import('../config/{routes}.yaml');
     }
 }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


25) ../project/src/Pagination/Paginator.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Pagination;

+use Traversable;
 use Doctrine\ORM\QueryBuilder as DoctrineQueryBuilder;
 use Doctrine\ORM\Tools\Pagination\CountWalker;
 use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
@@ -27,9 +28,9 @@
     private $results;
     private $numResults;

-    public function __construct(DoctrineQueryBuilder $queryBuilder, int $pageSize = self::PAGE_SIZE)
+    public function __construct(DoctrineQueryBuilder $doctrineQueryBuilder, int $pageSize = self::PAGE_SIZE)
     {
-        $this->queryBuilder = $queryBuilder;
+        $this->queryBuilder = $doctrineQueryBuilder;
         $this->pageSize = $pageSize;
     }

@@ -103,7 +104,7 @@
         return $this->numResults;
     }

-    public function getResults(): \Traversable
+    public function getResults(): Traversable
     {
         return $this->results;
     }
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector


26) ../project/src/Repository/PostRepository.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,7 @@

 namespace App\Repository;

+use DateTime;
 use App\Entity\Post;
 use App\Entity\Tag;
 use App\Pagination\Paginator;
@@ -30,28 +31,28 @@
  */
 class PostRepository extends ServiceEntityRepository
 {
-    public function __construct(ManagerRegistry $registry)
+    public function __construct(ManagerRegistry $managerRegistry)
     {
-        parent::__construct($registry, Post::class);
+        parent::__construct($managerRegistry, Post::class);
     }

     public function findLatest(int $page = 1, Tag $tag = null): Paginator
     {
-        $qb = $this->createQueryBuilder('p')
+        $queryBuilder = $this->createQueryBuilder('p')
             ->addSelect('a', 't')
             ->innerJoin('p.author', 'a')
             ->leftJoin('p.tags', 't')
             ->where('p.publishedAt <= :now')
             ->orderBy('p.publishedAt', 'DESC')
-            ->setParameter('now', new \DateTime())
+            ->setParameter('now', new DateTime())
         ;

         if (null !== $tag) {
-            $qb->andWhere(':tag MEMBER OF p.tags')
+            $queryBuilder->andWhere(':tag MEMBER OF p.tags')
                 ->setParameter('tag', $tag);
         }

-        return (new Paginator($qb))->paginate($page);
+        return (new Paginator($queryBuilder))->paginate($page);
     }

     /**
    ----------- end diff -----------


Applied rules:

 * Rector\Injection\Rector\StaticCall\StaticCallToAnotherServiceConstructorInjectionRector
 * Rector\Naming\Rector\Assign\RenameVariableToMatchGetMethodNameRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


27) ../project/src/Repository/TagRepository.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -26,8 +26,8 @@
  */
 class TagRepository extends ServiceEntityRepository
 {
-    public function __construct(ManagerRegistry $registry)
+    public function __construct(ManagerRegistry $managerRegistry)
     {
-        parent::__construct($registry, Tag::class);
+        parent::__construct($managerRegistry, Tag::class);
     }
 }
    ----------- end diff -----------


Applied rules:

 * Rector\Injection\Rector\StaticCall\StaticCallToAnotherServiceConstructorInjectionRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


28) ../project/src/Repository/UserRepository.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -27,8 +27,8 @@
  */
 class UserRepository extends ServiceEntityRepository
 {
-    public function __construct(ManagerRegistry $registry)
+    public function __construct(ManagerRegistry $managerRegistry)
     {
-        parent::__construct($registry, User::class);
+        parent::__construct($managerRegistry, User::class);
     }
 }
    ----------- end diff -----------


Applied rules:

 * Rector\Injection\Rector\StaticCall\StaticCallToAnotherServiceConstructorInjectionRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


29) ../project/src/Twig/SourceCodeExtension.php

    ---------- begin diff ----------
--- Original
+++ New
@@ -11,6 +11,11 @@

 namespace App\Twig;

+use ReflectionFunctionAbstract;
+use ReflectionMethod;
+use Closure;
+use ReflectionObject;
+use ReflectionFunction;
 use function Symfony\Component\String\u;
 use Twig\Environment;
 use Twig\Extension\AbstractExtension;
@@ -46,11 +51,11 @@
         ];
     }

-    public function showSourceCode(Environment $twig, $template): string
+    public function showSourceCode(Environment $environment, $template): string
     {
-        return $twig->render('debug/source_code.html.twig', [
+        return $environment->render('debug/source_code.html.twig', [
             'controller' => $this->getController(),
-            'template' => $this->getTemplateSource($twig->resolveTemplate($template)),
+            'template' => $this->getTemplateSource($environment->resolveTemplate($template)),
         ]);
     }

@@ -79,19 +84,19 @@
      *
      * This logic is copied from Symfony\Component\HttpKernel\Controller\ControllerResolver::getArguments
      */
-    private function getCallableReflector(callable $callable): \ReflectionFunctionAbstract
+    private function getCallableReflector(callable $callable): ReflectionFunctionAbstract
     {
         if (\is_array($callable)) {
-            return new \ReflectionMethod($callable[0], $callable[1]);
+            return new ReflectionMethod($callable[0], $callable[1]);
         }

-        if (\is_object($callable) && !$callable instanceof \Closure) {
-            $r = new \ReflectionObject($callable);
+        if (\is_object($callable) && !$callable instanceof Closure) {
+            $reflectionObject = new ReflectionObject($callable);

-            return $r->getMethod('__invoke');
+            return $reflectionObject->getMethod('__invoke');
         }

-        return new \ReflectionFunction($callable);
+        return new ReflectionFunction($callable);
     }

     /**
    ----------- end diff -----------


Applied rules:

 * Rector\Naming\Rector\ClassMethod\RenameVariableToMatchNewTypeRector
 * Rector\Naming\Rector\Class_\RenamePropertyToMatchTypeRector
 * Rector\TypeDeclaration\Rector\ClassMethod\AddParamTypeDeclarationRector


 [OK] Rector is done! 29 files would have changed (dry-run).

As you can see at https://github.com/rectorphp/rector/blob/master/config/set/symfony50.php, this set defines two rectors only, but Rector is freely roaming over with completely different ones.

@Aerendir
Copy link
Contributor

Ok, I understand.

Lets wait for @TomasVotruba ...

@TomasVotruba
Copy link
Member

TomasVotruba commented Aug 22, 2020

@kbsali Unfortunatelly, there is now no way to preserve annotation format correctly, as described in README: https://github.com/rectorphp/rector#how-to-apply-coding-standards

The same way php-parser 3 and bellow was very poor at keeping format for PHP code.
This will be solved by PHP 8, where attributes will be handled nicely by php-parser.

Untill then, the best solution is to use coding standards: there is new Doctrine annotation standard in ECS: deprecated-packages/symplify#2078

# ecs.php 

<?php

declare(strict_types=1);

use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\EasyCodingStandard\Configuration\Option;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;

return static function (ContainerConfigurator $containerConfigurator): void {
    $parameters = $containerConfigurator->parameters();
    $parameters->set(Option::SETS, [
        SetList::DOCTRINE_ANNOTATIONS,
    ]);
};

@kbsali
Copy link
Author

kbsali commented Aug 23, 2020

ok, very clear. Thanks @TomasVotruba

TomasVotruba added a commit that referenced this issue May 22, 2023
rectorphp/rector-src@3c69a0f Remove AddPregQuoteDelimiterRector as very narrow area and has not context awareness, better handle manually (#3927)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants