Skip to content

Instantly share code, notes, and snippets.

@pete-otaqui
Created May 13, 2013 13:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pete-otaqui/5568397 to your computer and use it in GitHub Desktop.
Save pete-otaqui/5568397 to your computer and use it in GitHub Desktop.
Semantic version bumping in PHP
/**
* 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";
}
@brenjt
Copy link

brenjt commented Sep 5, 2018

You should be resetting $patch in the major and minor cases and reset $minor in the major case

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