Version.php 2.4 KB

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