Blog posts under the xdebug tag https://webdevstudios.com/tags/xdebug/ WordPress Design and Development Agency Mon, 15 Apr 2024 16:05:21 +0000 en-US hourly 1 https://wordpress.org/?v=6.6.2 https://webdevstudios.com/wp-content/uploads/2022/07/cropped-wds-icon.white-on-dark-60x60.png Blog posts under the xdebug tag https://webdevstudios.com/tags/xdebug/ 32 32 58379230 Debugging WordPress Using Xdebug, Local, and VS Code https://webdevstudios.com/2022/10/06/debugging-wordpress/ https://webdevstudios.com/2022/10/06/debugging-wordpress/#comments Thu, 06 Oct 2022 16:00:51 +0000 https://webdevstudios.com/?p=25376 This post covers debugging WordPress using Xdebug, Local, and VS Code. This approach to debugging is far superior to logging variables to the error log or to the screen. Getting things set up correctly can be tricky. That’s where this tutorial helps. Xdebug Xdebug is a powerful tool for debugging PHP applications. It conveniently comes Read More Debugging WordPress Using Xdebug, Local, and VS Code

The post Debugging WordPress Using Xdebug, Local, and VS Code appeared first on WebDevStudios.

]]>
This post covers debugging WordPress using Xdebug, Local, and VS Code. This approach to debugging is far superior to logging variables to the error log or to the screen.

Getting things set up correctly can be tricky. That’s where this tutorial helps.

Xdebug in action

Xdebug

Xdebug is a powerful tool for debugging PHP applications. It conveniently comes bundled with Local.

We’re using VS Code for our code editor in this tutorial, as well as some other tools I’ve listed below. Everything included here is the current release and version numbers are noted just in case it might be helpful since things change.

Prerequisites

  • Local v6.4.2+6012: A local WordPress development environment, formally known as Local by Flywheel
      • PHP v7.4.1/v7.3.5/v8.0: Selectable via the Local UI. Choose v7.4.1 or v 7.3.5 for now because PHP 8 has a different Xdebug setup we’ll cover at the end of the article.
  • VS Code v1.70.2: Code editor
  • PHP Debug by Xdebug for VS code v1.27.0: VS Code extension which allows VS Code to talk to Xdebug
  • Xdebug Helper browser extension: Used for explicitly enabling or disabling debugging sessions

I use Windows because that’s what makes me happy, but this guide applies to other environments as well. I just wanted to note that, since the paths I’ll be referencing are Windows-y.

Create a Site in Local

Once all of the prerequisites have been installed and activated, you’ll need to create a new WP site in Local if you don’t have one already. When PHP Versions 7.3.x or 7.4.x are selected in Local, Xdebug Version 2 is used.

When PHP Version 8 is selected, Xdebug Version 3 is used. We’re going to use PHP Version 7.4.1 to start off with and will cover PHP Version 8 at the end of the article.

I’ve named my site xdebugvscode.test. Here are its settings:

Local site settings

Set Up php.ini.hbs Directives

Now that the site has been created, let’s double-check the Xdebug configuration directives in the site’s php.ini.hbs file. This file is located under your site’s conf/php directory.

For me, the path is D:devlocal-sitesxdebugvscodeconfphpphp.ini.hbs. Scroll to the bottom of the file under the [xdebug] section, and verify that you have the directives below set accordingly. If you need to make any changes, be sure to restart your Local site.

; Enable remote debugging.
xdebug.remote_enable=1

; If enabled, the xdebug.remote_host setting is ignored and
; Xdebug will try to connect to the client that made the HTTP request.
; It checks the $_SERVER['HTTP_X_FORWARDED_FOR'] and $_SERVER['REMOTE_ADDR'] variables to find out remote IP
xdebug.remote_connect_back=Off

; Set the port that Xdebug connects to.
xdebug.remote_port="9000"

; Disable the profiler.
xdebug.profiler_enable=0

; Set the profiler's output directory for when we're profiling.
xdebug.profiler_output_dir = "D:/dev/xdebug-profiler-output"

A Note About the php.ini.hbs File When Switching PHP Versions

If you ever change the PHP version for your Local site, Local will save the settings for the previous install of PHP under the {local-site-dir}/conf/php/php-{version-number}directory.

For example, I started out with PHP Version 7.4.1 installed, then switched to PHP Version 7.3.5. Local made a copy of my PHP Version 7.4.1 settings under D:devlocal-sitesxdebugvscodeconfphp-7.4.1.

If you change PHP versions and made any modifications to Local’s php.ini.hbs file, you’ll need to make the changes again, if this is the first time the PHP version has been activated. After that, if you swap between PHP versions, your setting changes will be preserved.

Ensure Xdebug Is Running

To make sure that Xdebug is running, create a file named pi.php in the root of your site and add the following code to it:

<?php
// Output information about PHP's configuration.
phpinfo();

location of the ph.php file

Now load up https://yoursite.test/pi.php and make sure that Xdebug is running. Find the Xdebug section; it will look something like this:
php_info() output
If you’re not seeing this, then Xdebug is not running. Double-check the php.ini.hbs file to ensure that Xdebug is enabled.

Activate Xdebug Helper Browser Extension

Once you’ve installed and activated the Xdebug Helper extension for your preferred browser, make sure to enable debugging by clicking on the icon and selecting Debug. The little bug icon will turn green letting you know that the browser extension will set the appropriate flag to turn on debugging.

Enable the Xdebug helper extension

Open Local Site in VS Code and Save a Workspace

Once the site has been created, go to File > Open Folder in VS Code, then navigate to the site’s directory. Now, save the workspace by going to File > Save Workspace As… and then give the workspace a name.

Install and Activate PHP Debug Extension for VS Code

The PHP Debug extension for VS Code helps to bring everything together. Locate the extension in VS Code’s Extension Browser, and activate it. Make sure to select the one published by the Xdebug team, since there are a few extensions with the same name.

PHP debug extension for VS Code

 

Create a launch.json File for Your Workspace

Next, we will create a launch.json file for our workspace. Click on VS Code’s debugging icon to open the debugging panel, then click on the create a launch.json file link.

Create launch.json step 1

Now select the name of your workspace which you created earlier.

Create launch.json step 2

VS Code will populate the launch.json file with defaults, but we’re going to replace them.

Create launch.json step 3

Go ahead and delete the entire contents of the default launch.json, replace the contents with the settings below, then save the file.

The launch.jsonwill be stored at {local-site-name}/.vscode/launch.json. So, mine is saved at D:devlocal-sitesxdebugvscode.vscodelaunch.json.

 

{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Listen for Xdebug",
      "type": "php",
      "request": "launch",
      "port": 9000,
      "log": false,
      "maxConnections": 1, // @see  https://github.com/xdebug/vscode-php-debug/issues/604
      "xdebugSettings": {
        "resolved_breakpoints": "0", // @see https://github.com/xdebug/vscode-php-debug/issues/629 and https://stackoverflow.com/a/69925257/3059883
        "max_data": 512,
        "show_hidden": 1,
        "max_children": 128
      }
    }
  ]
}

When using Local’s PHP Version 7.3.x or 7.4.x, the version of Xdebug in use will be 2.9.0, which had a bug that caused some weirdness with breakpoints. I’ve added some links to the config file above which go into some more detail if you’re interested.

Check out the PHP Debug extension’s Github page for more information about supported settings.

Add a Breakpoint to Your Code

For the purposes of this debugging WordPress demo, I’m going to add a breakpoint to line 48 of  Twenty Twenty-Two’s functions.php file.

To add a breakpoint, hover over the gutter (just to the left of a line number) and a little orange dot will appear. Click it to add a breakpoint.

Click it again to remove it. You can add multiple breakpoints, and the debugger will stop on each one. To keep things simple here, I’ll just add the one.

Adding a breakpoint

Once your breakpoint has been added, you will see it listed in the lower left-hand corner of  VS Code’s debugger panel. It’s also possible to set breakpoints on Notices, Warnings, Errors, etc., but we’ll uncheck all of those for this example.

Debugger breakpoints

Start Debugging WordPress

We’re finally ready to start debugging WordPress! Open VS Code’s debugger panel and click the green triangle to start listening for Xdebug. Use the F5 shortcut.
Start debugging
Once VS Code is listening for Xdebug, the Debugger Controls window will be displayed. The bottom of the VS Code window will turn orange.

Listening for debugger

Now Xdebug is waiting to start the session. To kick things off, just load a page that will hit the breakpoint.

I’m just going to load the homepage of the test site I created. Once I hit refresh on the homepage of the test site, VS Code will be highlighted in the taskbar and the debugger will stop executing code on the breakpoint that I had previously set.

Once a debugging session has started, additional controls will be active on the Debugger Control Panel, and variables will be listed under the VARIABLES section of the Debugging Panel.

Inside a debugging session

We can now use the Debugger Controls to navigate through the codebase:

Debugger Controls

  • Pause/Run (F6): Resumes code execution. Debugger will stop on the next breakpoint if set.
  • Step Over (F10): Steps over a block of code.
  • Step Into (F11): Steps into a block of code.
  • Step Out (Shift + F11): Steps out of a block of code that was previously stepped into.
  • Restart (Ctrl + Shift + F5): Restarts the debugging session.
  • Stop (Shift+F5): Halts execution of the script.

The GIF at the top of this article demonstrates some basic usage of these controls.

Exploring Variables

We can also explore the values of local and global variables using the VS Code’s VARIABLES section within the Debugging Panel.

Exploring variables

PHP Version 8 + Xdebug Version 3 Set Up

When a Local site is configured to use PHP Version 8.X, the bundled version of Xdebug will be Version 3, and there are many changes from Versions 2 to 3.

These changes are covered thoroughly in this guide. Notably, Xdebug Version 3 defaults to port 9003 instead of 9000. I’m going to switch my Xdebug Version 3 setup to use port 9000 for consistency, so I don’t have to change anything in my launch.json file.

Here are the Xdebug directives in my PHP Version 8 site’s php.ini.hbs file. Note that I’ve commented out the line xdebug.start_with_request.

xdebug.mode=debug
xdebug.client_port="9000"
; xdebug.start_with_request=yes
xdebug.discover_client_host=yes

Now that we’ve switched our site to PHP Version 8 if we check the output of our pi.php file that we created earlier, we can see that Xdebug Version 3 is now loaded, where Version 2.9.0 was being used under our PHP Versions 7.3 and 7.4 sites.

Xdebug version 3

One of the cool features that comes bundled with Xdebug Version 3 is the addition of the xdebug_info() function. This is similar to the php_info() function, but it provides more detailed diagnostics for about the Xdebug setup.

To use it, simply add a file to your site’s web root. For example, xdebug-info.php , then add the following contents:

<?php
xdebug_info();

Load that file up in your browser, and you’ll see something like this:

xdebug_info output - debugger not listening

In the screenshot above, the diagnostics log is indicating a problem connecting to the host on port 9000. The reason for this is that I have not enabled VS Code to listen for debugging.

So, I tap F5 to enable debugging, and now when I reload my xdebug-info.php, the Diagnostics Log is clean, and I’m ready to debug. Thanks to fellow WebDevStudios Backend Engineer, Biplav Subedi, for this tip!

xdebug_info output - debugger is listening

Troubleshooting

One common issue that comes up when you’re debugging WordPress is that the debugger does not stop on the breakpoint that you’ve set. This is typically caused by a port conflict—some other process is already using the port that you’ve configured for debugging.

Make sure that no other application is using the port that was configured in the php.ini.hbs and launch.json file. If an application is already using the port you’ve specified, make sure to change your port to something that’s not in use.

To check for a port conflict, end your debugging session in VS Code then run the following command:

Windows CMD: netstat -an | find "9000"

Linux/Mac: sudo netstat -nap | grep ":9000"

You should not see any output after entering these commands. If you do, that means that a process is already using the port you’ve configured for Xdebug (9000) in our example. So you should either configure a different port in your php.ini.hbs and launch.json files, or locate the process that is tying up the port, and stop it/configure it to use a different port.

Bonus: Quick and Dirty Debugging

Sometimes, instead of using Xdebug, I prefer to simply log variables to WP’s error.log file using PHP’s error_log().

I find this handy for real quick stuff, though it’s really not the best way to debug WordPress when things get serious. For this setup, first, add the following statements to your site’s wp-config.php file:

define( 'WP_DEBUG', true ); // Debugging mode activated.
define( 'WP_DEBUG_LOG', true ); // Logs to wp-content/debug.log
define( 'WP_DEBUG_DISPLAY', false ); // Don't add errors to the output.
define( 'SCRIPT_DEBUG', true ); // Load un-minified scripts.

Now, errors will be logged to your site’s wp-content/debug.log file. I typically keep this file open in a side panel of VS Code.

error logging to debug.log

I usually use this one-liner to output values to the debug.log file:  error_log( '$variable_name ' . var_export( $variable_name, true ) );

To make things easier, I trigger this one-liner using a VS Code User Snippet with the trigger logv. Here’s a copy of the debugging-related snippets I use. These are configured in VS Code under File > Preferences >  Configure User Snippets > PHP.

{
// Place your snippets for php here. Each snippet is defined under a snippet name and has a prefix, body and
// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
// same ids are connected.
// Example:
// "Print to console": {
// "prefix": "log",
// "body": [
// "console.log('$1');",
// "$2"
// ],
// "description": "Log output to console"
// }
"Log var_export()": {
"prefix": "logv",
"body": ["error_log( '$1 ' . var_export( $2, true ) );"],
"description": "Do a var_export( $variable ) to PHP error log."
},
"Log print_r()": {
"prefix": "logp",
"body": ["error_log( print_r( $0, true ) );"],
"description": "Do a print_r( $variable ) to PHP error log."
},
"Exit with var_dump()": {
"prefix": "xvd",
"body": ["exit( var_dump( $0 ) );"],
"description": "Exit with var_dump()"
},
"Exit with print_r()": {
"prefix": "xpr",
"body": ["exit( print_r( $0 ) );"],
"description": "Exit with print_r()"
},
"Detailed Error Log": {
"prefix": "logd",
"body": [
"error_log( print_r( (object)",
"t[",
"tt'line' => __LINE__,",
"tt'file' => __FILE__,",
"tt'dump' => [",
"ttt$0,",
"tt],",
"t], true ) );"
],
"description": "Detailed error logging"
},
"Log gettype()": {
"prefix": "logt",
"body": ["error_log( gettype( $0 ) );"],
"description": "Do a gettype( $variable ) to PHP error log."
},
"Debug Filters": {
"prefix": "logf",
"body": ["add_action( 'all', function() { error_log( var_export( current_filter(), true ) ); } );"],
"description": "Logs current filter."
}
}

Conclusion

That’s about it for this post on debugging WordPress using Xdebug, Local, and VS Code. Using Xdebug, you’ll be able to more efficiently and effectively debug code. If you’ve never used it before, I’m sure you will find that Xdebug is a helpful tool in your development arsenal.

The post Debugging WordPress Using Xdebug, Local, and VS Code appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2022/10/06/debugging-wordpress/feed/ 6 25376
Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug https://webdevstudios.com/2019/04/16/debugging-wordpress-with-local-by-flywheel-neovim-and-xdebug/ https://webdevstudios.com/2019/04/16/debugging-wordpress-with-local-by-flywheel-neovim-and-xdebug/#respond Tue, 16 Apr 2019 16:00:53 +0000 https://webdevstudios.com/?p=20143 Introduction Local by Flywheel is a popular tool for getting quick and reliable WordPress installations running on your computer. One of its lesser-known features is the inclusion of xdebug support. xdebug is a PHP extension that allows for real-time debugging of PHP code. Today, we’re going to go over how to get both of these Read More Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug

The post Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug appeared first on WebDevStudios.

]]>
Introduction

Local by Flywheel is a popular tool for getting quick and reliable WordPress installations running on your computer. One of its lesser-known features is the inclusion of xdebug support. xdebug is a PHP extension that allows for real-time debugging of PHP code. Today, we’re going to go over how to get both of these working together within vim to provide a powerful interface that allows for some successful debugging of WordPress.

Prerequisites

Firstly, this tutorial is intended for users of vim or neovim. If you aren’t familiar with how to use vi-like editors, but want to learn, I would recommend running vimtutor in your command line and learning how to move and work in vim before continuing with this post.

Next, you’ll need Local by Flywheel. You can download it here. If you haven’t set up a site before with Local, it is pretty straightforward. You can find a guide for getting started on Flywheel’s blog.

Setup

vim

For vim or neovim, henceforth referred to simply as “vim” (with distinctions for neovim if necessary), you will need the Vdebug plugin. Installation instructions are included on the plugin’s page. I use vim-plug to manage plugins; so my .vimrc looks like this:

""" Vim-Plug
call plug#begin()
Plug 'vim-vdebug/vdebug'
call plug#end()

After adding Vdebug, we’ll need to add some configuration. Before we continue, let’s get Local configured for xdebug.

Local and xdebug

Local ships with the xdebug extension available but not enabled. Each site that you want to debug will need its configuration altered to work with debugging. First, find your Local site site’s directory. In Local, you can view this on the Overview tab, under “Site Path.”

Open your site’s directory, and find the file conf/php/<your site's PHP version>/php.ini. Open this file with any text editor and find the section titled [Xdebug]. This contains the relevant configuration we’re looking for. After modifying this section, your section should look similar to:

xdebug.remote_enable=1
xdebug.remote_connect_back=On
xdebug.remote_port="9000"
xdebug.profiler_enable=1
xdebug.remote_autostart=true
xdebug.remote_handler=dbgp
xdebug.remote_mode=req
xdebug.remote_host=<your local IP>

Note that the remote_host argument should be your computer’s local IP. This will allow the Local machine to talk to your editor.

Save your modifications, and restart your site in Local.

Configuring vim

Open your vim configuration file. Typically, for vim, this will be ~/.vimrc, in NeoVim, your configuration is usually in ~/.config/nvim/init.vim. Add a new section to your vimrc that looks like this:

let g:vdebug_options= {
    "port" : 9000,
    "server" : '',
    "timeout" : 20,
    "on_close" : 'detach',
    "break_on_open" : 0,
    "ide_key" : '',
    "path_maps" : {
        '/app/public/': '<path to your project public folder>'
    },
    "debug_window_level" : 0,
    "debug_file_level" : 0,
    "debug_file" : "",
    "watch_window_style" : 'compact',
    "marker_default"     : '⬦',
    "marker_closed_tree" : '▸',
    "marker_open_tree" : '▾'
}

Note that you need to fill in the path_map item with your local project’s public folder. If your project is located in /Users/you/Local/myproject/, your public folder would be in /Users/you/Local/myproject/app/public/. Also note that the left-hand side points to /app/public/. This is where Local’s server stores your public files. The right-hand side points to the location of the files as you see them in your filesystem.

Now, save your vim configuration and restart vim (you can probably source the configuration, but Vdebug can be a little weird sometimes). Open a file in your project. Let’s try wp-config.php to start. Find a line with code before wp-settings.php is included and press <F10> on your keyboard.

The line should change color. In my editor, it shows a green line where I set the breakpoint:

Now, press <F5> and you should see a message in the status line saying that “Vdebug will wait for a connection in the background.” Visit any page in your site, and you should see Vdebug connect and pause on the line you set as a breakpoint:

Troubleshooting

Here are some tips if you’re having trouble with Vdebug:

  • If the debugger is attaching and then stopping, verify the path_maps configuration.
  • If the debugger is not attaching, verify your Xdebug configuration in your php.ini.

Working with the Debugger

Author note: the following code takes place in the twentynineteen theme. The premise of this exercise is ridiculous, and meant to be an example of how to use the debugging functionality.

Vdebug includes a number of default key mappings, as well as some commands to help evaluate your code. Open your theme’s functions.php and add the following:

add_filter( 'the_content', function( $content ) {
    if ( is_admin() ) {
        return $content;
    }

    return str_rot13( $content );
} );

Now, travel to a single post on your site’s frontend, and view a post:

Whoops, seems something has gone wrong! Let’s suppose this code is buried somewhere deep in our included files; it could be a pain to find the source of this issue. With xdebug, we can trace the code back to our bad filter—the one that we “totally don’t know about…”

First, open up template-parts/content/content-single.php, and find the line calling the_content:

23         the_content(
24             sprintf(
25                 wp_kses(
26                     /* translators: %s: Name of current post. Only visible to screen readers */
27                     __( 'Continue reading<span class="screen-reader-text"> "%s"</span>', 'twentynineteen' ),
28                     array(
29                         'span' => array(
30                             'class' => array(),
31                         ),
32                     )
33                 ),
34                 get_the_title()
35             )
36         );

Since we know our issue is in the content being output, move your cursor on the line with the call to the_content and press <F10> on your keyboard. The line should highlight to indicate that you have set a breakpoint.

Before continuing, it’s a good time to review some of Vdebug‘s key mappings from the Quick Guide section of the README:

<F5>: start/run (to next breakpoint/end of script)
<F2>: step over
<F3>: step into
<F4>: step out
<F6>: stop debugging (kills script)
<F7>: detach script from debugger
<F9>: run to cursor
<F10>: toggle line breakpoint
<F11>: show context variables (e.g. after "eval")
<F12>: evaluate variable under cursor
:Breakpoint <type> <args>: set a breakpoint of any type (see :help VdebugBreakpoints)
:VdebugEval <code>: evaluate some code and display the result
<Leader>e: evaluate the expression under visual highlight and display the result

We will primarily be focused on <F5>, <F3>, <F4>, <F9>, and <F10>. Remember, if you get lost, you can always press <F6> to quit the debugger and then start again.

Next, to start the debugger, press <F5>. You should see the following message in your status line: “Vdebug will wait for a connection in the background.” Reload the page in your browser and you should be presented with the debugging window.

The debugger should halt on our breakpoint. From here, we’ll want to “step into” the function calls to decipher what’s going on using <F3>. When we first step in, you’ll notice we’re not inside the_content, but __. What’s going on? PHP executes methods from the innermost function call to the outermost. Since our breakpoint is actually on a set of nested function calls, we’ll need to press <F4> to step out” of each function until we get to the_content:

Once we’re in the content, we can see a call to apply_filters. Knowing how WordPress works with Actions and Filters, it’s a safe bet that our content is being modified in a filter. Move your cursor to the line calling apply_filters, and press <F9> to allow the program to run until we get to that line.

Next, press <F3> to step into apply_filters. I’ll tell you, this function is a little confusing. We just want to worry about the line that actually calls the filter methods:

    $filtered = $wp_filter[ $tag ]->apply_filters( $value, $args );

Put your cursor on that line and press <F9> again, and then “step in” with <F3>. As you enter the apply_filters method, bear in mind that the crux of WordPress hooks are callbacks. With that in mind, it’s safe to say the following lines are where the magic happens:

282                 // Avoid the array_slice if possible.
283                 if ( $the_['accepted_args'] == 0 ) {
284                     $value = call_user_func_array( $the_['function'], array() );
285                 } elseif ( $the_['accepted_args'] >= $num_args ) {
286                     $value = call_user_func_array( $the_['function'], $args );
287                 } else {
288                     $value = call_user_func_array( $the_['function'], array_slice( $args, 0, (int)$the_['accepted_args'] ) );
289                 }

Lines 284, 286, and 288 all use call_user_func_array in some form or fashion. Place your cursor on each line and press <F10> to add a breakpoint, and then hit <F5> to continue execution. The debugger will begin breaking on one of those three lines.

The Watch Window

Vdebug displays a window where you can watch the variables that are available in various scopes. By default, the “Locals” scope is shown.

This is a window just like any other vim window. Move your cursor to the Locals window, and scroll down until you find the $the_ array (hint: you can search with normal vim commands); expand it by using the <Enter> key. Next, you should look at the value of $the_["function"]. Notice that this will either be an array or a string. Expand the array or view the string with each run of <F5>, looking for anything that may stick out as odd.

Did you find it? There’s a Closure. Since we can’t see what it does here, we’ll need to “step in” again with <F3>. The debugger now drops us into the offending method—the filter we added earlier calling str_rot13.

Wrapping Up

With this ridiculous example, I hope you are able to use xdebug in your own projects to effectively debug. Understanding the WordPress codebase is crucial to being an effective developer, and getting down and dirty with a debugger is a great way to learn how truly complex a system can be.

Tips

  • Vdebug can be fickle – you may need to hit <F6> a couple of times to close the debugger completely.
  • Use :help Vdebug and read the documentation to learn about things like <leader>e.
  • Use project-specific .vimrc files to set up your Vdebug paths:

In the following examples, use .vimrc for vim and init.vim for neovim:

" In your ~/.vimrc or ~/.config/nvim/init.vim
set exrc " see :help exrc

" At the BOTTOM of your RC file:
set secure

This will allow you to set up a configuration for each project. vim with search for either .vimrc, _vimrc, or .exrc in your current directory and load it if found. For neovim, the file names are .nvimrc, _nvimrc, and .exrc. I tend to work from the wp-content folder to make use of tags for my plugins and themes. Depending on where you start your editing, place your RC file in the appropriate location and add your vdebug_options configuration in there. Here’s mine in ~/src/WDS/local/lab/app/public/wp-content/.nvimrc:

" Local 'Lab' {{{
let g:vdebug_options= {
    "port" : 9000,
    "server" : '',
    "timeout" : 20,
    "on_close" : 'detach',
    "break_on_open" : 0,
    "ide_key" : '',
    "path_maps" : {
        '/app/public/': '/Users/phatsk/src/WDS/local/lab/app/public/'
    },
    "debug_window_level" : 0,
    "debug_file_level" : 0,
    "debug_file" : "",
    "watch_window_style" : 'compact',
    "marker_default"     : '⬦',
    "marker_closed_tree" : '▸',
    "marker_open_tree" : '▾'
}
" }}}

Now, I don’t have to worry about resetting things in my init.vim whenever I switch projects!

Actual Conclusion

You made it! In this post you (hopefully) learned:

  • How to enable xdebug in your Local installations
  • Install the Vdebug plugin for neo/vim
  • Effectively use Vdebug to track down bugs in code.

Happy bug squashing!

The post Debugging WordPress with Local by Flywheel, (neo)vim, and xdebug appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2019/04/16/debugging-wordpress-with-local-by-flywheel-neovim-and-xdebug/feed/ 0 20143
Debugging with Xdebug, VVV, and Sublime Text https://webdevstudios.com/2014/11/13/debugging-with-xdebug-vvv-and-sublime-text/ https://webdevstudios.com/2014/11/13/debugging-with-xdebug-vvv-and-sublime-text/#comments Thu, 13 Nov 2014 15:47:14 +0000 http://webdevstudios.com/?p=8645 ARE YOU READY TO TAKE YOUR DEBUGGING TO THE NEXT LEVEL?! ARE wp_die AND print_var JUST NOT CUTTING IT!? XDEBUG IS THE ANSWER! Xdebug is a PHP extension that provides advanced debugging capabilities such as breakpoints, watch expressions, and more in-depth error reporting. Setup Xdebug Xdebug needs to be set up with your local hosting system, whether that is MAMP, Read More Debugging with Xdebug, VVV, and Sublime Text

The post Debugging with Xdebug, VVV, and Sublime Text appeared first on WebDevStudios.

]]>
ARE YOU READY TO TAKE YOUR DEBUGGING TO THE NEXT LEVEL?!

ARE wp_die AND print_var JUST NOT CUTTING IT!?

20130422162353!Explosion

XDEBUG IS THE ANSWER!

Xdebug is a PHP extension that provides advanced debugging capabilities such as breakpoints, watch expressions, and more in-depth error reporting.

Setup Xdebug

Xdebug needs to be set up with your local hosting system, whether that is MAMP, Vagrant, or a custom solution. I will be going over how to set it up with Vagrant and Varying Vagrant Vagrants (VVV). MAMP also has a pretty simple system for getting it running.

VVV has Xdebug installed by default, but it needs to be manually activated. You can do this by ssh-ing into the Vagrant instance (vagrant ssh) and running xdebug_on. You will need to do this after each time you destroy and recreate the Vagrant instance.

You can also turn off Xdebug (if the extended error messages are bugging you) by ssh-ing into Vagrant and running xdebug_off.

So now that you have Xdebug running, how do we dig into the good stuff? First off, your PHP error notices will be replaced with something like this:

XDebug Error Notice

This more descriptive notice shows you the stack trace of the error, meaning you get to see everything that led up to this error (which function called which function called the function that the error occurred in) and allows you to get a better idea of the context of the error.

But there is a lot more to Xdebug than that! In order to get the rest of Xdebug’s expanded debug capabilities you need a Xdebug client– I’m going to show how to hook up the Sublime Text Xdebug plugin.

First install the plugin using the Sublime Text Package Control (which of course you already have installed) by pressing CTRL-SHIFT-P and choosing “Package Control: Install Package”, and then selecting “Xdebug Client”.

Screenshot 2014-10-27 13.29.57

Once the client is installed, you need to configure it to properly interface with VVV’s Xdebug setup. Open the Xdebug Client’s settings by pressing CTRL-SHIFT-P and then select “Preferences: Xdebug Settings – User” (You can view more available options by selecting “Preferences: Xdebug Settings – Default”).

{"path_mapping":{"\/srv\/www":"\/path\/to\/vagrant-local\/www"},"max_depth":5}

Just change “/path/to/vagrant-local/www” to the absolute path to your VVV www folder, and the Sublime Text Xdebug Client will know where to look for your local code.

Using Xdebug

Now that you have Xdebug activated and connected to Sublime Text, you can control the Xdebug Client by pressing CTRL-SHIFT-P and running the various Xdebug commands.

Screenshot 2014-10-27 15.50.01

One of the best features of Xdebug is the ability to add breakpoints and run through your code line by line. Let’s say you are having a mysterious issue and you want to see what exactly is going on at one point in your code.

Screenshot 2014-11-05 14.25.14

This little plugin is pretty simple, you can probably already see the reason that ‘THE PLUGIN WORKS” isn’t output after the post content, but this is just an example. Much larger, more complex bugs can be fixed by following this same method.

So we have our code, we have the post being rendered without the ‘THE PLUGIN WORKS’ text at the end, and we have no idea why. Lets add a breakpoint! By moving the cursor to line 25 and pressing “CMD-F8” or “CMD-SHIFT-P” then  searching for “Xdebug: Add/Remove Breakpoint”.

Screenshot 2014-11-05 14.32.07

That little dot next to the line means we have a breakpoint there! Make sure Xdebug is on in VVV and connect Sublime Text to VVV’s Xdebug by running the “Xdebug: Start Debugging” command (CMD-SHIFT-F9).

Now go back to the browser and refresh the page. It will seem like it starts to load, and then hangs loading indefinitely. This is because the breakpoint has taken effect and paused the PHP process so you can take a look. Switch back to Sublime Text and it should look something like this:

Screenshot 2014-11-05 14.33.49

The yellow arrow marks the line that PHP has paused at, this line has not run yet. The Xdebug Context window shows local and global variables that are currently accessible. The Xdebug Stack window shows everything that led up to this point in the process (what chain of functions led to the current function being called).

For this bug we are paying attention to the Xdebug Context, we want to see why nothing is added to the $content variable. If I expand the $this object so we can inspect the local to_append variable I can see that it is empty:

Screenshot 2014-11-05 14.34.26

Looking back up at the constructor function I can see that the variable was never assigned to, so adding $this->to_append = $append_text; to right after line 17 fixes the problem. Go ahead and detach the current debug process by pressing CMD-SHIFT-P and searching for “Xdebug: Breakpoint – Detach” this will let the page continue to load.

Once the fix has been made I can refresh the page again, the breakpoint will take effect again and this time I can see in the Xdebug Context that my fix has worked:

Screenshot 2014-11-05 14.37.39

and if I run “Xdebug: Stop Debugging” (and “Xdebug: Restore Layout”) the page will finish loading and I can confirm the plugin works as intended:

Screenshot 2014-11-05 14.37.50

Going Deeper

There is a lot more power to Xdebug than what I have shown you so far, when you are at a breakpoint you can also navigate through the code to see how things play out.

Screenshot 2014-11-05 15.27.50

Using these three-step functions you can:

  • Step Into – Enter the function invoked at the current line and continue debugging. Use this if you are getting unexpected results from a function call and want to investigate further.
  • Step Out – Exit the current function to the function that called this function (check the Xdebug Stack to see what this is).
  • Step Over – Run the current line and move to the next line. Repeatedly running this allows you to go step by step through a function and see what is happening.

It can even be fun to navigate bug-free code with these tools to just see everything in slo-mo action.

cool-slo-mo-gif-3479-19662-hd-wallpapers

So go ahead and dive in! It may seem intimidating at first but it is incredibly powerful and gives so much more information and control than logging can. If you aren’t using VVV and Sublime Text there are other methods of getting Xdebug working, and I recommend looking into it, it’s worth it!

More Resources

The post Debugging with Xdebug, VVV, and Sublime Text appeared first on WebDevStudios.

]]>
https://webdevstudios.com/2014/11/13/debugging-with-xdebug-vvv-and-sublime-text/feed/ 1 8645