PHP Semantic Versioning Helper


November 20th, 2018

PHP Semantic Versioning Helper

SemVer is a semantic versioning helper library for PHP by Chris Kankiewicz with support for parsing, incrementing, and comparison.

Here’s the basic usage which initializes a SemVer\Version object:

1use PHLAK\SemVer;
3$version = new SemVer\Version(); // Initilializes to '0.1.0'

With an instance of SemVer\Version you can access individual values:

1$version = new SemVer\Version('v1.2.3-beta.4+007');
3echo $version; // '1.2.3-beta.4+007'
4echo $version->major; // 1
5echo $version->minor; // 2
6echo $version->patch; // 3
7echo $version->preRelease; // 'beta.4'
8echo $version->build; // '007'

If you wanted to build something that increments your package builds you can use this package’s increment methods:

1$version = new SemVer\Version('v1.2.3');
3$version->incrementMajor(); // v1.2.3 -> v2.0.0
4$version->incrementMinor(); // v1.2.3 -> v1.3.0
5$version->incrementPatch(); // v1.2.3 -> v1.2.4

Last, the comparisons are pretty handy:

1$version1 = new SemVer('v1.2.3');
2$version2 = new SemVer('v3.2.1');
4$version1->gt($version2); // false
5$version1->lt($version2); // true
6$version1->eq($version2); // false
7$version1->neq($version2); // true
8$version1->gte($version2); // false
9$version1->lte($version2); // true

Before checking out this PHLAK/SemVer, I wasn’t aware that composer also has a composer/semver library, which has a comparator and semver class, however, I didn’t find the increment methods found in PHLAK/SemVer.

To get installation instructions, check out PHLAK/SemVer on GitHub!

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.