PHPStorm

In PHPStorm navigate to Run -> Edit Configurations… and add a new PHP Script.

As a File use your project’s path to bin/magento
As Arguments input command you wish to debug, for example: setup:upgrade --keep-generated
Lastly, set your IDE key through environment variables: XDEBUG_CONFIG="idekey=PHPSTORM"

Do note that it won’t work if Xdebug is disabled or is not installed.
Check if it’s on by running php -v.
If it’s enabled, you will see something like this:

PHP 7.4.27 (cli) (built: Dec 20 2021 21:28:15) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies
    with Xdebug v3.1.2, Copyright (c) 2002-2021, by Derick Rethans

If it’s disabled, the Xdebug line won’t be there:

PHP 7.4.27 (cli) (built: Dec 20 2021 21:28:15) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.27, Copyright (c), by Zend Technologies

sudo phpenmod xdebug to enable it
sudo phpdismod xdebug to disable it

You should also restart your webserver:
sudo service apache2 restart if you are using Apache
sudo service nginx restart if you are using Nginx

I moved those enabling/disabling steps into .bashrc file to make toggling between Xdebug a little bit faster. You can find it here.

Full working example:

Click to zoom

You can test it by setting up a breakpoint here.

Run it by navigating to Run -> Run… and selecting the name that you used when setting everything up (in my case this is bin/magento setup:upgrade)

Step 1 – run PHP Script

Click to zoom

Step 2 – console tab appears

Click to zoom

VoilĂ ! Xdebug breakpoint got triggered

Click to zoom

Happy debugging adventurer.

How to use PHPStorm built-in server

PHPStorm is shipped with a thing called Built-In Server which is an API that you can use to open any file in your project through IDE.

There are two prerequisites to make it work:
(1) PHPStorm project must be opened locally
(2) requested file must exist

Base URL looks like this: http://localhost:63342/api/file/

You can append any path that exists in your project to open it locally. For example, let’s say you want to open Magento_Catalog’s registration.php file:
vendor/magento/module-catalog/registration.php

The link is going to look like this:
http://localhost:63342/api/file/vendor/magento/module-catalog/registration.php

And you can test it for yourself here.

You are probably going to see this warning:

Decide by yourself if I’m trustworthy enough.

And if you want to disable those warnings permanently, go to PHPStorm settings: Build, Execution, Deployment -> Debugger and check Allow unsigned requests and press OK.