Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
CognateParseHookHandler
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 3
56
0.00% covered (danger)
0.00%
0 / 1
 newFromGlobalState
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 doContentAlterParserOutput
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2
3namespace Cognate\HookHandler;
4
5use Cognate\CognateRepo;
6use Cognate\CognateServices;
7use MediaWiki\MediaWikiServices;
8use MediaWiki\Parser\ParserOutput;
9use MediaWiki\Title\Title;
10
11/**
12 * @license GPL-2.0-or-later
13 * @author Addshore
14 */
15class CognateParseHookHandler {
16
17    /**
18     * @var CognateRepo
19     */
20    private $repo;
21
22    /**
23     * @var int[]
24     */
25    private $namespaces;
26
27    /**
28     * @var string
29     */
30    private $dbName;
31
32    public static function newFromGlobalState() {
33        $config = MediaWikiServices::getInstance()->getMainConfig();
34
35        return new CognateParseHookHandler(
36            CognateServices::getRepo(),
37            $config->get( 'CognateNamespaces' ),
38            $config->get( 'DBname' )
39        );
40    }
41
42    /**
43     * @param CognateRepo $repo
44     * @param int[] $namespaces
45     * @param string $dbName
46     */
47    public function __construct(
48        CognateRepo $repo,
49        array $namespaces,
50        $dbName
51    ) {
52        $this->repo = $repo;
53        $this->namespaces = $namespaces;
54        $this->dbName = $dbName;
55    }
56
57    /**
58     * Hook runs after internal parsing
59     * @see https://www.mediawiki.org/wiki/Manual:Hooks/ContentAlterParserOutput
60     *
61     * @param Title $title
62     * @param ParserOutput $parserOutput
63     *
64     * @return bool
65     */
66    public function doContentAlterParserOutput( Title $title, ParserOutput $parserOutput ) {
67        if ( !in_array( $title->getNamespace(), $this->namespaces ) ) {
68            return true;
69        }
70
71        $links = $parserOutput->getLanguageLinks();
72
73        $presentLanguages = [];
74        foreach ( $links as $linkString ) {
75            $linkParts = explode( ':', $linkString, 2 );
76            $presentLanguages[$linkParts[0]] = true;
77        }
78
79        $cognateLinks = $this->repo->getLinksForPage( $this->dbName, $title );
80
81        foreach ( $cognateLinks as $cognateLink ) {
82            $cognateLinkParts = explode( ':', $cognateLink, 2 );
83            if ( !array_key_exists( $cognateLinkParts[0], $presentLanguages ) ) {
84                $links[] = $cognateLink;
85            }
86        }
87
88        $parserOutput->setLanguageLinks( $links );
89
90        return true;
91    }
92
93}