Skip to content

Commit

Permalink
Autoload: improve/stabilize version check for TestCase
Browse files Browse the repository at this point in the history
The version check in the `Autoload::loadTestCase()` method could get confused if the package using this library, or a dependency of the package using this library would alias the `PHPUnit_Runner_Version`/`PHPUnit\Runner\Version` class.

As both classes contain the method we need to retrieve the version number, let's always base the loading on the available PHPUnit version number instead of the availability of either class.
  • Loading branch information
jrfnl committed Oct 3, 2021
1 parent ce8ae4a commit 24ea563
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions phpunitpolyfills-autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Yoast\PHPUnitPolyfills;

use PHPUnit\Runner\Version as PHPUnit_Version;
use PHPUnit_Runner_Version;

if ( \class_exists( 'Yoast\PHPUnitPolyfills\Autoload', false ) === false ) {

Expand Down Expand Up @@ -426,9 +427,7 @@ public static function loadAssertObjectEquals() {
* @return void
*/
public static function loadTestCase() {
if ( \class_exists( '\PHPUnit_Runner_Version' ) === true
|| \version_compare( PHPUnit_Version::id(), '8.0.0', '<' )
) {
if ( \version_compare( self::getPHPUnitVersion(), '8.0.0', '<' ) ) {
// PHPUnit < 8.0.0.
require_once __DIR__ . '/src/TestCases/TestCasePHPUnitLte7.php';
return;
Expand All @@ -444,7 +443,7 @@ public static function loadTestCase() {
* @return void
*/
public static function loadTestListenerDefaultImplementation() {
if ( \class_exists( '\PHPUnit_Runner_Version' ) === true ) {
if ( \version_compare( self::getPHPUnitVersion(), '6.0.0', '<' ) ) {
/*
* Alias one particular PHPUnit 4/5 class to its PHPUnit >= 6 name.
*
Expand Down Expand Up @@ -474,6 +473,26 @@ public static function loadTestListenerDefaultImplementation() {
// PHPUnit >= 7.0.0.
require_once __DIR__ . '/src/TestListeners/TestListenerDefaultImplementationPHPUnitGte7.php';
}

/**
* Retrieve the PHPUnit version id.
*
* As both the pre-PHPUnit 6 class, as well as the PHPUnit 6+ class contain the `id()` function,
* this should work independently of whether or not another library may have aliased the class.
*
* @return string Version number as a string.
*/
public static function getPHPUnitVersion() {
if ( \class_exists( '\PHPUnit\Runner\Version' ) ) {
return PHPUnit_Version::id();
}

if ( \class_exists( '\PHPUnit_Runner_Version' ) ) {
return PHPUnit_Runner_Version::id();
}

return '0';
}
}

\spl_autoload_register( __NAMESPACE__ . '\Autoload::load' );
Expand Down

0 comments on commit 24ea563

Please sign in to comment.