From 7b5a9fd99a4557bc7c167b99baa7ac3107d6f6c6 Mon Sep 17 00:00:00 2001 From: Marco Cesarato Date: Mon, 18 Jan 2021 23:02:23 +0100 Subject: [PATCH] feat: add semantic version parser --- src/SemanticVersion.php | 92 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 src/SemanticVersion.php diff --git a/src/SemanticVersion.php b/src/SemanticVersion.php new file mode 100644 index 0000000..324ee3e --- /dev/null +++ b/src/SemanticVersion.php @@ -0,0 +1,92 @@ +setVersion($version); + } + + /** + * Bump version. + * + * @param string $mode + */ + public function bump($mode): string + { + $version = $this->getVersion(); + + $newVersion = [0, 0, 0]; + $version = preg_replace('#^v#i', '', $version); + + // Generate new version code + $split = explode('-', $version); + $extra = !empty($split[1]) ? $split[1] : ''; + $parts = explode('.', $split[0]); + + foreach ($parts as $key => $value) { + $newVersion[$key] = (int)$value; + } + + $extraModes = [self::RELEASE_RC, self::RELEASE_BETA, self::RELEASE_ALPHA]; + + if (in_array($mode, $extraModes)) { + $partsExtra = explode('.', $extra); + $extraName = $partsExtra[0]; + $extraVersion = !empty($partsExtra[1]) ? $partsExtra[1] : 0; + if (is_numeric($extraName) && (empty($partsExtra[1]) || !is_numeric($partsExtra[1]))) { + $extraVersion = $partsExtra[0]; + } elseif ($extraName !== $mode) { + $extraVersion = 0; + } + $extraVersion++; + $extra = "{$mode}.{$extraVersion}"; + } + + if ($mode === self::RELEASE_MAJOR) { + $newVersion[0]++; + } elseif ($mode === self::RELEASE_MINOR) { + $newVersion[1]++; + } elseif ($mode === self::RELEASE_PATCH) { + $newVersion[2]++; + } + + // Recompose semver + $version = implode('.', $newVersion) . (!empty($extra) ? '-' . $extra : ''); + + $this->setVersion($version); + + return $version; + } + + public function getVersion(): string + { + return $this->version; + } + + public function setVersion(string $version): SemanticVersion + { + $this->version = $version; + + return $this; + } +}