Cache
11 months ago
DBPermissions.php
1 year ago
DataEncoder.php
10 months ago
Escape.php
10 months ago
Glob.php
2 years ago
Hooks.php
1 year ago
Math.php
1 year ago
PluginInfo.php
2 years ago
Sanitize.php
2 years ago
ServerVars.php
2 years ago
SlashMode.php
5 years ago
Strings.php
11 months ago
Times.php
1 year ago
Urls.php
1 year ago
Version.php
1 year ago
WpDefaultDirectories.php
1 year ago
Version.php
69 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\Utils; |
| 4 | |
| 5 | /** |
| 6 | * Class Version |
| 7 | * Provide method to convert version number to integer and vice versa |
| 8 | * @package WPStaging\Framework\Utils |
| 9 | */ |
| 10 | class Version |
| 11 | { |
| 12 | /** |
| 13 | * Convert version string format to integer format i.e. 1.0.0 to 10000 |
| 14 | * |
| 15 | * @param string $versionString |
| 16 | * @return int |
| 17 | * @throws \InvalidArgumentException |
| 18 | */ |
| 19 | public function convertStringFormatToIntFormat(string $versionString): int |
| 20 | { |
| 21 | $versionParts = explode('.', $versionString); |
| 22 | if (count($versionParts) !== 3) { |
| 23 | throw new \InvalidArgumentException('Invalid version string format'); |
| 24 | } |
| 25 | |
| 26 | foreach ($versionParts as $part) { |
| 27 | if (!is_numeric($part)) { |
| 28 | throw new \InvalidArgumentException('Version parts must be positive integers'); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | $versionParts = array_map('intval', $versionParts); |
| 33 | |
| 34 | if ($versionParts[0] < 0 || $versionParts[1] < 0 || $versionParts[2] < 0) { |
| 35 | throw new \InvalidArgumentException('Version parts must be positive integers'); |
| 36 | } |
| 37 | |
| 38 | if ($versionParts[0] === 0 && $versionParts[1] === 0 && $versionParts[2] === 0) { |
| 39 | throw new \InvalidArgumentException('Invalid version string format'); |
| 40 | } |
| 41 | |
| 42 | if ($versionParts[1] > 100 || $versionParts[2] > 100) { |
| 43 | throw new \InvalidArgumentException('Version Minor and Patch parts must be less than 100'); |
| 44 | } |
| 45 | |
| 46 | return $versionParts[0] * 10000 + $versionParts[1] * 100 + $versionParts[2]; |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Convert version integer format to string format i.e. 10000 to 1.0.0 |
| 51 | * |
| 52 | * @param int $version |
| 53 | * @return string |
| 54 | * @throws \InvalidArgumentException |
| 55 | */ |
| 56 | public function convertIntFormatToStringFormat(int $version): string |
| 57 | { |
| 58 | if ($version < 1) { |
| 59 | throw new \InvalidArgumentException('Version must be a positive integer'); |
| 60 | } |
| 61 | |
| 62 | $major = floor($version / 10000); |
| 63 | $minor = floor(($version % 10000) / 100); |
| 64 | $patch = $version % 100; |
| 65 | |
| 66 | return sprintf('%d.%d.%d', $major, $minor, $patch); |
| 67 | } |
| 68 | } |
| 69 |