VersionParser.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\App\AppStore\Version;
  7. /**
  8. * Class VersionParser parses the versions as sent by the Nextcloud app store
  9. *
  10. * @package OC\App\AppStore
  11. */
  12. class VersionParser {
  13. /**
  14. * @param string $versionString
  15. * @return bool
  16. */
  17. private function isValidVersionString($versionString) {
  18. return (bool)preg_match('/^[0-9.]+$/', $versionString);
  19. }
  20. /**
  21. * Returns the version for a version string
  22. *
  23. * @param string $versionSpec
  24. * @return Version
  25. * @throws \Exception If the version cannot be parsed
  26. */
  27. public function getVersion($versionSpec) {
  28. // * indicates that the version is compatible with all versions
  29. if ($versionSpec === '*') {
  30. return new Version('', '');
  31. }
  32. // Count the amount of =, if it is one then it's either maximum or minimum
  33. // version. If it is two then it is maximum and minimum.
  34. $versionElements = explode(' ', $versionSpec);
  35. $firstVersion = $versionElements[0] ?? '';
  36. $firstVersionNumber = substr($firstVersion, 2);
  37. $secondVersion = $versionElements[1] ?? '';
  38. $secondVersionNumber = substr($secondVersion, 2);
  39. switch (count($versionElements)) {
  40. case 1:
  41. if (!$this->isValidVersionString($firstVersionNumber)) {
  42. break;
  43. }
  44. if (str_starts_with($firstVersion, '>')) {
  45. return new Version($firstVersionNumber, '');
  46. }
  47. return new Version('', $firstVersionNumber);
  48. case 2:
  49. if (!$this->isValidVersionString($firstVersionNumber) || !$this->isValidVersionString($secondVersionNumber)) {
  50. break;
  51. }
  52. return new Version($firstVersionNumber, $secondVersionNumber);
  53. }
  54. throw new \Exception(
  55. sprintf(
  56. 'Version cannot be parsed: %s',
  57. $versionSpec
  58. )
  59. );
  60. }
  61. }