Q.
Basically this piece of code appears in my class constructor. It's working, but it seems very confusing.
It basically checks if the jQuery library is present locally and if it's not it will try to download it.
Is there any way I can improve this? Namely avoiding re-setting vars all the time?
CODE:
//First we check if JQuery version is correct
if ( isset($versionList->$version) ) {
$filePathFull = __DIR__ . '/versions/jquery-' . $version . '.js';
$filePathMin = __DIR__ . '/versions/jquery-' . $version . '.min.js';
$this->versionLoaded = $version;
//Now we check if the JQuery version is installed
if ( !file_exists($filePathFull) || !file_exists($filePathMin)) {
// They are not installed, so we will try to download and install it
if (!self::installVersion($version)) {
// Download failed, so we try the defaults
$filePathFull = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.js';
$filePathMin = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.min.js';
$this->versionLoaded = JQuery::DEFAULT_VERSION;
}
}
} else {
//Version is incorrect we go with the defaults
$filePathFull = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.js';
$filePathMin = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.min.js';
$this->versionLoaded = JQuery::DEFAULT_VERSION;
}
//This is a redundant check to see if the defaults are installed
if ( !file_exists($filePathFull) || !file_exists($filePathMin) ) {
// They are not installed, so we will try to download and install it
if (!self::installVersion(JQuery::DEFAULT_VERSION)) {
//Defaults are not installed so we throw an exception
throw new Exception("Nor the version $version or the default version " . JQuery::DEFAULT_VERSION . " could be found or downloaded");
}
}
Edit:
MORE DETAILS
A more detailed explanation...
As you correctly assumed, this is a "plugin". The plugable system requires wrapped JavaScript libraries in PHP classes that are used for a JS Dependency Manager. The JS Dependency Manager extends Composer which constrains how we handle this a bit. We have, however, freedom to chose how we wrap the JS Library.
Goals:
- Avoidance of library repetition (like having 2 versions of jQuery running which causes weird JS bugs)
- Automatic update of 3rd party JavaScript (directly from the repository instead of downloading and including them directly)
- Caching, Minimizing and removal of dead code from JS Scripts through Google Closure Compiler
- Libraries and scripts dependency management (specially regarding specific library versions such as jquery)