Rector
Rector has been useful for taking advantage of new language features as they become available in PHP. It doesn’t take a lot of setup, but given it’s infrequent use this guide might be useful to save re-leaning bits every time.
Installation
Try using the latest version, although it’s unlikely to work given both Sirius and Rector have a dependency on PHPStan
make api-composer COMPOSER_ARGS="require rector/rector --dev"
If that fails pin at the latest compatible version e.g.
make api-composer COMPOSER_ARGS="require rector/rector:0.16 --dev"
Use in docker
Add the following to the docker-compose.yml
api-app-rector:
image: 311462405659.dkr.ecr.eu-west-1.amazonaws.com/sirius/api-app-test:${BUILD_TAG:-latest}
command:
- vendor/bin/rector
- init
environment:
OPG_CORE_SESSION_TIMEOUT: ${TIMEOUT_OVERRIDE:-3600}
OPG_CORE_BACK_ENABLE_PAYMENT_PENDING_STATUS: ${OPG_CORE_BACK_ENABLE_PAYMENT_PENDING_STATUS_OVERRIDE:-0}
volumes:
- "./back-end:/var/www:delegated"
Rector configuration
Run Rector once with the init
option enabled to generate a rector.php file, then comment that line out
docker compose up api-app-rector
Alter this file to run the sets or individual rules you want to apply
Rule set example
<?php
declare(strict_types=1);
use Rector\Config\RectorConfig;
use Rector\Doctrine\Set\DoctrineSetList;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->paths([
__DIR__ . '/module',
]);
$rectorConfig->sets([
DoctrineSetList::ANNOTATIONS_TO_ATTRIBUTES,
]);
};
Single rule example
<?php
declare(strict_types=1);
use Rector\CodingStyle\Rector\String_\UseClassKeywordForClassNameResolutionRector;
use Rector\Config\RectorConfig;
return static function (RectorConfig $rectorConfig): void {
$rectorConfig->paths([
__DIR__ . '/module',
]);
$rectorConfig->rule(UseClassKeywordForClassNameResolutionRector::class);
};
Tips
- For large rule sets, such as new language features introduced in PHP upgrades, it might be best to run the ruleset as an experiment then pick out individual rules that you want to automatically apply and run and commit those one at a time. It’s usually easier to review one change in a lot of places than a lot of changes across a few places.
- If the change is taking too long or failing, edit the paths config to target a smaller subset of directories.