Completed
Push — master ( a40b1f...acc53b )
by Nicolaas
01:38
created

GoogleMapDataResponse::showaroundmexml()   F

Complexity

Conditions 16
Paths 576

Size

Total Lines 62
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 62
rs 3.4193
c 0
b 0
f 0
cc 16
eloc 47
nc 576
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * The way the map works is that you open a page, which loads the initial page
5
 * with the map points being loaded as a separate XML doc.
6
 *
7
 * This controller returns the Google Map data XML sheet
8
 * You can show one point by adding ?i=123
9
 * Where 123 is the ID of a GoogleMapLocationsObject
10
 *
11
 * Here are other return options for the Map .... *
12
 *
13
 * 'index' / 'showemptymap' => map without anything on it, fallback
14
 *
15
 * 'showpagepointsmapxml' => show points from the current page
16
 *
17
 * 'showchildpointsmapxml' => show points from the child pages (all child pages)
18
 *
19
 * 'showdirectchildren' => show points from the child pages (direct ones only)
20
 *
21
 * 'showsearchpoint' =>
22
 *
23
 * 'showcustompagesmapxml' => these are sitetree elements loaded by session
24
 *
25
 * 'showcustomdosmapxml' =>
26
 *
27
 * 'showdataobjects' =>
28
 *
29
 * 'updatemexml' =>
30
 *
31
 * 'showaroundmexml' =>
32
 *
33
 * 'showpointbyid' => can also be more than one ID
34
 *
35
 */
36
37
class GoogleMapDataResponse extends Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
38
{
39
    private static $session_var_prefix = "addCustomGoogleMap";
0 ignored issues
show
Unused Code introduced by
The property $session_var_prefix is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
40
41
    /**
42
     * set searches in show around me to a specific max radius
43
     * @var int
44
     */
45
    private static $max_radius_for_show_around_me = 20000;
0 ignored issues
show
Unused Code introduced by
The property $max_radius_for_show_around_me is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
46
47
    /**
48
     * Default URL handlers - (Action)/(ID)/(OtherID)
49
     */
50
    private static $url_handlers = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $url_handlers is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
51
        '/$Action//$OwnerID/$Title/$Longitude/$Latitude/$FilterCode/$SecondFilterCode' => 'handleAction',
52
    );
53
54
55
56
57
58
    #################
59
    # SESSION MANAGEMENT
60
    #################
61
62
    protected static function session_var_name($filterCode = "")
63
    {
64
        return Config::inst()->get("GoogleMapDataResponse", "session_var_prefix")."_".$filterCode;
65
    }
66
67
    /**
68
     * @param Array $addCustomGoogleMapArrayNEW
69
     * @param string $filterCode
70
     *
71
     */
72
    public static function add_custom_google_map_session_data($addCustomGoogleMapArrayNEW, $filterCode = "")
73
    {
74
        $addCustomGoogleMapArrayOLD = Session::get(self::session_var_name($filterCode));
75
        $addCustomGoogleMapArrayNEW = array_merge($addCustomGoogleMapArrayOLD, $addCustomGoogleMapArrayNEW);
76
        Session::set(Session::get(self::session_var_name($filterCode), serialize($addCustomGoogleMapArrayNEW)));
0 ignored issues
show
Unused Code introduced by
The call to Session::get() has too many arguments starting with serialize($addCustomGoogleMapArrayNEW).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
Bug introduced by
The call to set() misses a required argument $val.

This check looks for function calls that miss required arguments.

Loading history...
77
    }
78
79
    /**
80
     *
81
     *
82
     * @param Array $addCustomGoogleMapArray
83
     * @param string $filterCode
84
     *
85
     */
86
    public static function set_custom_google_map_session_data($addCustomGoogleMapArray, $filterCode = "")
87
    {
88
        if (!is_array($addCustomGoogleMapArray)) {
89
            user_error("addCustomGoogleMapArray should be an array!");
90
        }
91
        Session::set(self::session_var_name($filterCode), serialize($addCustomGoogleMapArray));
92
    }
