Skip to content

Instantly share code, notes, and snippets.

@andergmartins
Last active April 14, 2020 20:35
Show Gist options
  • Save andergmartins/a2beb96bb009543109926286a2a687d7 to your computer and use it in GitHub Desktop.
Save andergmartins/a2beb96bb009543109926286a2a687d7 to your computer and use it in GitHub Desktop.
Smart loader for libraries in WordPress
<?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);
@andergmartins
Copy link
Author

Well, it seems like Jetpack already implemented a solution for this using an autolaoder for composer:

https://github.com/Automattic/jetpack-autoloader

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment