Last active
September 16, 2024 16:46
-
-
Save derickr/d5fbab31f50e414acedbab99ac0fc596 to your computer and use it in GitHub Desktop.
save-code-coverage.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require 'vendor/autoload.php'; | |
use SebastianBergmann\CodeCoverage\Filter; | |
use SebastianBergmann\CodeCoverage\Driver\Selector; | |
use SebastianBergmann\CodeCoverage\CodeCoverage; | |
use SebastianBergmann\CodeCoverage\Report\PHP as PhpReport; | |
use SebastianBergmann\FileIterator\Facade as FileIteratorFacade; | |
$filter = new Filter; | |
$filter->includeFiles((new FileIteratorFacade)->getFilesAsArray( __DIR__ . '/html')); | |
$filter->includeFiles((new FileIteratorFacade)->getFilesAsArray( __DIR__ . '/src')); | |
$filter->includeFiles((new FileIteratorFacade)->getFilesAsArray( __DIR__ . '/views')); | |
$coverage = new CodeCoverage( | |
(new Selector)->forLineCoverage($filter), | |
$filter | |
); | |
$coverage->start($_SERVER['REQUEST_URI']); | |
function save_coverage() | |
{ | |
global $coverage; | |
$coverage->stop(); | |
(new PhpReport)->process($coverage, '/tmp/path/crawler/' . bin2hex(random_bytes(16)) . '.cov'); | |
} | |
register_shutdown_function('save_coverage'); | |
?> |
I've updated the GIST to use the FileIterator manually now.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I found this from your excellent YouTube video on generating code coverage inside the built in web server for php.
In September 2024, the current version of phpunit/php-code-coverage (version 11.0.6) does not have an includeDirectory method in the filter class.
To work round that very quickly while I got going, I just generated a static list of files in my project in a php file like this
Then in save-code-coverage.php, I just did
include 'all-my-files.php';
and instead of the includeDirectory calls, just did
$filter->includeFiles($myprojectfiles);
After that, code coverage is gathered correctly without any more changes to the script.
(Of couse, there are lots of other ways to dynamically build a list of files, but having a static list is really quick for execution and was very easy to implement from the shell on my Unix box without needing any more php code.)
Also, another note that is possibly useful for someone. In the project I was working on, there was no other routing used, so no other router script to plug this coverage trigger script into. However, it can work perfectly as a router script on its own - just add
return false;
at the end of the script. For the php built in web server, return false in a router script indicates to not do any routing and to just serve the requested URI directly. As my application was directly calling named files, this was fine for me.