93
94
    /**
95
     * @param string $filterCode
96
     *
97
     * @return Array
98
     */
99
    public static function get_custom_google_map_session_data($filterCode = "")
100
    {
101
        $data = Session::get(self::session_var_name($filterCode));
102
        if (is_array($data)) {
103
            $addCustomGoogleMapArray = $data;
104
        } else {
105
            try {
106
                $addCustomGoogleMapArray = unserialize($data);
107
            } catch (Exception $e) {
108
                $addCustomGoogleMapArray = array();
109
            }
110
        }
111
        return $addCustomGoogleMapArray;
112
    }
113
114
    /**
115
     *
116
     * @param string $filterCode
117
     */
118
    public static function clear_custom_google_map_session_data($filterCode = "")
119
    {
120
        Session::clear(self::session_var_name($filterCode));
121
    }
122
123
124
125
126
127
128
129
    #################
130
    # BASICS
131
    #################
132
    /**
133
     * @inherited
134
     */
135
    private static $allowed_actions = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $allowed_actions is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
136
        'showemptymap' => true,
137
        'showpagepointsmapxml' => true,
138
        'showchildpointsmapxml' => true,
139
        'showdirectchildren' => true,
140
        'showsearchpoint' => true,
141
        'showcustompagesmapxml' => true,
142
        'showcustomdosmapxml' => true,
143
        'showdataobjects' => true,
144
        'updatemexml' => 'ADMIN',
145
        'showaroundmexml' => true,
146
        'showpointbyid' => true
147
    );
148
149
    /**
150
     * @var Array
151
     */
152
    private static $actions_without_owner = array(
153
        'showemptymap'
154
    );
155
156
    /**
157
     * The Page that is displaying the
158
     * @var SiteTree
159
     */
160
    protected $owner = null;
161
162
    /**
163
     * @var Float
164
     */
165
    protected $lng = 0;
166
167
    /**
168
     * @var Float
169
     */
170
    protected $lat = 0;
171
172
    /**
173
     * @var String
174
     */
175
    protected $title = "";
176
177
    /**
178
     * @var String
179
     */
180
    protected $filterCode = "";
181
182
    /**
183
     * @var String
184
     */
185
    protected $secondFilterCode = "";
186
187
    /**
188
     * @var GoogleMap
189
     */
190
    protected $map = null;
191
192
193
194
195
196
197
198
199
200
201
202
    #################
203
    # SET AND GET VARIABLES
204
    #################
205
206
    public function init()
0 ignored issues
show
Coding Style introduced by
init uses the super-global variable $_GET 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...
207
    {
208
        parent::init();
209
        $id = 0;
210
        if ($this->request->param("OwnerID")) {
211
            $id = intval($this->request->param("OwnerID"));
212
        } elseif (isset($_GET["i"])) {
213
            $i = intval($_GET["i"]);
214
            $point = GoogleMapLocationsObject::get()->byID($i);
215
            if (!$point) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies 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 if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

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

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
216
                //New POINT
217
            } else {
218
                $id = $point->ParentID;
219
            }
220
        }
221
        if ($id) {
222
            $this->owner = SiteTree::get()->byID($id);
0 ignored issues
show
Documentation Bug introduced by
It seems like \SiteTree::get()->byID($id) can also be of type object<DataObject>. However, the property $owner is declared as type object<SiteTree>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
223
        }
224
        //HACK
225
        elseif (!$this->owner) {
226
            $this->owner = DataObject::get_one(
227
                'SiteTree',
228
                array("Title" => Convert::raw2sql($this->request->param("Title")))
229
            );
230
        }
231
        if ($this->owner || in_array($this->request->param("Action"), self::$actions_without_owner)) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies 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 if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

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

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
232
            //all ok
