summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Translate/translationaids/QueryAggregatorAwareTranslationAid.php
blob: 11358315b27aa7c1530ef196b5e3793bf9fa3c71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
/**
 * Translation aid helper class.
 *
 * @file
 * @author Niklas Laxström
 * @license GPL-2.0-or-later
 */

/**
 * Helper class for translation aids which use web services.
 *
 * @ingroup TranslationAids
 * @since 2015.02
 */
abstract class QueryAggregatorAwareTranslationAid
	extends TranslationAid
	implements QueryAggregatorAware
{
	private $queries = [];
	private $aggregator;

	// Interface: QueryAggregatorAware
	public function setQueryAggregator( QueryAggregator $aggregator ) {
		$this->aggregator = $aggregator;
	}

	/**
	 * Stores a web service query for later execution.
	 * @param TranslationWebService $service
	 * @param string $from Source language
	 * @param string $to Target language
	 * @param string $text Source text
	 */
	protected function storeQuery( TranslationWebService $service, $from, $to, $text ) {
		$queries = $service->getQueries( $text, $from, $to );
		foreach ( $queries as $query ) {
			$this->queries[] = [
				'id' => $this->aggregator->addQuery( $query ),
				'language' => $from,
				'text' => $text,
				'service' => $service,
			];
		}
	}

	/**
	 * Returns all stored queries.
	 * @return array Map of executed queries:
	 *  - language: string: source language
	 *  - text: string: source text
	 *  - response: TranslationQueryResponse
	 */
	protected function getQueryData() {
		foreach ( $this->queries as &$queryData ) {
			$queryData['response'] = $this->aggregator->getResponse( $queryData['id'] );
			unset( $queryData['id'] );
		}

		return $this->queries;
	}

	/**
	 * Returns all web services of given type.
	 * @param string $type
	 * @return TranslationWebService[]
	 */
	protected function getWebServices( $type ) {
		global $wgTranslateTranslationServices;

		$services = [];
		foreach ( $wgTranslateTranslationServices as $name => $config ) {
			$service = TranslationWebService::factory( $name, $config );
			if ( !$service || $service->getType() !== $type ) {
				continue;
			}

			$services[$name] = $service;
		}

		return $services;
	}
}