1<?php
2/**
3 * Copyright © 2013 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22abstract class ApiQueryContinueTestBase extends ApiQueryTestBase {
23
24	/**
25	 * @var bool Enable to print in-depth debugging info during the test run
26	 */
27	protected $mVerbose = false;
28
29	/**
30	 * Run query() and compare against expected values
31	 * @param array $expected
32	 * @param array $params Api parameters
33	 * @param int $expectedCount Max number of iterations
34	 * @param string $id Unit test id
35	 * @param bool $continue True to use smart continue
36	 */
37	protected function checkC( $expected, $params, $expectedCount, $id, $continue = true ) {
38		$result = $this->query( $params, $expectedCount, $id, $continue );
39		$this->assertResult( $expected, $result, $id );
40	}
41
42	/**
43	 * Run query in a loop until no more values are available
44	 * @param array $params Api parameters
45	 * @param int $expectedCount Max number of iterations
46	 * @param string $id Unit test id
47	 * @param bool $useContinue True to use smart continue
48	 * @return array Merged results data array
49	 * @throws Exception
50	 */
51	protected function query( $params, $expectedCount, $id, $useContinue = true ) {
52		if ( isset( $params['action'] ) ) {
53			$this->assertEquals( 'query', $params['action'], 'Invalid query action' );
54		} else {
55			$params['action'] = 'query';
56		}
57		$count = 0;
58		$result = [];
59		$continue = [];
60		do {
61			$request = array_merge( $params, $continue );
62			uksort( $request, static function ( $a, $b ) {
63				// put 'continue' params at the end - lazy method
64				$a = strpos( $a, 'continue' ) !== false ? 'zzz ' . $a : $a;
65				$b = strpos( $b, 'continue' ) !== false ? 'zzz ' . $b : $b;
66
67				return strcmp( $a, $b );
68			} );
69			$reqStr = http_build_query( $request );
70			// $reqStr = str_replace( '&', ' & ', $reqStr );
71			$this->assertLessThan( $expectedCount, $count, "$id more data: $reqStr" );
72			if ( $this->mVerbose ) {
73				print "$id (#$count): $reqStr\n";
74			}
75			try {
76				$data = $this->doApiRequest( $request );
77			} catch ( Exception $e ) {
78				throw new Exception( "$id on $count", 0, $e );
79			}
80			$data = $data[0];
81			if ( isset( $data['warnings'] ) ) {
82				$warnings = json_encode( $data['warnings'] );
83				$this->fail( "$id Warnings on #$count in $reqStr\n$warnings" );
84			}
85			$this->assertArrayHasKey( 'query', $data, "$id no 'query' on #$count in $reqStr" );
86			if ( isset( $data['continue'] ) ) {
87				$continue = $data['continue'];
88				unset( $data['continue'] );
89			} else {
90				$continue = [];
91			}
92			if ( $this->mVerbose ) {
93				$this->printResult( $data );
94			}
95			$this->mergeResult( $result, $data );
96			$count++;
97			if ( empty( $continue ) ) {
98				$this->assertEquals( $expectedCount, $count, "$id finished early" );
99
100				return $result;
101			} elseif ( !$useContinue ) {
102				$this->assertFalse( 'Non-smart query must be requested all at once' );
103			}
104		} while ( true );
105	}
106
107	/**
108	 * @param array $data
109	 */
110	private function printResult( $data ) {
111		$q = $data['query'];
112		$print = [];
113		if ( isset( $q['pages'] ) ) {
114			foreach ( $q['pages'] as $p ) {
115				$m = $p['title'];
116				if ( isset( $p['links'] ) ) {
117					$m .= '/[' . implode( ',', array_map(
118						static function ( $v ) {
119							return $v['title'];
120						},
121						$p['links'] ) ) . ']';
122				}
123				if ( isset( $p['categories'] ) ) {
124					$m .= '/(' . implode( ',', array_map(
125						static function ( $v ) {
126							return str_replace( 'Category:', '', $v['title'] );
127						},
128						$p['categories'] ) ) . ')';
129				}
130				$print[] = $m;
131			}
132		}
133		if ( isset( $q['allcategories'] ) ) {
134			$print[] = '*Cats/(' . implode( ',', array_map(
135				static function ( $v ) {
136					return $v['*'];
137				},
138				$q['allcategories'] ) ) . ')';
139		}
140		self::getItems( $q, 'allpages', 'Pages', $print );
141		self::getItems( $q, 'alllinks', 'Links', $print );
142		self::getItems( $q, 'alltransclusions', 'Trnscl', $print );
143		print ' ' . implode( '  ', $print ) . "\n";
144	}
145
146	private static function getItems( $q, $moduleName, $name, &$print ) {
147		if ( isset( $q[$moduleName] ) ) {
148			$print[] = "*$name/[" . implode( ',',
149				array_map(
150					static function ( $v ) {
151						return $v['title'];
152					},
153					$q[$moduleName] ) ) . ']';
154		}
155	}
156
157	/**
158	 * Recursively merge the new result returned from the query to the previous results.
159	 * @param mixed &$results
160	 * @param mixed $newResult
161	 * @param bool $numericIds If true, treat keys as ids to be merged instead of appending
162	 */
163	protected function mergeResult( &$results, $newResult, $numericIds = false ) {
164		$this->assertEquals(
165			is_array( $results ),
166			is_array( $newResult ),
167			'Type of result and data do not match'
168		);
169		if ( !is_array( $results ) ) {
170			$this->assertEquals( $results, $newResult, 'Repeated result must be the same as before' );
171		} else {
172			$sort = null;
173			foreach ( $newResult as $key => $value ) {
174				if ( !$numericIds && $sort === null ) {
175					if ( !is_array( $value ) ) {
176						$sort = false;
177					} elseif ( array_key_exists( 'title', $value ) ) {
178						$sort = static function ( $a, $b ) {
179							return strcmp( $a['title'], $b['title'] );
180						};
181					} else {
182						$sort = false;
183					}
184				}
185				$keyExists = array_key_exists( $key, $results );
186				if ( is_numeric( $key ) ) {
187					if ( $numericIds ) {
188						if ( !$keyExists ) {
189							$results[$key] = $value;
190						} else {
191							$this->mergeResult( $results[$key], $value );
192						}
193					} else {
194						$results[] = $value;
195					}
196				} elseif ( !$keyExists ) {
197					$results[$key] = $value;
198				} else {
199					$this->mergeResult( $results[$key], $value, $key === 'pages' );
200				}
201			}
202			if ( $numericIds ) {
203				ksort( $results, SORT_NUMERIC );
204			} elseif ( $sort !== null && $sort !== false ) {
205				usort( $results, $sort );
206			}
207		}
208	}
209}
210