Question

I am using the php-code-coverage to collect coverage information from one HTTP request (thru apache). I'd like to store the coverage data from several requests, and then collate the results into one comprehensive report.

Is this easy to do? I was hoping for something along the lines of:

<?php
require 'PHP/CodeCoverage/Autoload.php';

$coverage = new PHP_CodeCoverage;
$coverage->start('<some request>');

// ...

$coverage->stop();

$writer = new PHP_CodeCoverage_Report_XXX;
$writer->process($coverage, '/tmp/reportYYY.xml');


// at some later date, collate all the results.
$writer = new PHP_CodeCoverage_Report_HTML;
$writer->process('/tmp/reportX.xml');
// ...
$writer->process('/tmp/reportZ.xml');
Was it helpful?

Solution

I've managed to get this running using phpcov (installed via composer) as mentioned:

Using Apache .htaccess to prepend/append php scripts that serialize PHP_CodeCoverage object to file, you'll need to adjust paths appropriately:

.htaccess:

# Prepend the file
php_value auto_prepend_file "prepend.php" 

# Append file to bottom of page
php_value auto_append_file "append.php" 

prepend.php:

<?php
require_once '../vendor/autoload.php';
$coverage = new PHP_CodeCoverage;
$coverage->start('Site coverage');

append.php:

<?php

$coverage->stop();
$cov = serialize($coverage); //serialize object to disk
file_put_contents('../cov/site.' . date('U') . '.cov', $cov);

Because I'm serializing the object I had to edit /vendor/phpunit/phpcov/src/MergeCommand.php:

protected function execute(InputInterface $input, OutputInterface $output)
{
    $mergedCoverage = new PHP_CodeCoverage;

    $finder = new FinderFacade(
        array($input->getArgument('directory')),
        array(),
        array('*.cov')
    );

    foreach ($finder->findFiles() as $file) {
        print "Merging $file" . PHP_EOL;
        //$_coverage = include($file);
        $_coverage = unserialize(file_get_contents($file));
        $mergedCoverage->merge($_coverage);
        unset($_coverage);
    }

    $this->handleReports($mergedCoverage, $input, $output);
}

Then using phpcov, create the report:

./vendor/bin/phpcov merge --html="./cov/report/" ./cov -vvv
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top