Rector upgrades rules for Symfony Framework

Overview

Rector Rules for Symfony

See available Symfony rules

Install

This package is already part of rector/rector package, so it works out of the box.

All you need to do is install the main package, and you're good to go:

composer require rector/rector --dev

Use Sets

To add a set to your config, use Rector\Symfony\Set\SymfonySetList class and pick one of constants:

use Rector\Symfony\Set\SymfonySetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $containerConfigurator->import(SymfonySetList::SYMFONY_44);
};

Symfony Container

To work with some Symfony rules, you now need to link your container XML file

// rector.php
use Rector\Core\Configuration\Option;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;

return static function (ContainerConfigurator $containerConfigurator): void {
    $parameters = $containerConfigurator->parameters();

    $parameters->set(
        Option::SYMFONY_CONTAINER_XML_PATH_PARAMETER,
        __DIR__ . '/var/cache/dev/AppKernelDevDebugContainer.xml'
    );
};

Read a First Book About Rector

Are you curious, how Rector works internally, how to create your own rules and test them and why Rector was born? In May 2021 we've released the very first book: Rector - The Power of Automated Refactoring.

By buying a book you directly support maintainers who are working on Rector.


Support

Rector is a tool that we develop and share for free, so anyone can automate their refactoring. But not everyone has dozens of hours to understand complexity of abstract-syntax-tree in their own time. That's why we provide commercial support - to save your time.

Would you like to apply Rector on your code base but don't have time for the struggle with your project? Hire us to get there faster.

