Version.php 2.0 KB

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