Completed
Push — master ( 444b50...ece018 )
by Gábor
03:00
created

Version::parsePreReleaseVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of the egabor/composer-release-plugin package.
5
 *
6
 * (c) Gábor Egyed <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace egabor\Composer\ReleasePlugin;
13
14
use egabor\Composer\ReleasePlugin\Exception\InvalidVersionException;
15
16
final class Version extends SemVer
17
{
18
    private static $supportedPreLevels = [
19
        'alpha',
20
        'beta',
21
        'rc',
22
    ];
23
    private $preReleaseVersionParts;
24
25
    public function __construct($major, $minor, $patch, $pre = '', $build = '')
26
    {
27
        parent::__construct($major, $minor, $patch, $pre, $build);
28
29
        $this->assertValidVersion();
30
        $this->preReleaseVersionParts = '' !== $this->getPre() ? self::parsePreReleaseVersion($this->getPre()) : ['level' => '', 'separator' => '', 'number' => ''];
31
    }
32
33
    public function getPreLevel()
34
    {
35
        return $this->preReleaseVersionParts['level'];
36
    }
37
38
    public function getPreSeparator()
39
    {
40
        return $this->preReleaseVersionParts['separator'];
41
    }
42
43
    public function getPreNumber()
44
    {
45
        return $this->preReleaseVersionParts['number'];
46
    }
47
48
    public function isStable()
49
    {
50
        return 0 < $this->getMajor() && '' === $this->getPre();
51
    }
52
53
    private static function parsePreReleaseVersion($tag)
54
    {
55
        $pattern = '(?P<level>'.implode('|', self::$supportedPreLevels).')(?P<separator>\\.?)(?P<number>\\d*)';
56
        $matches = self::match($pattern, $tag, 'Pre-release version is not valid and cannot be parsed.');
57
58
        return array_replace(['level' => '', 'separator' => '', 'number' => ''], $matches);
59
    }
60
61
    private function assertValidVersion()
62
    {
63
        if ('0' === $this->getMajor() && '' !== $this->getPre()) {
64
            throw new InvalidVersionException('Invalid version. Pre-release versions can not have pre part.');
65
        }
66
67
        if ('0' !== $this->getPatch() && '' !== $this->getPre()) {
68
            throw new InvalidVersionException('Invalid version. Patch versions can not have pre part.');
69
        }
70
    }
71
}
72