Get mod date to attach a version number to JS src script
API

The documentation says the function returns a string, yet the last line of the implementation says otherwise...


/**
 * ...
 *
 * @return string
 */
function js($path){
    ...
    return false;
}



Replace a loop with array_map

Instead of this:


$return = '';
foreach($path as $value){
    $return .= js($value);
}
return $return;



You can write a bit simpler using array_map and join:

if (is_array($path)) {
    return join('', array_map('js', $path));
}


Getting the first character from a string

Instead of substr($path, 0, 1), when you know that $path is not empty (as in the posted code), a more natural way is to use indexing: $path[0].

Don't repeat yourself

dechex(filemtime(...)) is common in the two branches of this conditional:


if (substr($path, 0, 1) &lt;&gt; '/') {
    $version = dechex(filemtime(getcwd().'/'.$path));
} else {
    $version = dechex(filemtime(__DIR__.$path));
}



Extract the common part:

if ($path[0] &lt;&gt; '/') {
    $dir = getcwd().'/';
} else {
    $dir = __DIR__;
}


Use early returns

Instead of this kind of code:


if (cond1) {
    if (cond2) {
        // ...
        return X;
    } else {
        // ...
        return Y;
    }
}
return Z;



You can use "early returns" to reduce the nesting,
and thereby making the code slightly easier to read:

if (!cond1) {
    return Z;
}

if (cond2) {
    // ...
    return X;
}

return Y;


Alternative implementation

Putting the above tips together:

function js($path) {
    if (empty($path)) {
        return '';
    }

    if (is_array($path)) {
        return join('', array_map('js', $path));
    }

    $dir = $path[0] &lt;&gt; '/' ? getcwd().'/' : __DIR__;
    $version = dechex(filemtime($dir.$path));
    return "&lt;script src='$path?v=$version'&gt;&lt;/script&gt;\r\n";
}