You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

80 lines
2.0 KiB

  1. <?php
  2. namespace fast;
  3. /**
  4. * 版本检测和对比
  5. */
  6. class Version
  7. {
  8. /**
  9. * 检测版本是否的版本要求的数据中
  10. *
  11. * @param string $version
  12. * @param array $data
  13. * @return bool
  14. */
  15. public static function check($version, $data = [])
  16. {
  17. //版本号以.分隔
  18. $data = is_array($data) ? $data : [$data];
  19. if ($data) {
  20. if (in_array("*", $data) || in_array($version, $data)) {
  21. return true;
  22. }
  23. $ver = explode('.', $version);
  24. if ($ver) {
  25. $versize = count($ver);
  26. //验证允许的版本
  27. foreach ($data as $m) {
  28. $c = explode('.', $m);
  29. if (!$c || $versize != count($c)) {
  30. continue;
  31. }
  32. $i = 0;
  33. foreach ($c as $a => $k) {
  34. if (!self::compare($ver[$a], $k)) {
  35. continue 2;
  36. } else {
  37. $i++;
  38. }
  39. }
  40. if ($i == $versize) {
  41. return true;
  42. }
  43. }
  44. }
  45. }
  46. return false;
  47. }
  48. /**
  49. * 比较两个版本号
  50. *
  51. * @param string $v1
  52. * @param string $v2
  53. * @return boolean
  54. */
  55. public static function compare($v1, $v2)
  56. {
  57. if ($v2 == "*" || $v1 == $v2) {
  58. return true;
  59. } else {
  60. $values = [];
  61. $k = explode(',', $v2);
  62. foreach ($k as $v) {
  63. if (strpos($v, '-') !== false) {
  64. list($start, $stop) = explode('-', $v);
  65. for ($i = $start; $i <= $stop; $i++) {
  66. $values[] = $i;
  67. }
  68. } else {
  69. $values[] = $v;
  70. }
  71. }
  72. return in_array($v1, $values) ? true : false;
  73. }
  74. }
  75. }