Last Updated: February 25, 2016
·
1.242K
· pete-otaqui

Semantic Version Bumping in PHP

Available as a Gist on GitHub

/**
 * Semantically bump a version number, defaults to "minor".
 * 
 * If your version number includes a prefix, (e.g. "v" in "v0.1.0")
 * this will be preserved and returned.  Any suffix (e.g. "-beta"
 * in "v0.5.2-beta") will be lost.
 * 
 * You can provide version numbers in the following formats:
 * '0.1.2', 'v1.2-patched', '2.3', '3', 4.1, 5
 * And you will get back (assuming a minor bump):
 * '0.2.2', 'v1.3.0', '2.4.0', '3.1.0', '4.2.0', '5.1.0'
 * 
 * @param String|Null $version the current version number, defaults to '0.0.0'
 * @param String|Null $type the type of bump (major|minor|patch), defaults to 'minor'
 * @return String the new version number, e.g. '0.1.0'
 */
function bumpVersionNumber($version='0.0.0', $type='minor') {
    $version = ''.$version;
    $prefix = preg_replace('|[0-9].*$|', '', $version);
    $version = preg_replace('|[^0-9.]*([0-9.]+).*|', '$1', $version);
    while ( count(explode('.', $version)) < 3 ) {
        $version .= '.0';
    }
    list($major, $minor, $patch) = explode('.', $version);
    $major = (int) $major;
    $minor = (int) $minor;
    $patch = (int) $patch;
    switch ($type) {
        case 'major' : $major++; break;
        case 'minor' : $minor++; break;
        case 'patch' : $patch++; break;
    }
    return "$prefix$major.$minor.$patch";
}