rectorphp / rector

Instant Upgrades and Automated Refactoring of any PHP 5.3+ code
https://getrector.com
MIT License
8.61k stars 680 forks source link

[DX] Add RequiredPolyfillInterface to some rule to enable then, once the project is using polyfill package #8368

Closed TomasVotruba closed 8 months ago

TomasVotruba commented 8 months ago

E.g. if the project composer.json contains:

{
    "require": {
         "symfony/polyfill-php80": "^1.26",
    }
}

We upgrade to PHP 8.0 features, that benefit from this package. It must be manually checked what Rector rules should be extended, as this polyfill only adds helper for few functions, not all PHP 8.0 features.

To enable such a rule, it must require RequiredPolyfillInterface contract:

class SomeRector implements RequiredPolyfillInterface
{
     public function getPolyfill(): string
    {
         return 'symfony/polyfill-php80';
     }
}
fredericgboutin-yapla commented 4 months ago

This PR is such an underrated feature. You can basically set the PhpVersion to the minimum version your code must support, for example for us it is PHP 7.4. But we seek to migrate to PHP 8.2, so we set the targeted rules to UP_TO_PHP_82.

One would think that rector would automatically exclude all rules that are not PHP 7.4 compatible, but no. If you use a polyfill like symfony/polyfill-php80, symfony/polyfill-php81 and symfony/polyfill-php82 rector will enable some rules like StrStartsWithRector and StrContainsRector.

Anyway, thanks for that! Call me impressed. Cheers 👋

TomasVotruba commented 4 months ago

Thank you Frederic for kind words :pray: Spread the word to help out the community to learn about those features :partying_face: