summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Maps/src/DataAccess/JsonFileParser.php
blob: 81d6cfa0ddc9c0720c351c99b2e4ae14a8b06f94 (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
<?php

declare( strict_types = 1 );

namespace Maps\DataAccess;

use FileFetcher\FileFetcher;
use FileFetcher\FileFetchingException;
use Maps\MapsFactory;
use ValueParsers\ParseException;
use ValueParsers\ValueParser;

/**
 * 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 JsonFileParser implements ValueParser {

	private $fileFetcher;
	private $pageContentFetcher;
	private $defaultNamespace;

	public function __construct( $fileFetcher = null, PageContentFetcher $pageContentFetcher = null ) {
		$this->fileFetcher = $fileFetcher instanceof FileFetcher
			? $fileFetcher : MapsFactory::newDefault()->getGeoJsonFileFetcher();

		$this->pageContentFetcher = $pageContentFetcher instanceof PageContentFetcher
			? $pageContentFetcher : MapsFactory::newDefault()->getPageContentFetcher();

		$this->defaultNamespace = NS_GEO_JSON;
	}

	/**
	 * @param string $fileLocation
	 *
	 * @return array
	 * @throws ParseException
	 */
	public function parse( $fileLocation ) {
		$jsonString = $this->getJsonString( $fileLocation );

		if ( $jsonString === null ) {
			return [];
		}

		$json = json_decode( $jsonString, true );

		if ( $json === null ) {
			return [];
		}

		return $json;
	}

	private function getJsonString( string $fileLocation ): ?string {
		$content = $this->pageContentFetcher->getPageContent( $fileLocation, $this->defaultNamespace );

		if ( $content instanceof \JsonContent ) {
			return $content->getNativeData();
		}

		// Prevent reading JSON files on the server
		if( !filter_var( $fileLocation, FILTER_VALIDATE_URL) ) {
			return null;
		}

		try {
			return $this->fileFetcher->fetchFile( $fileLocation );
		}
		catch ( FileFetchingException $ex ) {
			return null;
		}
	}


}