Completed
Push — master ( 7c0b5b...8041ca )
by Stephan
16:56
created

MapView::getJsConfig()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 7
cts 7
cp 1
rs 8.9713
c 0
b 0
f 0
cc 2
eloc 16
nc 2
nop 0
crap 2
1
<?php
2
3
namespace SRF\Filtered\View;
4
5
use DataValues\Geo\Parsers\GeoCoordinateParser;
6
use Exception;
7
use Message;
8
use SMWPropertyValue;
9
use SRF\Filtered\ResultItem;
10
11
class MapView extends View {
12
13
	private static $viewParams = null;
14
15
	private $mapProvider = null;
16
17
18
	/**
19
	 * @param null $mapProvider
20
	 */
21 2
	public function setMapProvider( $mapProvider ) {
22 2
		$this->mapProvider = $mapProvider;
23 2
	}
24
25
	/**
26
	 * @return null
27
	 */
28 2
	public function getMapProvider() {
0 ignored issues
show
Coding Style introduced by
getMapProvider uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
29 2
		if ( $this->mapProvider === null ) {
30 2
			$this->setMapProvider( isset( $GLOBALS[ 'srfgMapProvider' ] ) ? $GLOBALS[ 'srfgMapProvider' ] : '' );
31
		}
32
33 2
		return $this->mapProvider;
34
	}
35
36
	/**
37
	 * @param ResultItem $row
38
	 * @return array|null
39
	 */
40 1
	public function getJsDataForRow( ResultItem $row ) {
41
42 1
		$markerPositionPropertyName = str_replace( ' ', '_', $this->getActualParameters()[ 'map view marker position property' ] );
43
44 1
		foreach ( $row->getValue() as $field ) {
45
46 1
			$printRequest = $field->getPrintRequest();
47 1
			$field->reset();
48
49 1
			$value = $field->getNextDataItem();
50 1
			if ( $printRequest->getData() instanceof SMWPropertyValue &&
51 1
				$printRequest->getData()->getInceptiveProperty()->getKey() === $markerPositionPropertyName &&
52 1
				( $value instanceof \SMWDIGeoCoord || $value instanceof \SMWDIBlob )
53
			) {
54
				$values = []; // contains plain text
55
56
				if ( $value instanceof \SMWDIGeoCoord ) {
57
58
					while ( $value instanceof \SMWDIGeoCoord ) {
59
						$values[] = [ 'lat' => $value->getLatitude(), 'lng' => $value->getLongitude() ];
60
						$value = $field->getNextDataItem();
61
					}
62
63
				} elseif ( class_exists( 'DataValues\Geo\Parsers\GeoCoordinateParser' ) ) {
64
65
					$coordParser = new GeoCoordinateParser();
0 ignored issues
show
Deprecated Code introduced by
The class DataValues\Geo\Parsers\GeoCoordinateParser has been deprecated with message: since 2.0, use the base class instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
66
					while ( $value instanceof \SMWDataItem ) {
67
						try {
68
							$latlng = $coordParser->parse( $value->getSerialization() );
69
							$values[] = [ 'lat' => $latlng->getLatitude(), 'lng' => $latlng->getLongitude() ];
70
							$value = $field->getNextDataItem();
71
						} catch ( Exception $exception ) {
72
							$this->getQueryPrinter()->addError( "Error on '$value': " . $exception->getMessage() );
73
						}
74
					}
75
76
				} else {
77
					$this->getQueryPrinter()->addError( Message::newFromKey( 'srf-filtered-map-geocoordinateparser-missing-error' )->inContentLanguage()->text() );
78
				}
79
80 1
				return [ 'positions' => $values, ];
81
			}
82
		}
83
84 1
		return null;
85
	}
86
87
	/**
88
	 * Returns an array of config data for this view to be stored in the JS
89
	 * @return array
90
	 */
91 1
	public function getJsConfig() {
92 1
		$config = parent::getJsConfig();
93
94
		$jsConfigKeys = [
95 1
			'height',
96
			'zoom',
97
			'minZoom',
98
			'maxZoom',
99
			'marker cluster',
100
			'marker cluster max zoom',
101
			'maxClusterRadius',
102
			'zoomToBoundsOnClick',
103
		];
104
105 1
		foreach ( $jsConfigKeys as $key ) {
106 1
			$this->addToConfig( $config, $key );
107
		}
108
109 1
		$this->addMarkerIconSetupToConfig( $config );
110
111 1
		$config[ 'map provider' ] = $this->getMapProvider();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $config['map provider'] is correct as $this->getMapProvider() (which targets SRF\Filtered\View\MapView::getMapProvider()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
112
113
		return $config;
114
	}
115
116
	/**
117
	 * A function to describe the allowed parameters of a query for this view.
118
	 *
119 2
	 * @return array of Parameter
120
	 */
121 2
	public static function getParameters() {
122
123 1
		if ( self::$viewParams === null ) {
124
125 1
			$params = parent::getParameters();
126
127
			$params[ 'marker position property' ] = [
128
				// 'type' => 'string',
129
				'name' => 'map view marker position property',
130
				'message' => 'srf-paramdesc-filtered-map-position',
131
				'default' => '',
132
				// 'islist' => false,
133 1
			];
134
135
			$params[ 'marker icon property' ] = [
136
				// 'type' => 'string',
137
				'name' => 'map view marker icon property',
138
				'message' => 'srf-paramdesc-filtered-map-icon',
139
				'default' => '',
140
				// 'islist' => false,
141 1
			];
142
143
			$params[ 'marker icons' ] = [
144
				// 'type' => 'string',
145
				'name' => 'map view marker icons',
146
				'message' => 'srf-paramdesc-filtered-map-icons',
147
				'default' => [],
148
				'islist' => true,
149 1
			];
150
151
			$params[ 'height' ] = [
152
				'type' => 'dimension',
153
				'name' => 'map view height',
154
				'message' => 'srf-paramdesc-filtered-map-height',
155
				'default' => 'auto',
156
				// 'islist' => false,
157 1
			];
158
159
			$params[ 'zoom' ] = [
160
				'type' => 'integer',
161
				'name' => 'map view zoom',
162
				'message' => 'srf-paramdesc-filtered-map-zoom',
163
				'default' => '',
164
				// 'islist' => false,
165
			];
166 1
167
			$params[ 'minZoom' ] = [
168
				'type' => 'integer',
169
				'name' => 'map view min zoom',
170
				'message' => 'srf-paramdesc-filtered-map-min-zoom',
171
				'default' => '',
172
				// 'islist' => false,
173
			];
174 1
175
			$params[ 'maxZoom' ] = [
176
				'type' => 'integer',
177
				'name' => 'map view max zoom',
178
				'message' => 'srf-paramdesc-filtered-map-max-zoom',
179
				'default' => '',
180
				// 'islist' => false,
181
			];
182
183 1
			//markercluster
184
			$params[ 'marker cluster' ] = [
185
				'type' => 'boolean',
186
				'name' => 'map view marker cluster',
187
				'message' => 'srf-paramdesc-filtered-map-marker-cluster',
188
				'default' => true,
189
				// 'islist' => false,
190
			];
191
192 1
			$params[ 'marker cluster max zoom' ] = [
193
				'type' => 'integer',
194
				'name' => 'map view marker cluster max zoom',
195
				'message' => 'srf-paramdesc-filtered-map-marker-cluster-max-zoom',
196
				'default' => '',
197
				// 'islist' => false,
198
			];
199
200 1
			//clustermaxradius - maxClusterRadius: The maximum radius that a cluster will cover from the central marker (in pixels). Default 80.
201
			$params[ 'maxClusterRadius' ] = [
202
				'type' => 'integer',
203 2
				'name' => 'map view marker cluster radius',
204
				'message' => 'srf-paramdesc-filtered-map-marker-cluster-max-radius',
205
				'default' => '',
206
				// 'islist' => false,
207
			];
208
209
			//clusterzoomonclick - zoomToBoundsOnClick: When you click a cluster we zoom to its bounds.
210
			$params[ 'zoomToBoundsOnClick' ] = [
211 1
				'type' => 'boolean',
212 1
				'name' => 'map view marker cluster zoom on click',
213
				'message' => 'srf-paramdesc-filtered-map-marker-cluster-zoom-on-click',
214
				'default' => true,
215
				// 'islist' => false,
216
			];
217
218
			self::$viewParams = $params;
219 1
		}
220
221 1
		return self::$viewParams;
222
	}
223 1
224
	/**
225 1
	 * Returns the name of the resource module to load.
226
	 *
227
	 * @return string
228
	 */
229 1
	public function getResourceModules() {
230
		return 'ext.srf.filtered.map-view';
231
	}
232
233
	/**
234 2
	 * @param array $config
235 2
	 * @param string $key
236
	 */
237
	private function addToConfig( &$config, $key ) {
238
239
		$paramDefinition = self::getParameters()[ $key ];
240
241
		$param = $this->getActualParameters()[ $paramDefinition[ 'name' ] ];
242
243
		if ( $param !== $paramDefinition[ 'default' ] ) {
244
			$config[ $key ] = $param;
245
		}
246
247
	}
248
249
	/**
250
	 * @param $config
251
	 */
252
	protected function addMarkerIconSetupToConfig( &$config ) {
253
254
		$param = $this->getActualParameters()[ 'map view marker icon property' ];
255
256
		if ( $param !== '' ) {
257
			$config[ 'marker icon property' ] = $this->getPropertyId( $param );
258
		}
259
260
		$config[ 'marker icons' ] = $this->getMarkerIcons();
261
	}
262
263
	/**
264
	 * @param $prop
265
	 * @return array
266
	 */
267
	protected function getPropertyId( $prop ) {
268
269
		$prop = strtr( $prop, ' ', '_' );
270
271
		$printrequests = $this->getQueryPrinter()->getPrintrequests();
272
		$cur = reset( $printrequests );
273
274
		while ( $cur !== false && ( !array_key_exists( 'property', $cur ) || $cur[ 'property' ] !== $prop ) ) {
275
			$cur = next( $printrequests );
276
		}
277
278
		return key( $printrequests );
279
	}
280
281
	/**
282
	 * @return array
283
	 */
284
	private function getMarkerIcons() {
285
286
		$ret = [];
287
288
		$actualParameters = self::getActualParameters()[ 'map view marker icons' ];
289
290
		foreach ( $actualParameters as $relation ) {
0 ignored issues
show
Bug introduced by
The expression $actualParameters of type string is not traversable.
Loading history...
291
292
			$relation = explode( '=', $relation, 2 );
293
294
			if ( count( $relation ) === 1 ) {
295
				$key = 'default';
296
				$icon = $relation[0];
297
			} else {
298
				$key = $relation[0];
299
				$icon = $relation[1];
300
			}
301
302
			$file = \WikiPage::factory( \Title::newFromText( $icon, NS_FILE ) )->getFile();
303
304
			if ( $file->exists() ) {
305
				$ret[ $key ] = $file->getUrl();
306
			} else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
307
				// TODO: $this->getQueryPrinter()->addError( NO_SUCH_FILE );
308
			}
309
		}
310
311
		return $ret;
312
	}
313
314
	/**
315
	 * @return bool
316
	 */
317
	public function getInitError() {
318
		return $this->getMapProvider() === ''? 'srf-filtered-map-provider-missing-error' : null;
319
	}
320
321
}