Search code examples
phpstorm

Search and replace in all files for context action in PhpStorm


After upgrading a project to PHP8, I'd like to refactor my code to use the new features, eg. replacing

if (strpos($link, 'somestring') === false) {

with

if (!str_contains($link, 'somestring')) {

PhpStorm offers a context menu for this action which is great. It also means that PhpStorm can detect these constructs.

But: Is there a possibility to replace all occurrences automatically, maybe in combination with the "Replace in files" menu? Of course a regex would also do the job, but a full automatic process would be more comfortable.


Solution

    1. Find which inspection is this. For this:

      • Place caret on the highlighted part (on strpos in this case)
      • Invoke Intentions/Quick Fix menu (Alt + Enter on most keymaps or via light bulb icon using a mouse)
      • Expand the most appropriate option (Arrow Right) enter image description here
      • Select "Edit inspection profile settings" -- it will take you to that inspection so you can clearly see its name and check what is does (although in this particular case it is not really necessary as the name is already shown on the first screenshot; but in other cases it can have different text there). enter image description here
    2. Run that particular inspection.

      • Use Code | Analyze Code | Run Inspection by Name... (Ctrl + Alt + Shift + I here on Windows keymap).
      • Locate that inspection there
      • Run it on a desired scope (e.g. a folder/custom scope/whole project etc) enter image description here
    3. The "Problems" toolwindow will be activated and will list all places where this inspection is triggered. You can do the batch fix here (on a file scope, not all occurrences at once though -- not all quick fixes have "fix all found occurrences at once" option).

      enter image description here

    P.S. You can skip some steps (1.4, 2.1 & 2.2) by simply selecting Run inspection on... on the first screenshot if you know for sure that it is the right inspection.


    Another approach / option -- use Rector that can do quite a few of such upgrades in automated way. It can be integrated with PhpStorm as of 2022.2 version (and you can always run it from a command line).