How to merge 2 PHP Code Sniffer or Clover xml reports


Sometimes you need to have two separate rule sets for PHP Code Sniffer. In my case I have one rule set for the source code and another rule set for the unit tests. However, when you have 2 separate rule sets you cannot get a single report, so my solution was to create a php script to merge the two after each one ran individually.

$lobjArgs = $_SERVER['argv'];

$lobjFiles = preg_grep("/^((?!.*(phpcs-merge\.php)).*)/", $lobjArgs);
$lobjFiles = preg_grep('/^((?!(--output)).*)/',$lobjFiles);
$lobjFiles = array_values($lobjFiles);

$lobjOptions = getopt('',array('output:'));

if(count($lobjFiles) >= 2)
{
    $lobjXmlAggregate = simplexml_load_file($lobjFiles[0]);

    $i = 1;

    while($i < count($lobjFiles))
    {
        $lobjXmlNext = simplexml_load_file($lobjFiles[$i]);
        foreach($lobjXmlNext->file as $file)
        {
            $lobjAddChild = $lobjXmlAggregate->addChild('file',$file);
            foreach($file->attributes() as $key => $value)
            {
                $lobjAddChild->addAttribute($key,$value);
            }

            foreach($file->error as $error)
            {
                $lobjAddError = $lobjAddChild->addChild('error',$error);

                foreach($error->attributes() as $key =>$value)
                {
                    $lobjAddError->addAttribute($key,$value);
                }
            }

        }
        $i++;
    }

    $lobjFileHandle = fopen($lobjOptions['output'],'w') or die("can't open file phpcs-merged.xml");
    fwrite($lobjFileHandle, $lobjXmlAggregate->asXML());
    fclose($lobjFileHandle);
}

echo "Merge complete"

Here’s what my Ant build target looks like.

 <target name="phpcs-merge" description="Merge phpcs-tst and phpcs-src files">
    <exec executable="${php-exe}/php.exe">
        <arg path='${config}/phpcs-merge.php' />
        <arg value='--output=${workspace}/build/logs/checkstyle-merged.xml' />
        <arg path="${workspace}/build/logs/checkstyle-src.xml" />
        <arg path="${workspace}/build/logs/checkstyle-tst.xml" />
    </exec>
 </target>

Another situation I use xml merging for is when I want to get code coverage reports for a lot of source code but an out of memory exception occurs if I try to run the coverage report on all of the code at once.

Leave a comment

Your email address will not be published. Required fields are marked *