PreReleaseSuffix.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php declare(strict_types = 1);
  2. namespace PharIo\Version;
  3. class PreReleaseSuffix {
  4. private const valueScoreMap = [
  5. 'dev' => 0,
  6. 'a' => 1,
  7. 'alpha' => 1,
  8. 'b' => 2,
  9. 'beta' => 2,
  10. 'rc' => 3,
  11. 'p' => 4,
  12. 'patch' => 4,
  13. ];
  14. /** @var string */
  15. private $value;
  16. /** @var int */
  17. private $valueScore;
  18. /** @var int */
  19. private $number = 0;
  20. /** @var string */
  21. private $full;
  22. /**
  23. * @throws InvalidPreReleaseSuffixException
  24. */
  25. public function __construct(string $value) {
  26. $this->parseValue($value);
  27. }
  28. public function asString(): string {
  29. return $this->full;
  30. }
  31. public function getValue(): string {
  32. return $this->value;
  33. }
  34. public function getNumber(): ?int {
  35. return $this->number;
  36. }
  37. public function isGreaterThan(PreReleaseSuffix $suffix): bool {
  38. if ($this->valueScore > $suffix->valueScore) {
  39. return true;
  40. }
  41. if ($this->valueScore < $suffix->valueScore) {
  42. return false;
  43. }
  44. return $this->getNumber() > $suffix->getNumber();
  45. }
  46. /**
  47. * @param $value
  48. */
  49. private function mapValueToScore($value): int {
  50. if (\array_key_exists($value, self::valueScoreMap)) {
  51. return self::valueScoreMap[$value];
  52. }
  53. return 0;
  54. }
  55. private function parseValue($value): void {
  56. $regex = '/-?((dev|beta|b|rc|alpha|a|patch|p)\.?(\d*)).*$/i';
  57. if (\preg_match($regex, $value, $matches) !== 1) {
  58. throw new InvalidPreReleaseSuffixException(\sprintf('Invalid label %s', $value));
  59. }
  60. $this->full = $matches[1];
  61. $this->value = $matches[2];
  62. if ($matches[3] !== '') {
  63. $this->number = (int)$matches[3];
  64. }
  65. $this->valueScore = $this->mapValueToScore($matches[2]);
  66. }
  67. }