Last active
April 14, 2020 20:35
-
-
Save andergmartins/a2beb96bb009543109926286a2a687d7 to your computer and use it in GitHub Desktop.
Smart loader for libraries in WordPress
This file contains hidden or 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 | |
use PPWPProPluginsAds\Autoloader; | |
if (file_exists(__DIR__ . '/vendor')) { | |
require_once __DIR__ . '/vendor/autoload.php'; | |
} | |
$version = '0.1.0'; | |
if (!function_exists('calculatePriorityFromVersion')) { | |
/** | |
* This function requires the version in a semantic version format: 0.0.0(-[alpha|beta|rc].0)? | |
* | |
* Examples: | |
* | |
* 1.2.3-alpha.4 => 01 02 03 1 04 => 10,203,104 | |
* 10.20.30-alpha.40 => 10 20 30 1 40 => 102,030,140 | |
* 10.20.30-beta.40 => 10 20 30 1 40 => 102,030,240 | |
* | |
* @see http://semver.org/ | |
* | |
* @param string $version | |
* | |
* @return int | |
*/ | |
function calculatePriorityFromVersion($version) | |
{ | |
$priority = 0; | |
if (strpos($version, '-')) { | |
// Has unstable version | |
$parts = explode('-', $version); | |
$version = $parts[0]; | |
$unstableVersion = strtolower($parts[1]); | |
$unstablePriority = 0; | |
if (false !== strpos($unstableVersion, 'alpha')) { | |
$unstablePriority += 100; | |
} elseif (false !== strpos($unstableVersion, 'beta')) { | |
$unstablePriority += 200; | |
} elseif (false !== strpos($unstableVersion, 'rc')) { | |
$unstablePriority += 300; | |
} | |
$unstableVersion = preg_replace('/(alpha|beta|rc)\./', '', $unstableVersion); | |
$unstablePriority += (int)$unstableVersion; | |
$priority += $unstablePriority; | |
} | |
$versions = explode('.', $version); | |
$priority += (int)$versions[0] * 10000000; | |
$priority += (int)$versions[1] * 100000; | |
$priority += (int)$versions[2] * 1000; | |
return $priority; | |
} | |
} | |
$loadingPriority = PHP_INT_MAX - calculatePriorityFromVersion($version); | |
add_action('ppwppropluginsads_library_load', function () use ($version) { | |
if (!defined('PPWPPROPLUGINSADS_LOADED')) { | |
define('PPWPPROPLUGINSADS_VERSION', $version); | |
if (!class_exists('PPWPProPluginsAds\\Autoloader')) { | |
require_once __DIR__ . '/core/Autoloader.php'; | |
} | |
Autoloader::register('PPWPProPluginsAds', __DIR__ . '/core'); | |
define('PPWPPROPLUGINSADS_LOADED', 1); | |
} | |
}, $loadingPriority); | |
Well, it seems like Jetpack already implemented a solution for this using an autolaoder for composer:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This only works for "predictable" implementations, so basically only on the libraries we have control. Can't protect us from other libraries loaded before we have the chance to load it.