Function call logging with Patchwork 02

I put some discernment into function call logging.

The idea

I’d like to be able to provide myself with a tool, a WordPress plugin specifically, to be used in staging environment and that would allow me to create ad-hoc adapter classes to be used in test-driven development of WordPress plugins and themes with as little effort as possible.
The “ad hoc” (“specific to the plugin or theme being developed”) part of it would require knowing which functions the plugin or theme calls and logging those. The reason for doing that I’ve explained in an earlier post.

Application of Patchwork

In my previous post I’ve written a simple test to see if the idea could work and moved on from that to another test to apply some discernment to the logger.
The purpose of the test is to log calls to the get_post_meta globally defined function coming from the tests/unit/CallerClass1.php class alone; the class is a prototype of what a class using WordPress function would be:


class CallerClass1 {

    public function call_global_function() {

and simply calls the function.
The test, in the tests/unit/PatchworkTest.php file, has the get_post_meta function definition in its head and will “log” (here just a $calls++ setting) only calls to the function coming from the CallerClass1 class file.


function get_post_meta() {
    return 'foo';

class PatchworkTest extends \PHPUnit_Framework_TestCase {

    protected function setUp() {

     * @test
     * it should allow filtering the call logging by caller class
    public function it_should_allow_filtering_the_call_logging_by_caller_class() {
        // set up
        $calls = 0;

        Patchwork\replace( 'get_post_meta', function () use ( &$calls ) {
            $backtrace = debug_backtrace( true );
            $target_file = __DIR__ . '/CallerClass1.php';
            $matches = array_filter( $backtrace, function ( $entry ) use ( $target_file ) {
                if ( ! isset( $entry['file'] ) ) {
                    return false;

                return ( strpos( $entry['file'], $target_file ) === 0 );
            } );
            if ( count( $matches ) > 0 ) {
                $calls ++;
        } );

        $class1 = new CallerClass1;

        // execute 
        // should log these
        // should not log these: not from CallerClass1

        // assert
        $this->assertEquals(2, $calls);

The test works. Function call logging tests success


I will be structuring the tests better and begin TDDing some accessory classes to support the function logging.