233
        } elseif (in_array($this->request->param("Action"), self::$actions_without_owner)) {
234
            //ok too
235
            $this->owner = DataObject::get_one('SiteTree');
236
        } else {
237
            user_error("no owner has been identified for GoogleMapDataResponse", E_USER_NOTICE);
238
        }
239
        //END HACK
240
        $this->title = urldecode($this->request->param("Title"));
241
        $this->lng = floatval($this->request->param("Longitude"));
242
        $this->lat = floatval($this->request->param("Latitude"));
243
        $this->filterCode = urldecode($this->request->param("FilterCode"));
244
        $this->secondFilterCode = urldecode($this->request->param("SecondFilterCode"));
245
        if (!$this->title && $this->owner) {
246
            $this->title = $this->owner->Title;
247
        }
248
    }
249
250
    /**
251
     * @param object $owner
252
     */
253
    public function setOwner($owner)
254
    {
255
        $this->owner = $owner;
256
    }
257
258
    /**
259
     * @param String $title
260
     */
261
    public function setTitle($title)
262
    {
263
        $this->title = $title;
264
    }
265
266
    /**
267
     * @param float $lng
268
     */
269
    public function setLng($lng)
270
    {
271
        $this->lng = $lng;
272
    }
273
274
    /**
275
     * @param Float $lat
276
     */
277
    public function setLat($lat)
278
    {
279
        $this->lat = $lat;
280
    }
281
282
    /**
283
     * @param string $filterCode
284
     */
285
    public function setFilterCode($filterCode)
286
    {
287
        $this->filterCode = $filterCode;
288
    }
289
290
291
292
293
294
295
296
297
298
299
300
    #################
301
    # ACTIONS
302
    #################
303
304
    /**
305
     * @param SS_HTTPRequest
306
     *
307
     * @return String (XML)
308
     */
309
    public function index($request)
310
    {
311
        return $this->showemptymap($request);
312
    }
313
314
    /**
315
     * @param SS_HTTPRequest
316
     *
317
     * @return String (XML)
318
     */
319
    public function showemptymap($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
320
    {
321
        return $this->makeXMLData(null, null, $this->title, $this->title." "._t("GoogleMap.MAP", "map"));
322
    }
323
324
    /**
325
     * @param SS_HTTPRequest
326
     *
327
     * @return String (XML)
328
     */
329 View Code Duplication
    public function showpagepointsmapxml($request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
330
    {
331
        $data = GoogleMapLocationsObject::get()->filter(array("ParentID" => $this->owner->ID));
332
        if ($data->count()) {
333
            return $this->makeXMLData(null, $data, $this->title, $this->title." "._t("GoogleMap.MAP", "map"));
334
        }
335
        return $this->showemptymap($request);
336
    }
337
338
    /**
339
     * @param SS_HTTPRequest
340
     *
341
     * @return String (XML)
342
     */
343 View Code Duplication
    public function showchildpointsmapxml($request)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
344
    {
345
        if ($children = $this->owner->getChildrenOfType($this->owner, null)) {
346
            return $this->makeXMLData($children, null, $this->title, $this->title." "._t("GoogleMap.MAP", "map"));
347
        }
348
        return $this->showemptymap($request);
349
    }
350
351
    /**
352
     * @param SS_HTTPRequest
353
     *
354
     * @return String (XML)
355
     */
356
    public function showdirectchildren($request)
357
    {
358
        if ($children = Provider::get()) {
359
            return $this->makeXMLData($children, null, $this->title, $this->title." "._t("GoogleMap.MAP", "map"));
360
        }
361
        return $this->showemptymap($request);
362
    }
363
364
    /**
365
     * @param SS_HTTPRequest
366
     *
367
     * @return String (XML)
0 ignored issues
show
Documentation introduced by
Should the return type not be null|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
368
     */
369
    public function showsearchpoint($request)
370
    {
371
        if ($this->lat && $this->lng) {
372
            $point = GoogleMapLocationsObject::create();
373
            $point->ParentID = $this->owner->ID;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<GoogleMapLocationsObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
374
            $point->Latitude = $this->lat;
0 ignored issues
show
Documentation introduced by
The property Latitude does not exist on object<GoogleMapLocationsObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
375
            $point->Longitude = $this->lng;
0 ignored issues
show
Documentation introduced by
The property Longitude does not exist on object<GoogleMapLocationsObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
376
            $point->CustomPopUpWindowTitle = $this->title;
0 ignored issues
show
Documentation introduced by
The property CustomPopUpWindowTitle does not exist on object<GoogleMapLocationsObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
377
            if ($this->address) {
0 ignored issues
show
Documentation introduced by
The property address does not exist on object<GoogleMapDataResponse>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
378
                die("get address to do");
0 ignored issues
show
Coding Style Compatibility introduced by
The method showsearchpoint() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
379
                $point->CustomPopUpWindowInfo = $this->address;
0 ignored issues
show
Unused Code introduced by
$point->CustomPopUpWindowInfo = $this->address; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
380
            }
381
            if ($point) {
382
                $data = new ArrayList();
383
                $data->push($point);
384
                return $this->makeXMLData(null, $data, $this->title, $this->title);
0 ignored issues
show
Documentation introduced by
$data is of type object<ArrayList>, but the function expects a object<DataList>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
385
            }
386
        }
387
        return $this->showemptymap($request);
388
    }
389
390
    /**
391
     * @param SS_HTTPRequest
392
     *
393
     * @return String (XML)
394
     */
395
    public function showpointbyid($request)
396
    {
397
        $id = $request->param("FilterCode");
398
        $ids = explode(',', $id);
399
        foreach ($ids as $key => $id) {
400
            $ids[$key] = intval($id);
401
        }
402
        $className = Convert::raw2sql($request->param("SecondFilterCode"));
403
        $direct = false;
404
        if (! $className) {
405
            $direct = true;
406
        } elseif (! class_exists($className)) {
407
            $direct = true;
408
        }
409
        if ($direct) {
410
            $className = "GoogleMapLocationsObject";
411
        }
412
        $objects = $className::get()->filter(array("ID" => $ids));
413
        if ($direct) {
414
            return $this->makeXMLData(null, $objects, $this->title, $this->title);
415
        } else {
416
            return $this->makeXMLData($objects, null, $this->title, $this->title);
417
        }
418
    }
419
420
421
    /**
422
     * load data from session
423
     *
424
     * @param SS_HTTPRequest
425
     *
426
     * @return String (XML)
427
     */
428
    public function showcustompagesmapxml($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
429
    {
430
        $addCustomGoogleMapArray = GoogleMapDataResponse::get_custom_google_map_session_data($this->filterCode);
431
        $pages = SiteTree::get()->filter(array("ID" => $addCustomGoogleMapArray));
432
        return $this->makeXMLData($pages, null, $this->title, $this->title);
433
    }
434
435
    /**
436
     * load a custom set of GoogleMapLocationsObjects
437
     *
438
     * @param SS_HTTPRequest
439
     *
440
     * @return String (XML)
441
     */
442
    public function showcustomdosmapxml($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
443
    {
444
        $array = GoogleMapDataResponse::get_custom_google_map_session_data($this->filterCode);
445
        $googleMapLocationsObjects = GoogleMapLocationsObject::get()->filter(array("ID" => $array));
446
        return $this->makeXMLData(null, $googleMapLocationsObjects, $this->title, $this->title);
447
    }
448
449
    /**
450
     * Show what is around my points
451
     *
452
     * @param SS_HTTPRequest
453
     *
454
     * @return String (XML)
455
     */
456
    public function showaroundmexml($request)
0 ignored issues
show
Coding Style introduced by
showaroundmexml uses the super-global variable $_GET 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...
457
    {
458
        $lng = 0;
459
        $lat = 0;
460
        $maxRadius = intval($this->Config()->get('max_radius_for_show_around_me')) - 0;
461
        if (isset($_GET['maxradius'])) {
462
            $maxRadius = intval($_GET['maxradius']);
463
        }
464
        $excludeIDList = array();
465
        $stage = '';
466
        if (Versioned::current_stage() == "Live") {
467
            $stage = "_Live";
468
        }
469
        if ($this->lng && $this->lat) {
470
            $lng = $this->lng;
471
            $lat = $this->lat;
472
        } elseif ($this->owner->ID) {
473
            //find the average!
474
            $objects = GoogleMapLocationsObject::get()->filter(array("ParentID" => $this->owner->ID));
475
            if ($count = $objects->count()) {
476
                foreach ($objects as $point) {
477
                    $lng += $point->Longitude;
478
                    $lat += $point->Latitude;
479
                }
480
                $lng = $lng / $count;
481
                $lat = $lat / $count;
482
            }
483
        }
484
        $classNameForParent = '';
485
        if ($otherClass = $this->filterCode) {
486
            $classNameForParent = $otherClass;
487
        }
488
        if ($this->title) {
489
            $title = $this->title;
490
        } else {
491
            $title = _t("GoogleMap.CLOSES_TO_ME", "Closest to me");
492
        }
493
        if ($lng && $lat) {
494
            $orderByRadius = GoogleMapLocationsObject::radius_definition($lng, $lat);
495
            $where = "(".$orderByRadius.") > 0 (".$orderByRadius.") < ".$maxRadius." AND \"GoogleMapLocationsObject\".\"Latitude\" <> 0 AND \"GoogleMapLocationsObject\".\"Longitude\" <> 0";
496
            if ($classNameForParent && !is_object($classNameForParent)) {
497
                $where .= " AND \"SiteTree".$stage."\".\"ClassName\" = '".$classNameForParent."'";
498
            }
499
            if (count($excludeIDList)) {
500
                $where .= " AND \"GoogleMapLocationsObject\".\"ID\" NOT IN (".implode(",", $excludeIDList).") ";
501
            }
502
            $objects = GoogleMapLocationsObject::get()
503
                ->where($where)
504
                ->sort($orderByRadius)
505
                ->leftJoin("SiteTree".$stage."", "SiteTree".$stage.".ID = GoogleMapLocationsObject.ParentID")
506
                ->limit(Config::inst()->get("GoogleMap", "number_shown_in_around_me"));
507
            if ($objects->count()) {
508
                return $this->makeXMLData(
509
                    null,
510
                    $objects,
511
                    $title,
512
                    Config::inst()->get("GoogleMap", "number_shown_in_around_me") . " "._t("GoogleMap.CLOSEST_POINTS", "closest points")
513
                );
514
            }
515
        }
516
        return $this->showemptymap($request);
517
    }
518
519
    /**
520
     * URL must contain for GET variables
521
     * i - ID of owner
522
     * a - action
523
     * x - lng
524
     * y - lat
525
     *
526
     * actions are:
527
     *   - add
528
     *   - move
529
     *   - remove
530
     *
531
     * @param SS_HTTPRequest
532
     *
533
     * @return String (message)
0 ignored issues
show
Documentation introduced by
Should the return type not be integer|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
534
     */
535
    public function updatemexml($request)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Coding Style introduced by
updatemexml uses the super-global variable $_REQUEST 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...
536
    {
537
        //we use request here, because the data comes from javascript!
538
        if ($this->owner->canEdit()) {
539
            if (isset($_REQUEST["x"]) && isset($_REQUEST["y"]) && isset($_REQUEST["i"]) && isset($_REQUEST["a"])) {
540
                $lng = floatval($_REQUEST["x"]);
541
                $lat = floatval($_REQUEST["y"]);
542
                $id = intval($_REQUEST["i"]);
543
                $action = $_REQUEST["a"];
544
                if ($lng && $lat) {
545
                    if (0 == $id && "add" == $action) {
546
                        $point = new GoogleMapLocationsObject;
547
                        $point->ParentID = $this->owner->ID;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<GoogleMapLocationsObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
548
                        $point->Longitude = $lng;
0 ignored issues
show
Documentation introduced by
The property Longitude does not exist on object<GoogleMapLocationsObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
549
                        $point->Latitude = $lat;
0 ignored issues
show
Documentation introduced by
The property Latitude does not exist on object<GoogleMapLocationsObject>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

Since the property has write access only, you can use the @property-write annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
550
                        $point->write();
551
                        return $point->ID;
552
                    } elseif ($id > 0 && "move" == $action) {
553
                        $point = GoogleMapLocationsObject::get()->byID($id);
554
                        if ($point) {
555
                            if ($point->ParentID == $this->owner->ID) {
556
                                $point->Longitude = $lng;
557
                                $point->Latitude = $lat;
558
                                $point->Address = "";
559
                                $point->FullAddress = "";
560
                                $point->write();
561
                                return  _t("GoogleMap.LOCATION_UPDATED", "location updated");
562
                            } else {
563
                                return _t("GoogleMap.NO_PERMISSION_TO_UPDATE", "you dont have permission to update that location");
564
                            }
565
                        } else {
566
                            return _t("GoogleMap.COULD_NOT_FIND_LOCATION", "could not find location");
567
                        }
568
                    } elseif ($id && "remove" == $action) {
569
                        $point = GoogleMapLocationsObject::get()->byID($id);
570
                        if ($point) {
571
                            if ($point->ParentID == $this->owner->ID) {
572
                                $point->delete();
573
                                $point = null;
0 ignored issues
show
Unused Code introduced by
$point is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
574
                                return _t("GoogleMap.LOCATION_DELETED", "location deleted");
575
                            } else {
576
                                return _t("GoogleMap.NO_DELETE_PERMISSION", "you dont have permission to delete that location");
577
                            }
578
                        } else {
579
                            return _t("GoogleMap.COULD_NOT_FIND_LOCATION", "could not find location.");
580
                        }
581
                    }
582
                } else {
583
                    return _t("GoogleMap.LOCATION_NOT_DEFINED", "point not defined.");
584
                }
585
            } else {
586
                return _t("GoogleMap.MISSING_VARIABLES", "not enough information was provided.");
587
            }
588
        }
589
        return  _t("GoogleMap.POINT_NOT_UPDATED", "You do not have permission to change the map.");
590
    }
591
592
593
594
595
596
597
598
    #################
599
    # TEMPLATE METHODS
600
    #################
601
    /**
602
     *
603
     * @return GoogleMap
604
     */
605
    public function GoogleMapController()
606
    {
607
        if (!$this->map) {
608
            user_error("No map has been created");
609
        }
610
        return $this->map;
611
    }
612
613
614
615
616
617
618
619
620
    #################
621
    # PRIVATE PARTY
622
    #################
623
624
    /**
625
     * @param DataList $pages
0 ignored issues
show
Documentation introduced by
Should the type for parameter $pages not be DataList|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
626
     * @param DataList $dataPoints
0 ignored issues
show
Documentation introduced by
Should the type for parameter $dataPoints not be DataList|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
627
     * @param string $title
628
     * @param string $selectionStatement
629
     *
630
     * @return String (XML)
631
     */
632
    protected function makeXMLData(
633
        $pages = null,
634
        $dataPoints = null,
635
        $title = '',
636
        $selectionStatement = ''
0 ignored issues
show
Unused Code introduced by
The parameter $selectionStatement is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
637
    ) {
638
        $this->response->addHeader("Content-Type", "text/xml; charset=\"utf-8\"");
639
        return self::xml_sheet(
640
            $pages,
641
            $dataPoints,
642
            $title,
643
            $selectionStatement = ''
644
        );
645
    }
646
647
648
649
    ################################
650
    # STATIC METHODS
651
    ################################
652
653
    public static function xml_sheet(
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
654
        $pages = null,
655
        $dataPoints = null,
656
        $title = '',
657
        $selectionStatement = ''
658
    ) {
659
        $map = Injector::inst()->get("GoogleMap");
660
        $map->setTitleOfMap($title);
661
        $map->setWhereStatementDescription($selectionStatement ? $selectionStatement : $title);
662
        if ($pages) {
663
            $map->setPageDataObjectSet($pages);
664
        } elseif ($dataPoints) {
665
            $map->setPoints($dataPoints);
666
        }
667
        $map->createDataPoints();
668
        return $map->renderWith("GoogleMapXml");
669
    }
670
671
672
673
    /**
674
     * var arrayOfLatitudeAndLongitude: Array (Latitude" => 123, "Longitude" => 123, "Marker" => "red1");
675
     * Marker is optional
676
     * @param Array arrayOfLatitudeAndLongitude
677
     * @param String title
678
     *
679
     * @return String (HTML - img tag)
680
     */
681
682
    public static function quick_static_map($arrayOfLatitudeAndLongitude, $title)
683
    {
684
        $staticMapURL = '';
0 ignored issues
show
Unused Code introduced by
$staticMapURL is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
685
        $count = 0;
686
        //width
687
        $staticMapWidth = Config::inst()->get("GoogleMap", "google_map_width");
688
        if ($staticMapWidth > 512) {
689
            $staticMapWidth = 512;
690
        }
691
        //height
692
        $staticMapHeight = Config::inst()->get("GoogleMap", "google_map_height");
693
        if ($staticMapHeight > 512) {
694
            $staticMapHeight = 512;
695
        }
696
        $staticMapURL = "size=".$staticMapWidth."x".$staticMapHeight;
697
        if (count($arrayOfLatitudeAndLongitude)) {
698
            //http://maps.google.com/maps/api/staticmap?sensor=true&maptype=map&size=209x310&
699
            //markers=color:green%7Clabel:A%7C-45.0302,168.663
700
            //&markers=color:red%7Clabel:Q%7C-36.8667,174.767
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
701
            foreach ($arrayOfLatitudeAndLongitude as $row) {
702
                $staticMapURL .= '&amp;markers=color:'.$row["Colour"].'%7Clabel:'.$row["Label"].'%7C';
703
                $staticMapURL .= round($row["Latitude"], 6).",".round($row["Longitude"], 6);
704
                $count++;
705
            }
706
            if ($count == 1) {
707
                $staticMapURL .= '&amp;center='.$defaultCenter.'&amp;zoom='. Config::inst()->get("GoogleMap", "default_zoom");
0 ignored issues
show
Bug introduced by
The variable $defaultCenter does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
708
            }
709
        }
710
        return self::make_static_map_url_into_image($staticMapURL, $title);
711
    }
712
713
    /**
714
     * @param String $staticMapURL
715
     * @param String $title
716
     *
717
     * @return String (HTML - img tag)
718
     */
719
    protected static function make_static_map_url_into_image($staticMapURL, $title)
720
    {
721
        $fullStaticMapURL =
722
            'http://maps.google.com/maps/api/staticmap?'
723
                .Config::inst()->get("GoogleMap", "static_map_settings").'&amp;'
724
                .$staticMapURL.'&amp;'
725
                .'key='.Config::inst()->get("GoogleMap", "google_map_api_key");
726
        if (Config::inst()->get("GoogleMap", "save_static_map_locally")) {
727
            $fileName = str_replace(array('&', '|', ',', '=', ';'), array('', '', '', '', ''), $staticMapURL);
728
            $length = strlen($fileName);
729
            $fileName = "_sGMap".substr(hash("md5", $fileName), 0, 35)."_".$length.".gif";
730
            $fullStaticMapURL = StaticMapSaverForHTTPS::convert_to_local_file(str_replace('&amp;', '&', $fullStaticMapURL), $fileName);
731
        }
732
        return '<img class="staticGoogleMap" src="'.$fullStaticMapURL.'" alt="map: '.Convert::raw2att($title).'" />';
733
    }
734
}
735