Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
27 / 27 |
|
100.00% |
5 / 5 |
CRAP | |
100.00% |
1 / 1 |
SiteTableSiteLookup | |
100.00% |
27 / 27 |
|
100.00% |
5 / 5 |
11 | |
100.00% |
1 / 1 |
__construct | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
getSite | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
getSiteFromSitesLoop | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
5 | |||
getSiteFromHostMap | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
2 | |||
addSiteToHostMap | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 |
1 | <?php |
2 | |
3 | namespace FileImporter\Remote\MediaWiki; |
4 | |
5 | use FileImporter\Data\SourceUrl; |
6 | use MediaWiki\Site\Site; |
7 | use MediaWiki\Site\SiteLookup; |
8 | use Psr\Log\LoggerInterface; |
9 | use Psr\Log\NullLogger; |
10 | |
11 | /** |
12 | * Lookup that can be used to get a Site object from the locally configured sites based on the |
13 | * hostname. |
14 | * |
15 | * @license GPL-2.0-or-later |
16 | * @author Addshore |
17 | */ |
18 | class SiteTableSiteLookup { |
19 | |
20 | private SiteLookup $siteLookup; |
21 | private LoggerInterface $logger; |
22 | /** @var array<string,string> */ |
23 | private array $hostGlobalIdMap = []; |
24 | |
25 | public function __construct( SiteLookup $siteLookup, ?LoggerInterface $logger = null ) { |
26 | $this->siteLookup = $siteLookup; |
27 | $this->logger = $logger ?? new NullLogger(); |
28 | } |
29 | |
30 | public function getSite( SourceUrl $sourceUrl ): ?Site { |
31 | return $this->getSiteFromHostMap( $sourceUrl->getHost() ) ?? |
32 | $this->getSiteFromSitesLoop( $sourceUrl->getHost() ); |
33 | } |
34 | |
35 | private function getSiteFromSitesLoop( string $host ): ?Site { |
36 | /** @var Site|null $siteFound */ |
37 | $siteFound = null; |
38 | |
39 | /** @var Site $site */ |
40 | foreach ( $this->siteLookup->getSites() as $site ) { |
41 | if ( $site->getDomain() === $host ) { |
42 | if ( $siteFound ) { |
43 | $this->logger->warning( |
44 | 'Host {host} matches at least two sites, {site1} and {site2}.', |
45 | [ |
46 | 'host' => $host, |
47 | 'site1' => $siteFound->getGlobalId(), |
48 | 'site2' => $site->getGlobalId(), |
49 | ] |
50 | ); |
51 | return null; |
52 | } |
53 | |
54 | $siteFound = $site; |
55 | } |
56 | } |
57 | |
58 | if ( $siteFound ) { |
59 | $this->addSiteToHostMap( $siteFound, $host ); |
60 | return $siteFound; |
61 | } |
62 | |
63 | return null; |
64 | } |
65 | |
66 | private function getSiteFromHostMap( string $host ): ?Site { |
67 | if ( array_key_exists( $host, $this->hostGlobalIdMap ) ) { |
68 | return $this->siteLookup->getSite( $this->hostGlobalIdMap[$host] ); |
69 | } |
70 | |
71 | return null; |
72 | } |
73 | |
74 | private function addSiteToHostMap( Site $site, string $host ): void { |
75 | if ( $site->getGlobalId() ) { |
76 | $this->hostGlobalIdMap[$host] = $site->getGlobalId(); |
77 | } |
78 | } |
79 | |
80 | } |