Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
15.22% covered (danger)
15.22%
7 / 46
25.00% covered (danger)
25.00%
1 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiDescription
15.22% covered (danger)
15.22%
7 / 46
25.00% covered (danger)
25.00%
1 / 4
172.01
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getDescription
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
 getDescriptionFromExtracts
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
72
 checkExtensions
35.71% covered (danger)
35.71%
5 / 14
0.00% covered (danger)
0.00%
0 / 1
8.25
1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
16 *
17 * @file
18 */
19
20declare( strict_types=1 );
21
22namespace MediaWiki\Extension\WikiSEO;
23
24use ApiMain;
25use ExtensionDependencyError;
26use ExtensionRegistry;
27use InvalidArgumentException;
28use MediaWiki\Request\FauxRequest;
29use MediaWiki\Title\Title;
30use MWException;
31
32class ApiDescription {
33
34    /**
35     * Description source
36     * Currently only TextExtracts is supported
37     */
38    private readonly string $source;
39
40    /**
41     * ApiDescription constructor.
42     * @param Title $title The page title to get the description from
43     * @param bool $tryCleanSentence Flag to try to remove dangling sentences
44     * @param string $source
45     * @throws ExtensionDependencyError
46     */
47    public function __construct(
48        private readonly Title $title,
49        private readonly bool $tryCleanSentence = false,
50        string $source = 'extracts',
51    ) {
52        $this->source = strtolower( $source );
53
54        $this->checkExtensions();
55    }
56
57    /**
58     * Request the description
59     *
60     * @return string
61     * @throws MWException
62     */
63    public function getDescription(): string {
64        switch ( $this->source ) {
65            case 'extracts':
66                return $this->getDescriptionFromExtracts();
67
68            default:
69                return '';
70        }
71    }
72
73    /**
74     * Call text extracts
75     * Returns an empty string on error
76     *
77     * @return string
78     * @throws MWException
79     */
80    public function getDescriptionFromExtracts(): string {
81        $query = [
82            'format' => 'json',
83            'action' => 'query',
84            'prop' => 'extracts',
85            'titles' => $this->title->getPrefixedText(),
86            'exchars' => 160,
87            'exintro' => 1,
88            'explaintext' => 1,
89            'exsectionformat' => 'plain'
90        ];
91
92        $request = new ApiMain( new FauxRequest( $query ) );
93
94        $request->execute();
95
96        $data = $request->getResult()->getResultData();
97
98        if ( $data === null ) {
99            return '';
100        }
101
102        if ( !isset( $data['batchcomplete'] ) ||
103            !isset( $data['query']['pages'] ) ||
104            $data['batchcomplete'] === false ||
105            empty( $data['query']['pages'] )
106        ) {
107            return '';
108        }
109
110        $text = array_shift( $data['query']['pages'] )['extract']['*'] ?? '';
111
112        if ( $this->tryCleanSentence && substr( $text, -1 ) !== '.' ) {
113            $parts = explode( '.', $text );
114            array_pop( $parts );
115            $text = sprintf( '%s.', implode( '.', $parts ) );
116        }
117
118        return str_replace( "\n", ' ', strip_tags( $text ) );
119    }
120
121    /**
122     * @throws ExtensionDependencyError
123     * @throws InvalidArgumentException
124     */
125    private function checkExtensions(): void {
126        switch ( $this->source ) {
127            case 'extracts':
128                if ( !ExtensionRegistry::getInstance()->isLoaded( 'TextExtracts' ) ) {
129                    throw new ExtensionDependencyError( [
130                        [
131                            'msg' => 'TextExtracts not loaded',
132                            'type' => 'missing-extensions',
133                            'missing' => 'TextExtracts',
134                        ]
135                    ] );
136                }
137                return;
138
139            default:
140                throw new InvalidArgumentException(
141                    sprintf( 'Format "%s" is not implemented. Use "extracts".', $this->source )
142                );
143        }
144    }
145}