Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
112 / 112
100.00% covered (success)
100.00%
6 / 6
CRAP
100.00% covered (success)
100.00%
1 / 1
SemverVersioning
100.00% covered (success)
100.00%
112 / 112
100.00% covered (success)
100.00%
6 / 6
45
100.00% covered (success)
100.00%
1 / 1
 parseVersion
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
9
 normalizeVersion
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
6
 validateExtra
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
9
 nextVersion
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
1 / 1
6
 compareVersions
100.00% covered (success)
100.00%
30 / 30
100.00% covered (success)
100.00%
1 / 1
14
 firstVersion
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * Semver versioning plugin.
4 *
5 * @package automattic/jetpack-changelogger
6 */
7
8namespace Automattic\Jetpack\Changelogger\Plugins;
9
10use Automattic\Jetpack\Changelog\ChangeEntry;
11use Automattic\Jetpack\Changelogger\PluginTrait;
12use Automattic\Jetpack\Changelogger\VersioningPlugin;
13use InvalidArgumentException;
14
15/**
16 * Semver versioning plugin.
17 */
18class SemverVersioning implements VersioningPlugin {
19    use PluginTrait;
20
21    /**
22     * Parse a semver version.
23     *
24     * @param string $version Version.
25     * @return array With components:
26     *  - major: (int) Major version.
27     *  - minor: (int) Minor version.
28     *  - patch: (int) Patch version.
29     *  - version: (string) Major.minor.patch.
30     *  - prerelease: (string|null) Pre-release string.
31     *  - buildinfo: (string|null) Build metadata string.
32     * @throws InvalidArgumentException If the version number is not in a recognized format.
33     */
34    public function parseVersion( $version ) {
35        // This is slightly looser than the official version from semver.org, in that leading zeros are allowed.
36        if ( ! preg_match( '/^(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(?:-(?P<prerelease>(?:[0-9a-zA-Z-]+)(?:\.(?:[0-9a-zA-Z-]+))*))?(?:\+(?P<buildinfo>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/', $version, $m ) ) {
37            throw new InvalidArgumentException( "Version number \"$version\" is not in a recognized format." );
38        }
39        $info = array(
40            'major'      => (int) $m['major'],
41            'minor'      => (int) $m['minor'],
42            'patch'      => (int) $m['patch'],
43            'version'    => sprintf( '%d.%d.%d', $m['major'], $m['minor'], $m['patch'] ),
44            'prerelease' => isset( $m['prerelease'] ) && '' !== $m['prerelease'] ? $m['prerelease'] : null,
45            'buildinfo'  => isset( $m['buildinfo'] ) && '' !== $m['buildinfo'] ? $m['buildinfo'] : null,
46        );
47
48        if ( null !== $info['prerelease'] ) {
49            $sep        = '';
50            $prerelease = '';
51            foreach ( explode( '.', $info['prerelease'] ) as $part ) {
52                if ( ctype_digit( $part ) ) {
53                    $part = (int) $part;
54                }
55                $prerelease .= $sep . $part;
56                $sep         = '.';
57            }
58            $info['prerelease'] = $prerelease;
59        }
60
61        return $info;
62    }
63
64    /**
65     * Check and normalize a version number.
66     *
67     * @param string|array $version Version string, or array as from `parseVersion()` (ignoring a `version` key).
68     * @param array        $extra Extra components for the version, replacing any in `$version`.
69     * @return string Normalized version.
70     * @throws InvalidArgumentException If the version number is not in a recognized format or extra is invalid.
71     */
72    public function normalizeVersion( $version, $extra = array() ) {
73        if ( is_array( $version ) ) {
74            $info = $version + array(
75                'prerelease' => null,
76                'buildinfo'  => null,
77            );
78            $test = $this->parseVersion( '0.0.0' );
79            unset( $test['version'] );
80            if ( array_intersect_key( $test, $info ) !== $test ) {
81                throw new InvalidArgumentException( 'Version array is not in a recognized format.' );
82            }
83
84            if ( null !== $info['prerelease'] ) {
85                $info['prerelease'] = $this->parseVersion( '0.0.0-' . $info['prerelease'] )['prerelease'];
86            }
87        } else {
88            $info = $this->parseVersion( $version );
89        }
90        $info = array_merge( $info, $this->validateExtra( $extra, false ) );
91
92        $ret = sprintf( '%d.%d.%d', $info['major'], $info['minor'], $info['patch'] );
93        if ( null !== $info['prerelease'] ) {
94            $ret .= '-' . $info['prerelease'];
95        }
96        if ( null !== $info['buildinfo'] ) {
97            $ret .= '+' . $info['buildinfo'];
98        }
99        return $ret;
100    }
101
102    /**
103     * Validate an `$extra` array.
104     *
105     * @param array $extra Extra components for the version. See `nextVersion()`.
106     * @param bool  $nulls Return nulls for unset fields.
107     * @return array
108     * @throws InvalidArgumentException If the `$extra` data is invalid.
109     */
110    private function validateExtra( array $extra, $nulls = true ) {
111        $info = array();
112
113        if ( isset( $extra['prerelease'] ) ) {
114            try {
115                $info['prerelease'] = $this->parseVersion( '0.0.0-' . $extra['prerelease'] )['prerelease'];
116            } catch ( InvalidArgumentException $ex ) {
117                throw new InvalidArgumentException( 'Invalid prerelease data' );
118            }
119        } elseif ( $nulls || array_key_exists( 'prerelease', $extra ) ) {
120            $info['prerelease'] = null;
121        }
122        if ( isset( $extra['buildinfo'] ) ) {
123            try {
124                $info['buildinfo'] = $this->parseVersion( '0.0.0+' . $extra['buildinfo'] )['buildinfo'];
125            } catch ( InvalidArgumentException $ex ) {
126                throw new InvalidArgumentException( 'Invalid buildinfo data' );
127            }
128        } elseif ( $nulls || array_key_exists( 'buildinfo', $extra ) ) {
129            $info['buildinfo'] = null;
130        }
131
132        return $info;
133    }
134
135    /**
136     * Determine the next version given a current version and a set of changes.
137     *
138     * @param string        $version Current version.
139     * @param ChangeEntry[] $changes Changes.
140     * @param array         $extra Extra components for the version.
141     *  - prerelease: (string|null) Prerelease version, e.g. "dev", "alpha", or "beta", if any. See semver docs for accepted values.
142     *  - buildinfo: (string|null) Build info, if any. See semver docs for accepted values.
143     * @return string
144     * @throws InvalidArgumentException If the version number is not in a recognized format, or other arguments are invalid.
145     */
146    public function nextVersion( $version, array $changes, array $extra = array() ) {
147        $info = array_merge(
148            $this->parseVersion( $version ),
149            $this->validateExtra( $extra )
150        );
151
152        $significances = array();
153        foreach ( $changes as $change ) {
154            $significances[ (string) $change->getSignificance() ] = true;
155        }
156        if ( isset( $significances['major'] ) ) {
157            $info['patch'] = 0;
158            if ( 0 === (int) $info['major'] ) {
159                if ( is_callable( array( $this->output, 'getErrorOutput' ) ) ) {
160                    $out = $this->output->getErrorOutput(); // @phan-suppress-current-line PhanUndeclaredMethod -- See https://github.com/phan/phan/issues/1204.
161                    $out->writeln( '<warning>Semver does not automatically move version 0.y.z to 1.0.0.</>' );
162                    $out->writeln( '<warning>You will have to do that manually when you\'re ready for the first release.</>' );
163                }
164                ++$info['minor'];
165            } else {
166                $info['minor'] = 0;
167                ++$info['major'];
168            }
169        } elseif ( isset( $significances['minor'] ) ) {
170            $info['patch'] = 0;
171            ++$info['minor'];
172        } else {
173            ++$info['patch'];
174        }
175
176        return $this->normalizeVersion( $info );
177    }
178
179    /**
180     * Compare two version numbers.
181     *
182     * @param string $a First version.
183     * @param string $b Second version.
184     * @return int Less than, equal to, or greater than 0 depending on whether `$a` is less than, equal to, or greater than `$b`.
185     * @throws InvalidArgumentException If the version numbers are not in a recognized format.
186     */
187    public function compareVersions( $a, $b ) {
188        $aa = $this->parseVersion( $a );
189        $bb = $this->parseVersion( $b );
190        if ( $aa['major'] !== $bb['major'] ) {
191            return $aa['major'] - $bb['major'];
192        }
193        if ( $aa['minor'] !== $bb['minor'] ) {
194            return $aa['minor'] - $bb['minor'];
195        }
196        if ( $aa['patch'] !== $bb['patch'] ) {
197            return $aa['patch'] - $bb['patch'];
198        }
199
200        if ( null === $aa['prerelease'] ) {
201            return null === $bb['prerelease'] ? 0 : 1;
202        }
203        if ( null === $bb['prerelease'] ) {
204            return -1;
205        }
206
207        $aaa = explode( '.', $aa['prerelease'] );
208        $bbb = explode( '.', $bb['prerelease'] );
209        $al  = count( $aaa );
210        $bl  = count( $bbb );
211        for ( $i = 0; $i < $al && $i < $bl; $i++ ) {
212            $a = $aaa[ $i ];
213            $b = $bbb[ $i ];
214            if ( ctype_digit( $a ) ) {
215                if ( ctype_digit( $b ) ) {
216                    if ( (int) $a !== (int) $b ) {
217                        return (int) $a - (int) $b;
218                    }
219                } else {
220                    return -1;
221                }
222            } elseif ( ctype_digit( $b ) ) {
223                return 1;
224            } else {
225                $tmp = strcmp( $a, $b );
226                if ( 0 !== $tmp ) {
227                    return $tmp;
228                }
229            }
230        }
231        return $al - $bl;
232    }
233
234    /**
235     * Return a valid "first" version number.
236     *
237     * @param array $extra Extra components for the version, as for `nextVersion()`.
238     * @return string
239     */
240    public function firstVersion( array $extra = array() ) {
241        return $this->normalizeVersion(
242            array(
243                'major' => 0,
244                'minor' => 1,
245                'patch' => 0,
246            ) + $this->validateExtra( $extra )
247        );
248    }
249}