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    private $path;
19    private $release;
20    private $version;
21
22    /**
23     * @param string $release
24     * @param string $path
25     */
26    public function __construct($release, $path)
27    {
28        $this->release = $release;
29        $this->path    = $path;
30    }
31
32    /**
33     * @return string
34     */
35    public function getVersion()
36    {
37        if ($this->version === null) {
38            if (count(explode('.', $this->release)) == 3) {
39                $this->version = $this->release;
40            } else {
41                $this->version = $this->release . '-dev';
42            }
43
44            $git = $this->getGitInformation($this->path);
45
46            if ($git) {
47                if (count(explode('.', $this->release)) == 3) {
48                    $this->version = $git;
49                } else {
50                    $git = explode('-', $git);
51
52                    $this->version = $this->release . '-' . end($git);
53                }
54            }
55        }
56
57        return $this->version;
58    }
59
60    /**
61     * @param  string      $path
62     * @return bool|string
63     */
64    private function getGitInformation($path)
65    {
66        if (!is_dir($path . DIRECTORY_SEPARATOR . '.git')) {
67            return false;
68        }
69
70        $dir = getcwd();
71        chdir($path);
72        $returnCode = 1;
73        $result     = @exec('git describe --tags 2>&1', $output, $returnCode);
74        chdir($dir);
75
76        if ($returnCode !== 0) {
77            return false;
78        }
79
80        return $result;
81    }
82}
83