Last active
November 17, 2017 02:56
-
-
Save rheinardkorf/8616d0f7f33d9a3459bd4121a24934ae to your computer and use it in GitHub Desktop.
Example snippet to determine supported PHP versions using PHPCompatibility sniffs and phpcs.
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 | |
function check_compatibility( $audit_files_directory, $phpcs_report_file, $phpcompat_report_file, $lowest_version = '5.2' ) { | |
// Official PHP versions. | |
// Note: Does not include patch releases as PHPCompatibility doesn't get this granular. | |
$php_versions = array( | |
'5.2', | |
'5.3', | |
'5.4', | |
'5.5', | |
'5.6', | |
'7.0', | |
'7.1', | |
'7.2', | |
); | |
$compatible_versions = array(); // PHP versions that this code is compatible with. | |
$compat = array(); // Sniff results keyed by PHP version. | |
// Run phpcs with PHPCompatibility standard. | |
// Note: The $lowest_version is important as it will flag all errors from most recent version to the $lowest_version. | |
exec( 'phpcs -p ' . $audit_files_directory . ' --standard=PHPCompatibility --runtime-set testVersion ' . $lowest_version . ' --report=json --report-file=' . $phpcs_report_file ); | |
// Only proceed if phpcs successfully created a report file. | |
if ( file_exists( $phpcs_report_file ) ) { | |
$json = file_get_contents( $phpcs_report_file ); | |
$json = json_decode( $json, true ); | |
// Map errors into an array keyed by PHP version. | |
foreach ( $json['files'] as $filename => $errors ) { | |
foreach ( $errors['messages'] as $message ) { | |
$version = []; | |
preg_match( '/(\d)(.\d)+/', $message['message'], $version ); | |
if ( ! array_key_exists( $version['0'], $compat ) ) { | |
$compat[ $version['0'] ] = array( 'files' => array() ); | |
} | |
$compat[ $version['0'] ]['files'][ $filename ]['messages'][] = $message; | |
} | |
} | |
ksort( $compat ); | |
// Output the new keyed results as json file. | |
file_put_contents( $phpcompat_report_file, json_encode( $compat ) ); | |
// Get all versions that report errors... | |
$versions = array_keys( $compat ); | |
// ... sort them from higest to lowest... | |
asort( $versions ); | |
// ... get the highest version ... | |
$highest_version = array_pop( $versions ); | |
// ... then slice the array to only contain remaining compatible versions. | |
$offset = array_search( $highest_version, $php_versions ); | |
$compatible_versions = array_slice( $php_versions, $offset + 1 ); | |
} | |
// Return the results. | |
return array( | |
'compatible_versions' => $compatible_versions, | |
'details' => $compat, | |
); | |
} | |
// Example: | |
check_compatibility( '.', './report.json', './compatibility.json' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment