1<?php 2 3/* 4 * This file is part of the Symfony package. 5 * 6 * (c) Fabien Potencier <fabien@symfony.com> 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12namespace Symfony\Component\Intl\Util; 13 14/** 15 * Facilitates the comparison of version strings. 16 * 17 * @author Bernhard Schussek <bschussek@gmail.com> 18 */ 19class Version 20{ 21 /** 22 * Compares two versions with an operator. 23 * 24 * This method is identical to {@link version_compare()}, except that you 25 * can pass the number of regarded version components in the last argument 26 * $precision. 27 * 28 * Examples: 29 * 30 * Version::compare('1.2.3', '1.2.4', '==') 31 * // => false 32 * 33 * Version::compare('1.2.3', '1.2.4', '==', 2) 34 * // => true 35 * 36 * @param int|null $precision The number of components to compare. Pass 37 * NULL to compare the versions unchanged. 38 * 39 * @return bool Whether the comparison succeeded 40 * 41 * @see normalize() 42 */ 43 public static function compare(string $version1, string $version2, string $operator, ?int $precision = null) 44 { 45 $version1 = self::normalize($version1, $precision); 46 $version2 = self::normalize($version2, $precision); 47 48 return version_compare($version1, $version2, $operator); 49 } 50 51 /** 52 * Normalizes a version string to the number of components given in the 53 * parameter $precision. 54 * 55 * Examples: 56 * 57 * Version::normalize('1.2.3', 1); 58 * // => '1' 59 * 60 * Version::normalize('1.2.3', 2); 61 * // => '1.2' 62 * 63 * @param int|null $precision The number of components to include. Pass 64 * NULL to return the version unchanged. 65 * 66 * @return string|null the normalized version or NULL if it couldn't be 67 * normalized 68 */ 69 public static function normalize(string $version, ?int $precision) 70 { 71 if (null === $precision) { 72 return $version; 73 } 74 75 $pattern = '[^\.]+'; 76 77 for ($i = 2; $i <= $precision; ++$i) { 78 $pattern = sprintf('[^\.]+(\.%s)?', $pattern); 79 } 80 81 if (!preg_match('/^'.$pattern.'/', $version, $matches)) { 82 return null; 83 } 84 85 return $matches[0]; 86 } 87 88 /** 89 * Must not be instantiated. 90 */ 91 private function __construct() 92 { 93 } 94} 95