blob: ea7724d53da85ed22e49d3f8b0da99bf831117c1 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
|
<?php
declare( strict_types = 1 );
namespace Maps\DataAccess;
use FileFetcher\FileFetcher;
use FileFetcher\FileFetchingException;
use MediaWiki\Storage\RevisionLookup;
/**
* Returns the content of the JSON file at the specified location as array.
* Empty array is returned on failure.
*
* @licence GNU GPL v2+
* @author Jeroen De Dauw < jeroendedauw@gmail.com >
*/
class GeoJsonFetcher {
private $fileFetcher;
private $titleParser;
private $revisionLookup;
public function __construct( FileFetcher $fileFetcher, \TitleParser $titleParser, RevisionLookup $revisionLookup ) {
$this->fileFetcher = $fileFetcher;
$this->titleParser = $titleParser;
$this->revisionLookup = $revisionLookup;
}
public function parse( string $fileLocation ): array {
return $this->fetch( $fileLocation )->getContent();
}
public function fetch( string $fileLocation ) {
try {
$title = $this->titleParser->parseTitle( $fileLocation, NS_GEO_JSON );
$revision = $this->revisionLookup->getRevisionByTitle( $title );
if ( $revision !== null ) {
$content = $revision->getContent( 'main' );
if ( $content instanceof \JsonContent ) {
return new GeoJsonFetcherResult(
$this->normalizeJson( $content->getNativeData() ),
$revision->getId(),
$title
);
}
}
}
catch ( \MalformedTitleException $e ) {
}
// Prevent reading JSON files on the server
if( !filter_var( $fileLocation, FILTER_VALIDATE_URL) ) {
return $this->newEmptyResult();
}
try {
return new GeoJsonFetcherResult(
$this->normalizeJson( $this->fileFetcher->fetchFile( $fileLocation ) ),
null,
null
);
}
catch ( FileFetchingException $ex ) {
return $this->newEmptyResult();
}
}
private function newEmptyResult(): GeoJsonFetcherResult {
return new GeoJsonFetcherResult(
[],
null,
null
);
}
private function normalizeJson( ?string $jsonString ): array {
if ( $jsonString === null ) {
return [];
}
$json = json_decode( $jsonString, true );
if ( $json === null ) {
return [];
}
return $json;
}
}
|