Upgrading major libraries that your application depends on can be a tedious and time consuming process. Dealing with deprecations and backwards incompatible changes can consume a significant amount of time and energy. In the past we’ve relied on manually updating code or using find and replace. But in last few years new techniques have emerged that make routine upgrades easier to do.
jscodeshift and how it does AST transformations. Modifying the Abstract Syntax Tree is a much better way to modify code as it lets tooling leverage type information and handle more complex scenarios. Fast forward a few years and TomasVortuba has created rector bringing AST transformations to PHP.
While the rector documentation suggests using
composer require in your project I’ve not had much success in doing that. Instead I’ve had better results using the rector docker image or installing it as a standalone project. Using the provided docker image requires you to pull down the image and run it:
- # Pull down the image.
- docker pull rector/rector:latest
- # Mount the current directory to `/project` and run
- # the phpunit8 rector on its src directory.
- docker run -v $(pwd):/project rector/rector:latest process /project/src --set phpunit8 --dry-run
Using a standalone installation can be done with a git clone and composer:Show Plain Text
- # Clone rector and install its dependencies.
- cd ~/projects
- git clone https://github.com/rectorphp/rector
- cd rector
- composer install
- # Run rector on your project
- # To actually apply changes remove the `--dry-run` flag.
- cd ~/project/myapp
- ~/projects/rector/bin/rector process src --autoload-file vendor/autoload.php --set phpunit8 --dry-run
Rector + CakePHP
The Rector and CakePHP communities have already built ‘sets’ to help you navigate the various deprecations that have been introduced in each of the 3.x releases. We’ll continue that process for 4.x, and we plan on incorporating rector into a future iteration of the
cake upgrade command that bundles rector and other upgrade tasks together. If you haven’t addressed all the deprecations in your application or plugins I suggest you give rector a try as it might save you a bunch of tedious work.