Skip to content

Commit

Permalink
Autoload: introduce method get_deprecated_classes().
Browse files Browse the repository at this point in the history
This method will return the array for the class mapping between the
legacy classes and their namespaced 2.x counterparts. The need for this
change came up while using the 2.x version of the library together
with WordPress core, that includes a 1.x version of Requests.

In order to prevent WordPress core from autoloading the 1.x classes,
they must be aliased before accessed. Through exposing the mapping
array, the classes can be aliased before being loaded by WordPress core.

See WordPress#659
  • Loading branch information
alpipego committed Feb 12, 2022
1 parent 294ec52 commit f9c888a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
31 changes: 31 additions & 0 deletions examples/preload-aliases.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/**
* If you need to run the Requests 2.x library with WordPress core that still ships v1.x,
* use the following to preload the class aliases before WordPress gets a chance to load
* the actual implementations of Requests 1.x.
*/

// First, include the Requests Autoloader.
require_once 'path/to/Requests/src/Autoload.php';

// Make sure the autoloader is registered first as otherwise you may run into trouble on PHP 8.1.
// See: https://news-web.php.net/php.internals/115549
WpOrg\Requests\Autoload::register();

// Silence deprecations.
// Depending on when the bootstrapping is done, you may need to wrap this in a `if (!defined(...)) {}`.
define('REQUESTS_SILENCE_PSR0_DEPRECATIONS', true);

$preload = WpOrg\Requests\Autoload::get_deprecated_classes();
// Add the base Requests class, just to be safe.
$preload['requests'] = '\WpOrg\Requests\Requests';

// Preload the class aliases for the Requests 1.x classes to ensure only Requests 2.x classes get loaded.
foreach ($preload as $old => $new) {
// Make sure we don't get "Class already exists errors" from autoloading chains
// Think: an `implements` causing an interface to be loaded before we explicitly request it.
if (class_exists($old) === false && interface_exists($old) === false) {
WpOrg\Requests\Autoload::load($old);
}
}
9 changes: 9 additions & 0 deletions src/Autoload.php
Original file line number Diff line number Diff line change
Expand Up @@ -183,5 +183,14 @@ public static function load($class_name) {

return false;
}

/**
* Get the array of deprecated Requests 1.x classes mapped to their equivalent Requests 2.x implementation.
*
* @return array
*/
public static function get_deprecated_classes() {
return self::$deprecated_classes;
}
}
}

0 comments on commit f9c888a

Please sign in to comment.