SemanticVersion::version()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 2
b 0
f 0
nc 2
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 2
rs 10
1
<?php
2
3
namespace Fractal\SemVer;
4
5
6
use Fractal\SemVer\Contracts\VersionInterface;
7
use Fractal\SemVer\Exceptions\ParseVersionException;
8
use Fractal\SemVer\Traits\Compares;
9
10
/**
11
 * Class SemanticVersion
12
 *
13
 * @author Mikhail Shtanko <[email protected]>
14
 */
15
class SemanticVersion implements VersionInterface
16
{
17
    use Compares;
18
19
    /**
20
     * Regex patter for version validation.
21
     *
22
     * @var string
23
     */
24
    protected const REGEX_PATTERN = '/(?:\d+\.?){3}/i';
25
26
    /**
27
     * Semantic version template.
28
     *
29
     * @const string
30
     */
31
    protected const VERSION_TEMPLATE = 'major.minor.patch';
32
33
    /**
34
     * Semantic version delimiter.
35
     *
36
     * @const string
37
     */
38
    protected const VERSION_DELIMITER = '.';
39
40
    /**
41
     * @var int
42
     */
43
    protected $major;
44
45
    /**
46
     * @var int
47
     */
48
    protected $minor;
49
50
    /**
51
     * @var int
52
     */
53
    protected $patch;
54
55
    /**
56
     * Version constructor.
57
     *
58
     * @param int $major
59
     * @param int $minor
60
     * @param int $patch
61
     */
62 18
    protected function __construct(int $major, int $minor, int $patch)
63
    {
64 18
        $this->major = $major;
65 18
        $this->minor = $minor;
66 18
        $this->patch = $patch;
67 18
    }
68
69
    /**
70
     * Creates new Version from string.
71
     *
72
     * @param string $version
73
     *
74
     * @return \Fractal\SemVer\Contracts\VersionInterface
75
     *
76
     * @throws \Fractal\SemVer\Exceptions\ParseVersionException
77
     */
78 19
    public static function fromString(string $version): VersionInterface
79
    {
80 19
        if (!preg_match(static::REGEX_PATTERN, $version)) {
81 1
            throw new ParseVersionException(static::VERSION_TEMPLATE, $version);
82
        }
83
84 18
        [$major, $minor, $patch] = explode(static::VERSION_DELIMITER, $version);
85
86 18
        return new static((int)$major, (int)$minor, (int)$patch);
87
    }
88
89
    /**
90
     * Convert Version to string.
91
     *
92
     * @param bool $withPatch
93
     *
94
     * @return string
95
     */
96 16
    public function version(bool $withPatch = true): string
97
    {
98 16
        return $withPatch
99 16
            ? "{$this->major}.{$this->minor}.{$this->patch}"
100 16
            : "{$this->major}.{$this->minor}";
101
    }
102
103
    /**
104
     * Convert Version to string.
105
     *
106
     * @return string
107
     */
108 15
    public function __toString(): string
109
    {
110 15
        return $this->version();
111
    }
112
}