Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
CxServerClient
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 2
30
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3namespace ContentTranslation\Service;
4
5use ContentTranslation\Exception\CxServerConfigurationException;
6use MediaWiki\Config\ServiceOptions;
7use MediaWiki\Http\HttpRequestFactory;
8use Psr\Log\LoggerInterface;
9
10class CxServerClient {
11
12    private string $cxServerHost;
13
14    /**
15     * @internal For use by ServiceWiring
16     */
17    public const CONSTRUCTOR_OPTIONS = [
18        'ContentTranslationCxServerHost'
19    ];
20
21    /**
22     * @throws CxServerConfigurationException
23     */
24    public function __construct(
25        private readonly HttpRequestFactory $httpRequestFactory,
26        private readonly LoggerInterface $logger,
27        ServiceOptions $options
28    ) {
29        $options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
30
31        $this->cxServerHost = $options->get( 'ContentTranslationCxServerHost' );
32
33        if ( !$this->cxServerHost ) {
34            throw new CxServerConfigurationException( 'Cxserver host not set' );
35        }
36    }
37
38    /**
39     * @param string $path relative path to the requested cxserver endpoint e.g. /suggest/sections/Football/en/el
40     * @return mixed
41     */
42    public function get( string $path ) {
43        $url = rtrim( $this->cxServerHost, '/' ) . '/' . ltrim( $path, '/' );
44        try {
45            $response = $this->httpRequestFactory->get( $url, [], __METHOD__ );
46        } catch ( \Exception $exception ) {
47            $this->logger->error(
48                'CX server request to {url} failed because of exception: {exception}',
49                [ 'url' => $url, 'exception' => $exception->getMessage() ]
50            );
51            return null;
52        }
53
54        if ( !$response ) {
55            $this->logger->error( 'CX server request to {url} returned an empty response', [ 'url' => $url ] );
56            return null;
57        }
58
59        return $response;
60    }
61}