Version.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. <?php
  2. /*
  3. * This file is part of the Version package.
  4. *
  5. * (c) Sebastian Bergmann <sebastian@phpunit.de>
  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 SebastianBergmann;
  11. /**
  12. * @since Class available since Release 1.0.0
  13. */
  14. class Version
  15. {
  16. /**
  17. * @var string
  18. */
  19. private $path;
  20. /**
  21. * @var string
  22. */
  23. private $release;
  24. /**
  25. * @var string
  26. */
  27. private $version;
  28. /**
  29. * @param string $release
  30. * @param string $path
  31. */
  32. public function __construct($release, $path)
  33. {
  34. $this->release = $release;
  35. $this->path = $path;
  36. }
  37. /**
  38. * @return string
  39. */
  40. public function getVersion()
  41. {
  42. if ($this->version === null) {
  43. if (count(explode('.', $this->release)) == 3) {
  44. $this->version = $this->release;
  45. } else {
  46. $this->version = $this->release . '-dev';
  47. }
  48. $git = $this->getGitInformation($this->path);
  49. if ($git) {
  50. if (count(explode('.', $this->release)) == 3) {
  51. $this->version = $git;
  52. } else {
  53. $git = explode('-', $git);
  54. $this->version = $this->release . '-' . end($git);
  55. }
  56. }
  57. }
  58. return $this->version;
  59. }
  60. /**
  61. * @param string $path
  62. *
  63. * @return bool|string
  64. */
  65. private function getGitInformation($path)
  66. {
  67. if (!is_dir($path . DIRECTORY_SEPARATOR . '.git')) {
  68. return false;
  69. }
  70. $process = proc_open(
  71. 'git describe --tags',
  72. [
  73. 1 => ['pipe', 'w'],
  74. 2 => ['pipe', 'w'],
  75. ],
  76. $pipes,
  77. $path
  78. );
  79. if (!is_resource($process)) {
  80. return false;
  81. }
  82. $result = trim(stream_get_contents($pipes[1]));
  83. fclose($pipes[1]);
  84. fclose($pipes[2]);
  85. $returnCode = proc_close($process);
  86. if ($returnCode !== 0) {
  87. return false;
  88. }
  89. return $result;
  90. }
  91. }