ComposerVersionNormalizer.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * @license GPL-2.0-or-later
  4. * @author Jeroen De Dauw < jeroendedauw@gmail.com >
  5. */
  6. class ComposerVersionNormalizer {
  7. /**
  8. * Ensures there is a dash in between the version and the stability suffix.
  9. *
  10. * Examples:
  11. * - 1.23RC => 1.23-RC
  12. * - 1.23alpha => 1.23-alpha
  13. * - 1.23alpha3 => 1.23-alpha3
  14. * - 1.23-beta => 1.23-beta
  15. *
  16. * @param string $version
  17. *
  18. * @return string
  19. * @throws InvalidArgumentException
  20. */
  21. public function normalizeSuffix( $version ) {
  22. if ( !is_string( $version ) ) {
  23. throw new InvalidArgumentException( '$version must be a string' );
  24. }
  25. return preg_replace( '/^(\d[\d\.]*)([a-zA-Z]+)(\d*)$/', '$1-$2$3', $version, 1 );
  26. }
  27. /**
  28. * Ensures the version has four levels.
  29. * Version suffixes are supported, as long as they start with a dash.
  30. *
  31. * Examples:
  32. * - 1.19 => 1.19.0.0
  33. * - 1.19.2.3 => 1.19.2.3
  34. * - 1.19-alpha => 1.19.0.0-alpha
  35. * - 1337 => 1337.0.0.0
  36. *
  37. * @param string $version
  38. *
  39. * @return string
  40. * @throws InvalidArgumentException
  41. */
  42. public function normalizeLevelCount( $version ) {
  43. if ( !is_string( $version ) ) {
  44. throw new InvalidArgumentException( '$version must be a string' );
  45. }
  46. $dashPosition = strpos( $version, '-' );
  47. if ( $dashPosition !== false ) {
  48. $suffix = substr( $version, $dashPosition );
  49. $version = substr( $version, 0, $dashPosition );
  50. }
  51. $version = implode( '.', array_pad( explode( '.', $version, 4 ), 4, '0' ) );
  52. if ( $dashPosition !== false ) {
  53. $version .= $suffix;
  54. }
  55. return $version;
  56. }
  57. }