phptestingphpmd

PHPMD Catch/Suppress fatal errors


I'm trying to automate my testing. As a smoke test I would like to check my PHP code with PHPMD before continuing with the actual Unit tests. Sounds sensible enough right?

Thing is that PHPMD seems to crash when fatal errors arise in my PHP files. For a test I added an extra accolade at a function definition like so:

function foo() {{
    // Stuff
}

Were I expected a 1 exit code, PHPMD seems to crash completely and instead returns a 0 exit code. Rendering my automated script useless. Is there a way to suppress these errors and return the expected exit code? For PHPUnit the --process-isolation option solved this problem but I can't seem to find such option for PHPMD.

Relevant automated testing code

#!/usr/bin/php
<?php

    exec('meta/phpmd', $output, $returnCode);
    if ($returnCode == 1) {
        echo '[Fail] PHP code is breaking', PHP_EOL;
        exit(1);
    } elseif ($returnCode == 2) {
        echo '[Warn] PHP code is unclean', PHP_EOL;
    } else {
        echo '[OK] Code is clean! ', PHP_EOL;
    }

Solution

  • As a workaround (and possible solution) one could check the syntax before passing it to PHPMD. I changed my testing code to this:

    #!/usr/bin/php
    <?php
    
    $dir_root = dirname(dirname(__DIR__));
    $dir_php  = $dir_root . DIRECTORY_SEPARATOR . 'api' . DIRECTORY_SEPARATOR . 'App';
    
    exec('find ' . $dir_php . ' -iname *.php | xargs -n1 php -l 2>/dev/null', $output, $returnCode);
    if ($returnCode != 0) {
        echo '[Fail] PHP contains syntax errors', PHP_EOL,
             implode(PHP_EOL, $output), PHP_EOL;
        exit($returnCode);
    }
    
    exec('meta/phpmd', $output, $returnCode);
    if ($returnCode == 1) {
        echo '[Fail] PHP code is breaking', PHP_EOL;
        exit(1);
    } elseif ($returnCode == 2) {
        echo '[Warn] PHP code is unclean', PHP_EOL;
    }
    

    Credits to Winglian at Reddit for the mass php -l code https://www.reddit.com/r/PHP/comments/2t7mvc/lint_an_entire_directory_of_php_files_in_parallel/