Version.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /*
  3. * This file is part of sebastian/version.
  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. final class Version
  12. {
  13. /**
  14. * @var string
  15. */
  16. private $path;
  17. /**
  18. * @var string
  19. */
  20. private $release;
  21. /**
  22. * @var string
  23. */
  24. private $version;
  25. public function __construct(string $release, string $path)
  26. {
  27. $this->release = $release;
  28. $this->path = $path;
  29. }
  30. public function getVersion(): string
  31. {
  32. if ($this->version === null) {
  33. if (\substr_count($this->release, '.') + 1 === 3) {
  34. $this->version = $this->release;
  35. } else {
  36. $this->version = $this->release . '-dev';
  37. }
  38. $git = $this->getGitInformation($this->path);
  39. if ($git) {
  40. if (\substr_count($this->release, '.') + 1 === 3) {
  41. $this->version = $git;
  42. } else {
  43. $git = \explode('-', $git);
  44. $this->version = $this->release . '-' . \end($git);
  45. }
  46. }
  47. }
  48. return $this->version;
  49. }
  50. /**
  51. * @return bool|string
  52. */
  53. private function getGitInformation(string $path)
  54. {
  55. if (!\is_dir($path . DIRECTORY_SEPARATOR . '.git')) {
  56. return false;
  57. }
  58. $process = \proc_open(
  59. 'git describe --tags',
  60. [
  61. 1 => ['pipe', 'w'],
  62. 2 => ['pipe', 'w'],
  63. ],
  64. $pipes,
  65. $path
  66. );
  67. if (!\is_resource($process)) {
  68. return false;
  69. }
  70. $result = \trim(\stream_get_contents($pipes[1]));
  71. \fclose($pipes[1]);
  72. \fclose($pipes[2]);
  73. $returnCode = \proc_close($process);
  74. if ($returnCode !== 0) {
  75. return false;
  76. }
  77. return $result;
  78. }
  79. }