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