Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 29
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
RepoApiInteractor
0.00% covered (danger)
0.00%
0 / 29
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 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 request
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace ArticlePlaceholder;
4
5use MediaWiki\Http\HttpRequestFactory;
6use MediaWiki\Json\FormatJson;
7use Wikimedia\Stats\StatsFactory;
8
9/**
10 * Gateway to API of the repository
11 *
12 * @license GPL-2.0-or-later
13 */
14class RepoApiInteractor {
15
16    /**
17     * @var string
18     */
19    private $repoApiUrl;
20
21    /**
22     * @var StatsFactory
23     */
24    private $statsFactory;
25
26    /**
27     * @var HttpRequestFactory
28     */
29    private $httpRequestFactory;
30
31    /**
32     * @param string $repoApiUrl
33     * @param StatsFactory $statsFactory
34     * @param HttpRequestFactory $httpRequestFactory
35     */
36    public function __construct(
37        $repoApiUrl,
38        StatsFactory $statsFactory,
39        HttpRequestFactory $httpRequestFactory
40    ) {
41        $this->repoApiUrl = $repoApiUrl;
42        $this->statsFactory = $statsFactory;
43        $this->httpRequestFactory = $httpRequestFactory;
44    }
45
46    /**
47     * @param array $params
48     *
49     * @return array
50     */
51    public function request( array $params ) {
52        $url = wfAppendQuery( $this->repoApiUrl, $params );
53        $req = $this->httpRequestFactory->create(
54            $url,
55            [
56                'userAgent' => 'ArticlePlaceholder ' . $this->httpRequestFactory->getUserAgent(),
57            ],
58            __METHOD__
59        );
60        $metric = $this->statsFactory->getCounter( 'ArticlePlaceholder_apitermsearch_total' );
61
62        $status = $req->execute();
63        if ( !$status->isOK() ) {
64            $metric->setLabel( 'status', 'errored' )
65                ->copyToStatsdAt( 'articleplaceholder.apitermsearch.errored' )
66                ->increment();
67            return [];
68        }
69
70        $json = $req->getContent();
71        $data = FormatJson::decode( $json, true );
72        if ( !$data || !empty( $data['error'] ) ) {
73            $metric->setLabel( 'status', 'invalid' )
74                ->copyToStatsdAt( 'articleplaceholder.apitermsearch.invalid' )
75                ->increment();
76            return [];
77        }
78
79        $metric->setLabel( 'status', 'ok' )
80            ->copyToStatsdAt( 'articleplaceholder.apitermsearch.ok' )
81            ->increment();
82        return $data;
83    }
84
85}