Version.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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 string $version1 A version string.
  34. * @param string $version2 A version string to compare.
  35. * @param string $operator The comparison operator.
  36. * @param integer|null $precision The number of components to compare. Pass
  37. * NULL to compare the versions unchanged.
  38. *
  39. * @return Boolean Whether the comparison succeeded.
  40. *
  41. * @see normalize()
  42. */
  43. public static function compare($version1, $version2, $operator, $precision = null)
  44. {
  45. $version1 = self::normalize($version1, $precision);
  46. $version2 = self::normalize($version2, $precision);
  47. return version_compare($version1, $version2, $operator);
  48. }
  49. /**
  50. * Normalizes a version string to the number of components given in the
  51. * parameter $precision.
  52. *
  53. * Examples:
  54. *
  55. * Version::normalize('1.2.3', 1);
  56. * // => '1'
  57. *
  58. * Version::normalize('1.2.3', 2);
  59. * // => '1.2'
  60. *
  61. * @param string $version A version string.
  62. * @param integer|null $precision The number of components to include. Pass
  63. * NULL to return the version unchanged.
  64. *
  65. * @return string|null The normalized version or NULL if it couldn't be
  66. * normalized.
  67. */
  68. public static function normalize($version, $precision)
  69. {
  70. if (null === $precision) {
  71. return $version;
  72. }
  73. $pattern = '[^\.]+';
  74. for ($i = 2; $i <= $precision; ++$i) {
  75. $pattern = sprintf('[^\.]+(\.%s)?', $pattern);
  76. }
  77. if (!preg_match('/^' . $pattern . '/', $version, $matches)) {
  78. return null;
  79. }
  80. return $matches[0];
  81. }
  82. /**
  83. * Must not be instantiated.
  84. */
  85. private function __construct() {}
  86. }