Comments
  • setDescription not changed for Commands MakeCommandLazyRector|CommandPropertyToAttributeRector

    setDescription not changed for Commands MakeCommandLazyRector|CommandPropertyToAttributeRector

    When i have a setDescription in my configure function it is not moved to static property for https://github.com/rectorphp/rector-symfony/blob/main/docs/rector_rules_overview.md#makecommandlazyrector and not moved when i enable https://github.com/rectorphp/rector-symfony/blob/main/docs/rector_rules_overview.md#commandpropertytoattributerector

    opened by johanadivare 21
  • Feature/Support: Migrate route configuration from yaml to annotation/attribute

    Feature/Support: Migrate route configuration from yaml to annotation/attribute

    Feature Request

    I'm actually working on a legacy application with Symfony 3.4 and everything is structured in not necessary bundles. Actually the ~500 routes of the application are configured with YAML in the different bundles. My target is to migrate the route configuration to annotations or attributes. For the beginning I prefer annotations because there are already Rector rules which converts routes between annotations and attributes and legacy applications may not use PHP 8^^

    I've already seen that somebody asked for this feature but no one has implemented it or not?

    My first step was to get the resolved routes from Symfony because of the bundle structure a route configuration in YAML for a controller/action looks like FooBundle:Bar:baz and will be resolved by the router to \FooBar\FooBundle\Controller\Bar::bazAction which makes me easily to get the correct controller and especially the action because inside the Controller there are often more than one action implemented. For testing I implemented a Symfony command which iterates through the existing routes from the Symfony router and every information of route like path, name, default, ... are available. Very easy to get the important information.

    Now the PHP files must be edited which will be easy with Rector but I don't know if it possible to iterate over the configured routes instead of iterating over directories/files?

    If it's not possible maybe it's possible to extend the Symfony command which I used for testing that it can use Rector to edit the PHP files but the isn't my prefered solution because it wouldn't be a contribution to the Rector project but I publish it on GitHub.

    WDYT? I'm very open for any input :)

    Diff

    -foo_baz:
    -    path: /foo/{baz}
    -    defaults: { _controller: FooBundle:Bar:baz, _format: json }
    -    methods: [ GET, POST ]
    
    +/**
    + * @Route(name="foo_baz", path="/foo/{baz}", methods={"GET","POST"}, defaults={_format="json"})
    + */
    public function bazAction(string $baz)
    
    opened by malteschlueter 21
  • Is there a Rector for Symfony service name migrations?

    Is there a Rector for Symfony service name migrations?

    It's nice that that's lots of little Rectors for doing simple things, but it seems to me the most laborious and complex task of upgrading an old Symfony project is upgrading to the new Symfony 3.3 configuration. Specifically, this means replacing service "machine names" (e.g. my.foo) with FQCN names (e.g. My\Foo::class).

    Without this, SymfonySetList::SYMFONY_CONSTRUCTOR_INJECTION cannot do its job and isn't very helpful, because it only promotes services called via get() that specify FQCN class names already. In older projects, this means little or no services are fixed because machine names for services were the norm back then. Nevertheless, it should be possible to read the service configuration and map those names back to the actual class names to both perform the constructor injection and rename the service. However, I cannot find any Rector to do this.

    opened by Bilge 14
  • [Symfony] Add constant int value support on WebTestCaseAssertIsSuccessfulRector

    [Symfony] Add constant int value support on WebTestCaseAssertIsSuccessfulRector

    Add failing test for #250

    I think the fix might be in ValueResolver from PhpParser as we use isValue to check if the constant is equal to int. But maybe we should also resolve the constant values?

    HACKTOBERFEST-ACCEPTED 
    opened by JohJohan 11
  • Question about using rector on a bundle

    Question about using rector on a bundle

    Hi there,

    that might be a dumb question, but I'm still on a learning curve from being an engineer only to also developer, but here is the situation. We've written a bundle with some clients, services and so on, which we are using on almost all projects internally.

    I've already noticed, that the code quality could be a lot better, but I would like to check it via rector check as well, but obviously, there is no container loaded, so there isn't any container XML available.

    I've already tried to include the bundle specifically in one of the projects by adding it to the $rectorConfig->paths, but it seems to ignore that directory (analyzed file count doesn't change).

    Any hint would be appreciated.

    Thanks !

    Regards Oliver

    opened by riskersen 11
  • Symfony v6 Controller getDoctrine()

    Symfony v6 Controller getDoctrine()

    Hi

    According to https://github.com/symfony/symfony/blob/6.0/UPGRADE-6.0.md, getDoctrine() is being deprecated I have a lot of code $em = $this->getDoctrine()->getManager(); in my controllers, I would like to know if there is, or how to add, a rule to swap from this code to EntityManagerInterface $entityManager constructor injection or controller action injection

    thank you

    opened by 94noni 10
  • Rector is adding useless cast (int) to Command::Success

    Rector is adding useless cast (int) to Command::Success

    Hi,

    Now https://github.com/rectorphp/rector-symfony/issues/255 is implemented (cc @johanadivare), there is an issue. I would say it's the rule https://github.com/rectorphp/rector-symfony/blob/main/docs/rector_rules_overview.md#consoleexecutereturnintrector

    When running, rector with the SymfonyLevelSetList::UP_TO_SYMFONY_61 I get

    return 0;
    

    changed to

     return (int) Command::SUCCESS;
    

    If I try to change to

     return Command::SUCCESS;
    

    Running rector give me again

     return (int) Command::SUCCESS;
    

    I saw you just did a PR https://github.com/rectorphp/rector-symfony/pull/290 @TomasVotruba, dont know if it was for this.

    easy-pick 
    opened by VincentLanglet 9
  • Upgrading to 0.12.3 gives

    Upgrading to 0.12.3 gives "Method getExtendedTypes() was not found in reflection of class Symfony\Component\Form\AbstractTypeExtension"

    It seems that, after Rector finishes its first run after upgrading from 0.11 -> 0.12, almost every file in my project is attributed to an error similar to the following:

    [ERROR] Could not process "src/Kernel.php" file, due to: "Method getExtendedTypes() was not found in reflection of class Symfony\Component\Form\AbstractTypeExtension.". On line: 328

    Of course, the source file (Kernel.php) is different in each case, but otherwise the error is the same for every single file. Many of these files do not even appear to be tangentially related to the Form component in any way, so I have no idea what is going on.

    This occurs on Symfony 4.4.33.

    opened by Bilge 9
  • Add check that scope is vaild

    Add check that scope is vaild

    When i run rector, i have the following error:

    [ERROR] Could not process "src/SomeMyNamespace/SomeMyClass.php" file by
             "Rector\Symfony2\Rector\MethodCall\AddFlashRector", due to:
             "Call to a member function getClassReflection() on null".
    
    opened by sam0delkin 9
  • [CommandPropertyToAttributeRector] is not setting all attributes

    [CommandPropertyToAttributeRector] is not setting all attributes

    Bug Report

    CommandPropertyToAttributeRector is not setting aliases and hidden in AsCommand attribute

    | Subject | Details | | :------------- | :--------------------| | Rector version | last dev-main | | Installed as | composer dependency |

    Minimal PHP Code Causing Issue

    See https://getrector.org/demo/69d11564-5a50-458b-b185-de0c343b416b

    <?php
    
    class SunshineCommand extends \Symfony\Component\Console\Command\Command
    {
        /** @var string|null */
        public static $defaultName = 'sunshine';
    
        /** @var string|null */
        public static $defaultDescription = 'Let the sun shine!';
        
    
        /**
         * {@inheritdoc}
         */
        protected function configure(): void
        {
            $this
                ->setAliases(['sun', 'shine'])
            ;
        }
    }
    

    Responsible rules

    • CommandPropertyToAttributeRector

    Expected Behavior

    <?php
    
    #[\Symfony\Component\Console\Attribute\AsCommand('sunshine', 'Let the sun shine!', ['sun', 'shine'], false)
    class SunshineCommand extends \Symfony\Component\Console\Command\Command
    {
        /**
         * {@inheritdoc}
         */
        protected function configure(): void
        {
        }
    }
    
    opened by johanadivare 8
  • Annotation To Attributes : function constant with wrong argument

    Annotation To Attributes : function constant with wrong argument

    Bug Report

    | Subject | Details | | :------------- | :---------------------------------------------------------------| | Rector version | 0.14.0 |

    Hi,

    I'm using SensioLab bundle (extra) for our route in controller. I'm using the annotation @Security for more flexibility. I'm using php function constant as parameter for is_granted. With Attribute, it seems we must use \\\ instead of \\ for the fqn of the class + constant Note: It's a bit strange, not sure it's on purpose or a bug but it's working with 3 instead of 2. So Rector should update this argument too.

    Framework/ORM

    Symfony 6.1 Doctrine

    Php

    php 8.1.9 CentOs stream 8

    My file rector.php

    return static function (RectorConfig $rectorConfig): void {
    
        $rectorConfig->paths([
                                 __DIR__ . '/src/Controller/ResourcesBrandController.php'
                             ]);
    
        // Custom Annotation
        $rectorConfig->ruleWithConfiguration(
            AnnotationToAttributeRector::class, [
                                                  new AnnotationToAttribute('App\\Service\\PlatformUserActivity\\Mapping\\Annotation\\UserActivityLoggable'),
                                                  new AnnotationToAttribute('App\\Service\\PlatformUserActivity\\Mapping\\Annotation\\Versioned'),
                                              ]
        );
    
        // https://github.com/rectorphp/rector/blob/main/docs/rector_rules_overview.md#inlineconstructordefaulttopropertyrector
        $rectorConfig->rule(InlineConstructorDefaultToPropertyRector::class);
    
        // Add back new line after statement but keep for Class constant and Trait
        $rectorConfig->rule(NewlineAfterStatementCustomRector::class);
    
        $rectorConfig->sets(
            [
                DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES,
                DoctrineSetList::GEDMO_ANNOTATIONS_TO_ATTRIBUTES,
                SymfonySetList::ANNOTATIONS_TO_ATTRIBUTES,
                SymfonySetList::SYMFONY_CODE_QUALITY,
                SensiolabsSetList::FRAMEWORK_EXTRA_61,
                LevelSetList::UP_TO_PHP_80
            ]
        );
    
    };
    

    Original code with annotation

    /**
     * Class ResourcesBrandController
     *
     * @Route("/%route-backend_prefix%/resources/brand")
     * @Security("is_granted('ROLE_GA_BRAND_USER') and is_granted(constant('\\App\\Security\\Voter\\BrandVoter::ACCESS'))")
     */
    class ResourcesBrandControllerextends AbstractController
    {
    

    Expected Behaviour

    /**
     * Class ResourcesBrandController
     */
    #[Route(path: '/%route-backend_prefix%/resources/brand')]
    #[Security("is_granted('ROLE_GA_BRAND_USER') and is_granted(constant('\\\App\\\Security\\\Voter\\\BrandVoter::ACCESS'))")]
    class ResourcesBrandController extends AbstractController
    {
    

    What rector do

    /**
     * Class ResourcesBrandController
     */
    #[Route(path: '/%route-backend_prefix%/resources/brand')]
    #[Security("is_granted('ROLE_GA_BRAND_USER') and is_granted(constant('\\App\\Security\\Voter\\BrandVoter::ACCESS'))")]
    class ResourcesBrandController extends AbstractController
    {
    

    Like that, the ExpressionLanguage try to load a class called AppSecurityVoterBrandVoter instead of \App\Security\Voter\BrandVoter

    opened by kruggs 8
  • TypedPropertyFromStrictSetUpRector and Symfony container

    TypedPropertyFromStrictSetUpRector and Symfony container

    When using TypedPropertyFromStrictSetUpRector, properties in setUp() that are set with static::getContainer()->get('my_service') are refactored wit ?object instead of the inferred type of the service

    opened by yguedidi 1
  • [SYMFONY62] Deprecated MessageHandlerInterface and MessageSubscriberInterface

    [SYMFONY62] Deprecated MessageHandlerInterface and MessageSubscriberInterface

    These interfaces from symfony/messenger are deprecated in Symfony 6.2 in favor of the AsMessageHandler attribute.

    See https://github.com/symfony/symfony/pull/47068

    opened by enumag 1
  • AddRouteAnnotationRector does not work with invokable Controller

    AddRouteAnnotationRector does not work with invokable Controller

    Minimal YAML Code Causing Issue

    test_route:
      path: /test
      methods: ["GET"]
      controller: App\Controller\TestRouteController
    

    Minimal PHP Code Causing Issue

    <?php
    
    declare(strict_types=1);
    
    namespace App\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    
    class TestRouteController extends AbstractController
    {
        public function __invoke(): void {
        }
    }
    

    Responsible Rule

    • AddRouteAnnotationRector

    Expected Behaviour

    <?php
    
    declare(strict_types=1);
    
    namespace App\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
    +use Symfony\Component\Routing\Annotation\Route;
    
    class TestRouteController extends AbstractController
    {
    +   /**
    +   * @Route(path="/test", name="test_route", methods={"GET"})
    +   */
        public function __invoke(): void {
        }
    }
    
    opened by jambonfarci 1
  • [SYMFONY62] Replace ParamConverter with MapEntity

    [SYMFONY62] Replace ParamConverter with MapEntity

    See https://github.com/rectorphp/rector-symfony/issues/264

    This is my first time working with Rector and the AST so please add feedback 🙂

    Right now I'm confused why the use is not being removed (I thought RenamedClassesDataCollector would take care of that) and why the MapEntity is placed on a new line instead of prepended to the parameter.

    To do:

    • [x] ~Set MapEntity on the same line as the class method parameter~ Rector convention
    • [x] Remove use of ParamConverter
    • [x] Add fixture with multiple ParamConverters
    • [ ] Add fixture(s) that should be skipped
    • [x] Add fixture with other options (id, exclude, strip_null, entity_manager and evict_cache)
    • [ ] Fix CI

    Discussion:

    1. Should this also replace Entity attributes since that is a shortcut for using expr?
    opened by stefantalen 1
  • [SYMFONY62] Replace `supports` with `resolve`

    [SYMFONY62] Replace `supports` with `resolve`

    Make sure to write a custom rule for this as return type has changed from bool to array more information can be found on the symfony pull request

    Some more info https://github.com/rectorphp/rector-symfony/pull/279#discussion_r1029400492 & https://github.com/rectorphp/rector-symfony/pull/287

    opened by johanadivare 0
  • [SYMFONY53] replace `getCollectionKeyType` and `getCollectionValueType` with `getCollectionKeyTypes` and `getCollectionValueTypes`

    [SYMFONY53] replace `getCollectionKeyType` and `getCollectionValueType` with `getCollectionKeyTypes` and `getCollectionValueTypes`

    Make sure to write a custom rule for this as return type has changed more information can be found on the symfony pull request

    Some more info https://github.com/rectorphp/rector-symfony/pull/283

    opened by johanadivare 0
Rector upgrades rules for Nette

Rector Rules for Nette See available Nette rules Install composer require rector/rector-nette Use Sets To add a set to your config, use Rector\Nette\S

RectorPHP 21 Nov 7, 2022
Rector upgrades rules for Laravel

Rector Rules for Laravel See available Laravel rules Install This package is already part of rector/rector package, so it works out of the box. All yo

Rector 185 Dec 30, 2022
Rector rules for Nette to Symfony migration

Rector Nette to Symfony Do you need to migrate from Nette to Symfony? You can ↓ How we Migrated 54 357-lines Application from Nette to Symfony in 2 Pe

Rector 8 May 30, 2022
PHPStan Rules for Rector developers

Rector PHPStan Rules PHPStan rules for Rector and projects that maintain Rector rulesets. Install composer require rector/phpstan-rules --dev Do you u

RectorPHP 12 Dec 22, 2022
Instant Upgrades and Instant Refactoring of any PHP 5.3+ code

Rector - Speedup Your PHP Development Rector helps you with 2 areas - major code changes and in daily work. Do you have a legacy code base? Do you wan

RectorPHP 6.5k Jan 8, 2023
phpcs-security-audit is a set of PHP_CodeSniffer rules that finds vulnerabilities and weaknesses related to security in PHP code

phpcs-security-audit v3 About phpcs-security-audit is a set of PHP_CodeSniffer rules that finds vulnerabilities and weaknesses related to security in

Floe design + technologies 655 Jan 3, 2023
A toolbar for Laravel Telescope, based on the Symfony Web Profiler.

Laravel Telescope Toolbar Extends Laravel Telescope to show a powerful Toolbar See https://github.com/laravel/telescope Install First install Telescop

Fruitcake 733 Dec 30, 2022
Symfony kafka bundle to produce and consume messages.

Technology stack Quick start Example project Basic Configuration Consuming messages Retrying failed messages Handling offsets Decoders Denormalizers V

STS Gaming Group 25 Oct 3, 2022
PHP Benchmarking Framework

Athletic Athletic is a benchmarking framework. It allows developers to benchmark their code without littering microtime() calls everywhere. Athletic w

Zachary Tong 304 Dec 21, 2022
Rector upgrades rules for CakePHP

Rector Rules for CakePHP See available CakePHP rules Install composer require rector/rector-cakephp Use Sets To add a set to your config, use Rector\C

RectorPHP 19 Oct 27, 2022
Rector upgrades rules for Nette

Rector Rules for Nette See available Nette rules Install composer require rector/rector-nette Use Sets To add a set to your config, use Rector\Nette\S

RectorPHP 21 Nov 7, 2022
Rector upgrades rules for PHPUnit

Rector Rules for PHPUnit See available PHPUnit rules Install composer require rector/rector-phpunit Use Sets To add a set to your config, use Rector\P

RectorPHP 34 Dec 27, 2022
Rector upgrades rules for Doctrine

Rector Rules for Doctrine See available Doctrine rules Install This package is already part of rector/rector package, so it works out of the box.

Rector 37 Nov 7, 2022
Rector upgrades rules for Laravel

Rector Rules for Laravel See available Laravel rules Install This package is already part of rector/rector package, so it works out of the box. All yo

Rector 185 Dec 30, 2022
Rector - Instant Upgrades and Automated Refactoring

Rector - Instant Upgrades and Automated Refactoring This repository (rectorphp/rector-src) is for development Rector only. Head to rectorphp/rector fo

Rector 64 Dec 27, 2022
Rector rules for Nette to Symfony migration

Rector Nette to Symfony Do you need to migrate from Nette to Symfony? You can ↓ How we Migrated 54 357-lines Application from Nette to Symfony in 2 Pe

Rector 8 May 30, 2022
PHPStan Rules for Rector developers

Rector PHPStan Rules PHPStan rules for Rector and projects that maintain Rector rulesets. Install composer require rector/phpstan-rules --dev Do you u

RectorPHP 12 Dec 22, 2022
Rector Rules for BEAR.Sunday

Rector Rules for BEAR.Sunday The rector/rector rules for BEAR.Sunday.

BEAR.Sunday 2 Mar 30, 2022
Manage redirects using database rules. Rules are intended to be very similar to Laravel default routes, so syntax is pretty easy to comprehend.

Laravel DB redirector Manage HTTP redirections in Laravel using database Manage redirects using database rules. Rules are intended to be very similar

Vladimir Ković 12 Jul 18, 2022
Phpcs-magento-rules - A set of PHPCS rules used by made.com when hacking Magento

Made.com PHPCS Magento Rules A set of PHPCS rules used by made.com when hacking Magento. Pre-Requisites PHPCS Installation Short Version Clone this re

Made.com Tech Team 26 Jun 3, 2020