Xdebug.php (2424B)
1 <?php 2 /* 3 * This file is part of the PHP_CodeCoverage package. 4 * 5 * (c) Sebastian Bergmann <sebastian@phpunit.de> 6 * 7 * For the full copyright and license information, please view the LICENSE 8 * file that was distributed with this source code. 9 */ 10 11 /** 12 * Driver for Xdebug's code coverage functionality. 13 * 14 * @since Class available since Release 1.0.0 15 * @codeCoverageIgnore 16 */ 17 class PHP_CodeCoverage_Driver_Xdebug implements PHP_CodeCoverage_Driver 18 { 19 /** 20 * Constructor. 21 */ 22 public function __construct() 23 { 24 if (!extension_loaded('xdebug')) { 25 throw new PHP_CodeCoverage_Exception('This driver requires Xdebug'); 26 } 27 28 if (version_compare(phpversion('xdebug'), '2.2.0-dev', '>=') && 29 !ini_get('xdebug.coverage_enable')) { 30 throw new PHP_CodeCoverage_Exception( 31 'xdebug.coverage_enable=On has to be set in php.ini' 32 ); 33 } 34 } 35 36 /** 37 * Start collection of code coverage information. 38 */ 39 public function start() 40 { 41 xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE); 42 } 43 44 /** 45 * Stop collection of code coverage information. 46 * 47 * @return array 48 */ 49 public function stop() 50 { 51 $data = xdebug_get_code_coverage(); 52 xdebug_stop_code_coverage(); 53 54 return $this->cleanup($data); 55 } 56 57 /** 58 * @param array $data 59 * @return array 60 * @since Method available since Release 2.0.0 61 */ 62 private function cleanup(array $data) 63 { 64 foreach (array_keys($data) as $file) { 65 unset($data[$file][0]); 66 67 if ($file != 'xdebug://debug-eval' && file_exists($file)) { 68 $numLines = $this->getNumberOfLinesInFile($file); 69 70 foreach (array_keys($data[$file]) as $line) { 71 if (isset($data[$file][$line]) && $line > $numLines) { 72 unset($data[$file][$line]); 73 } 74 } 75 } 76 } 77 78 return $data; 79 } 80 81 /** 82 * @param string $file 83 * @return int 84 * @since Method available since Release 2.0.0 85 */ 86 private function getNumberOfLinesInFile($file) 87 { 88 $buffer = file_get_contents($file); 89 $lines = substr_count($buffer, "\n"); 90 91 if (substr($buffer, -1) !== "\n") { 92 $lines++; 93 } 94 95 return $lines; 96 } 97 }