Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
78 / 78
100.00% covered (success)
100.00%
9 / 9
CRAP
100.00% covered (success)
100.00%
1 / 1
WordpressVersioning
100.00% covered (success)
100.00%
78 / 78
100.00% covered (success)
100.00%
9 / 9
34
100.00% covered (success)
100.00%
1 / 1
 getOptions
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 parseVersion
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
7
 normalizeVersion
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 normalizeVersionInternal
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
4
 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%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 parsePrerelease
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 compareVersions
100.00% covered (success)
100.00%
14 / 14
100.00% covered (success)
100.00%
1 / 1
5
 firstVersion
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2/**
3 * WordPress 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;
14use Symfony\Component\Console\Input\InputOption;
15
16/**
17 * WordPress versioning plugin.
18 *
19 * - Major versions are in the form of a decimal number with tenths, e.g "9.4".
20 * - Point releases add another number after a dot.
21 * - Prerelease versions add a suffix: "-dev", "-alpha", "-beta", or "-rc",
22 *   with an optional number after all except "-dev".
23 * - Buildinfo adds any other `[a-zA-Z0-9.-]` after a '+' suffix.
24 */
25class WordpressVersioning implements VersioningPlugin {
26    use PluginTrait;
27
28    /**
29     * Define any command line options the versioning plugin wants to accept.
30     *
31     * @return InputOption[]
32     */
33    public function getOptions() {
34        return array(
35            new InputOption( 'point-release', null, InputOption::VALUE_NONE, 'Do a point release' ),
36        );
37    }
38
39    /**
40     * Parse a WordPress-style version.
41     *
42     * @param string $version Version.
43     * @return array With components:
44     *  - major: (float) Major version.
45     *  - point: (int) Point version.
46     *  - version: (string) Major combined with point.
47     *  - prerelease: (string|null) Pre-release string.
48     *  - buildinfo: (string|null) Build metadata string.
49     * @throws InvalidArgumentException If the version number is not in a recognized format.
50     * @phan-return array{major:float,point:int,version:string,prerelease:?string,buildinfo:?string}
51     */
52    public function parseVersion( $version ) {
53        if ( ! preg_match( '/^(?P<major>\d+\.\d)(?:\.(?P<point>\d+))?(?:-(?P<prerelease>dev|(?:alpha|beta|rc)\d*|(?:a|beta)\.\d+))?(?:\+(?P<buildinfo>[0-9a-zA-Z.-]+))?$/', $version, $m ) ) {
54            throw new InvalidArgumentException( "Version number \"$version\" is not in a recognized format." );
55        }
56        $ret            = array(
57            'major'      => (float) $m['major'],
58            'point'      => (int) ( $m['point'] ?? null ),
59            'prerelease' => isset( $m['prerelease'] ) && '' !== $m['prerelease'] ? $m['prerelease'] : null,
60            'buildinfo'  => isset( $m['buildinfo'] ) && '' !== $m['buildinfo'] ? $m['buildinfo'] : null,
61        );
62        $ret['version'] = sprintf( '%.1f', (float) $m['major'] );
63        if ( 0 !== $ret['point'] ) {
64            $ret['version'] .= '.' . $ret['point'];
65        }
66        return $ret;
67    }
68
69    /**
70     * Check and normalize a version number.
71     *
72     * @param string $version Version string.
73     * @param array  $extra Extra components for the version, replacing any in `$version`.
74     * @return string Normalized version.
75     * @throws InvalidArgumentException If the version number is not in a recognized format or extra is invalid.
76     */
77    public function normalizeVersion( $version, $extra = array() ) {
78        return $this->normalizeVersionInternal( $this->parseVersion( $version ), $extra );
79    }
80
81    /**
82     * Check and normalize a version number.
83     *
84     * @param array{major:float,point:int,prerelease?:?string,buildinfo?:?string} $version Version info.
85     * @param array                                                               $extra Extra components for the version, replacing any in `$version`.
86     * @return string Normalized version.
87     * @throws InvalidArgumentException If the version number is not in a recognized format or extra is invalid.
88     */
89    private function normalizeVersionInternal( $version, $extra = array() ) {
90        $info = $version + array(
91            'prerelease' => null,
92            'buildinfo'  => null,
93        );
94        $info = array_merge( $info, $this->validateExtra( $extra, false ) );
95        '@phan-var array{major:float,point:int,prerelease:?string,buildinfo:?string} $info'; // The array_merge confuses Phan.
96
97        $ret = sprintf( '%.1f', $info['major'] );
98        if ( 0 !== $info['point'] ) {
99            $ret .= '.' . $info['point'];
100        }
101        if ( null !== $info['prerelease'] ) {
102            $ret .= '-' . $info['prerelease'];
103        }
104        if ( null !== $info['buildinfo'] ) {
105            $ret .= '+' . $info['buildinfo'];
106        }
107        return $ret;
108    }
109
110    /**
111     * Validate an `$extra` array.
112     *
113     * @param array $extra Extra components for the version. See `nextVersion()`.
114     * @param bool  $nulls Return nulls for unset fields.
115     * @return array{prerelease?:?string,buildinfo?:?string}
116     * @throws InvalidArgumentException If the `$extra` data is invalid.
117     */
118    private function validateExtra( array $extra, $nulls = true ) {
119        $info = array();
120
121        if ( isset( $extra['prerelease'] ) ) {
122            try {
123                $info['prerelease'] = $this->parseVersion( '0.0-' . $extra['prerelease'] )['prerelease'];
124            } catch ( InvalidArgumentException $ex ) {
125                throw new InvalidArgumentException( 'Invalid prerelease data' );
126            }
127        } elseif ( $nulls || array_key_exists( 'prerelease', $extra ) ) {
128            $info['prerelease'] = null;
129        }
130        if ( isset( $extra['buildinfo'] ) ) {
131            try {
132                $info['buildinfo'] = $this->parseVersion( '0.0+' . $extra['buildinfo'] )['buildinfo'];
133            } catch ( InvalidArgumentException $ex ) {
134                throw new InvalidArgumentException( 'Invalid buildinfo data' );
135            }
136        } elseif ( $nulls || array_key_exists( 'buildinfo', $extra ) ) {
137            $info['buildinfo'] = null;
138        }
139
140        return $info;
141    }
142
143    /**
144     * Determine the next version given a current version and a set of changes.
145     *
146     * @param string        $version Current version.
147     * @param ChangeEntry[] $changes Changes.
148     * @param array         $extra Extra components for the version.
149     * @return string
150     * @throws InvalidArgumentException If the version number is not in a recognized format, or other arguments are invalid.
151     */
152    public function nextVersion( $version, array $changes, array $extra = array() ) {
153        $info = array_merge(
154            $this->parseVersion( $version ),
155            $this->validateExtra( $extra )
156        );
157        '@phan-var array{major:float,point:int,prerelease:?string,buildinfo:?string} $info'; // The array_merge confuses Phan.
158
159        if ( $this->input->getOption( 'point-release' ) ) {
160            ++$info['point'];
161        } else {
162            $info['point']  = 0;
163            $info['major'] += 0.1;
164        }
165
166        return $this->normalizeVersionInternal( $info );
167    }
168
169    /**
170     * Extract the index and values from a prerelease string.
171     *
172     * @param string|null $s String.
173     * @return array First element being the index value of the pattern matched, subsequent elements being int values of the matched capture groups.
174     * @throws InvalidArgumentException If the string is invalid.
175     */
176    private function parsePrerelease( $s ) {
177        if ( null === $s ) {
178            return array( 100, 0 );
179        }
180
181        foreach ( array( 'dev', 'alpha(\d*)', 'a\.(\d+)', 'beta(\d*)', 'beta\.(\d+)', 'rc(\d*)' ) as $i => $re ) {
182            if ( preg_match( "/^{$re}\$/", $s, $m ) ) {
183                $m[0] = $i;
184                return array_map( 'intval', $m );
185            }
186        }
187
188        throw new InvalidArgumentException( "Invalid prerelease string \"$s\"" ); // @codeCoverageIgnore
189    }
190
191    /**
192     * Compare two version numbers.
193     *
194     * @param string $a First version.
195     * @param string $b Second version.
196     * @return int Less than, equal to, or greater than 0 depending on whether `$a` is less than, equal to, or greater than `$b`.
197     * @throws InvalidArgumentException If the version numbers are not in a recognized format.
198     */
199    public function compareVersions( $a, $b ) {
200        $aa = $this->parseVersion( $a );
201        $bb = $this->parseVersion( $b );
202
203        $ret = $aa['major'] <=> $bb['major'];
204        if ( ! $ret ) {
205            $ret = $aa['point'] <=> $bb['point'];
206        }
207        if ( $ret ) {
208            return $ret;
209        }
210
211        $avalues = $this->parsePrerelease( $aa['prerelease'] );
212        $bvalues = $this->parsePrerelease( $bb['prerelease'] );
213
214        $l = min( count( $avalues ), count( $bvalues ) );
215        for ( $i = 0; $i < $l; $i++ ) {
216            if ( $avalues[ $i ] !== $bvalues[ $i ] ) {
217                return $avalues[ $i ] <=> $bvalues[ $i ];
218            }
219        }
220
221        return count( $avalues ) <=> count( $bvalues );
222    }
223
224    /**
225     * Return a valid "first" version number.
226     *
227     * @param array $extra Extra components for the version, as for `nextVersion()`.
228     * @return string
229     */
230    public function firstVersion( array $extra = array() ) {
231        return $this->normalizeVersionInternal(
232            array(
233                'major' => 0.0,
234                'point' => 0,
235            ) + $this->validateExtra( $extra )
236        );
237    }
238}