Using Rector to Ease Upgrades

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.

I first encountered the concept of ‘codemods’ in the JavaScript ecosystem. Christoph Nakazawa gave a talk at JSConf about 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.

Installing Rector

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:

Show Plain Text
  1. # Pull down the image.
  2. docker pull rector/rector:latest
  4. # Mount the current directory to `/project` and run
  5. # the phpunit8 rector on its src directory.
  6. 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
  1. # Clone rector and install its dependencies.
  2. cd ~/projects
  3. git clone
  4. cd rector
  5. composer install
  7. # Run rector on your project
  8. # To actually apply changes remove the `--dry-run` flag.
  9. cd ~/project/myapp
  10. ~/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.


The command that works for me is:
docker run -v (pwd):/project rector/rector:latest process /project/src —autoload-file /project/vendor/autoload.php —set cakephp38 —dry-run

Alexander Garzon on 9/12/19

what a story Mark

Mykola on 9/19/19

Have your say: