Using var_export to Refactor Legacy Code
When you’re working with legacy code some times you need to add testing to an additional piece of form processing that has no tests. I find it helpful to break out the form processing code into it’s own class so it’s easier to test but if you’re not lucky it could be a large complicated form with lots of options so setting up a test case can be difficult. var_export is an excellent solution to get the posted data out so you can use it.
What’s var_export
var_dump outputs information about a variable that are helpful for debugging but var_export outputs a parsable string of a variable so it can be reused in PHP.
Output:
Example
So how do we use this for testing?
Let’s look at this following example:
1. Create a Test
First things we want to do is create a test with a basic check to make sure we’re on the right path:
2. Generate Some Test Data
Next we need to generate some test data. I do this by filling out the form with every weird option that might exist. Then inside the controller I add three lines:
In our example this looks like:
Then we’ll copy and paste the output directly into our test:
3. Break Out the Form Processing Logic
Next we need to create a new function in our ItemFormProcessorFromExistingForm
class to process the data and insert it into the controller.
4. Get Your Test Running
Now that we have the function broken it’s own function it’s important to make sure it the test is running. In a lot of cases you might need to setup instances of additional classes (maybe the logged in user?). The important thing is to get the test running
5. Make Sure You Aren’t Missing Any Critical Code
The next step is to generate a code coverage report on the tested function and verify you’re covering all the important parts. I try to get to at least 90% code coverage and make sure all the weird looking parts are covered.
5. Refactor
Now it’s time to clean up the legacy code!
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows