SearchByAddressForm::setUseAutocomplete()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * form that can be used to search by address
5
 *
6
 *
7
 *
8
 *
9
 */
10
11
12
class SearchByAddressForm extends Form
13
{
14
    private static $type_of_result = '';
15
16
    /**
17
     *
18
     * @var String
19
     */
20
    protected $defaultAddress = "";
21
22
    /**
23
     *
24
     * @param String
25
     */
26
    public function setDefaultAddress($s)
27
    {
28
        $this->defaultAddress = $s;
29
    }
30
31
    /**
32
     *
33
     * @var Array
34
     */
35
    protected $classNamesSearchedFor = array();
36
37
    /**
38
     *
39
     * @param Array
40
     */
41
    public function setClassNamesSearchedFor($a)
42
    {
43
        $this->classNamesSearchedFor = $a;
44
    }
45
46
    /**
47
     *
48
     * @var Boolean
49
     */
50
    protected $useAutocomplete = true;
51
52
    /**
53
     *
54
     * @param Boolean
55
     */
56
    public function setUseAutocomplete($a)
0 ignored issues
show
Unused Code introduced by
The parameter $a 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...
57
    {
58
        $this->useAutocomplete = $b;
0 ignored issues
show
Bug introduced by
The variable $b 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...
59
    }
60
61
62
63
    /**
64
     *
65
     * @param Controller $controller
66
     * @param String $name
67
     * @param String $defaultAddress
68
     * @param Array $classNamesSearchedFor
69
     *
70
     * @return Form
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
71
     */
72
    public function __construct($controller, $name, $defaultAddress = "", $classNamesSearchedFor = array("SiteTree"))
73
    {
74
        $this->defaultAddress = $defaultAddress;
75
        if (!$this->defaultAddress) {
76
            $this->defaultAddress = isset($_GET["FindNearAddress"]) ? $_GET["FindNearAddress"] : "";
77
        }
78
        $classNamesAsString = '';
79
        if (is_array($classNamesSearchedFor)) {
80
            $this->classNamesSearchedFor = $classNamesSearchedFor;
81
            $classNamesAsString = implode(",", $this->classNamesSearchedFor);
82
        }
83
        parent::__construct(
84
            $controller,
85
            "SearchByAddressForm",
86
            new FieldList(
87
                $addressField = new TextField(
88
                    "FindNearAddress",
89
                    _t("GoogleMapLocationsDOD.ENTERLOCATION", "Enter your location"),
90
                    $this->defaultAddress
91
                ),
92
                new HiddenField("ClassNamesSearchedFor", "ClassName", $classNamesAsString)
93
            ),
94
            new FieldList(new FormAction("findnearaddress", _t("GoogleMapLocationsDOD.SEARCH", "Search"))),
95
            new RequiredFields("FindNearAddress")
96
        );
97
        $addressField->setAttribute('placeholder', _t('GoogleMapLocationsDOD.YOUR_ADDRESS', "Enter your exact address or zip code here.")) ;
98
        if ($this->useAutocomplete) {
99
            $apiVersion = Config::inst()->get("GoogleMap", "api_version");
100
            Requirements::javascript(
101
                "//maps.googleapis.com/maps/api/js"
102
                ."?v=".$apiVersion
103
                ."&libraries=places"
104
                ."&key=".Config::inst()->get('GoogleMap', 'google_map_api_key')
105
            );
106
            $typeOfResult = $this->Config()->get('type_of_result');
107
            $setTypeLine = '';
108
            if ($typeOfResult) {
109
                $setTypeLine = 'autocomplete.setTypes([\''.$typeOfResult.'\']);';
110
            }
111
            Requirements::customScript(
112
                '
113
                function init_search_by_address_form() {
114
                    var input = document.getElementById("'.$this->getName()."_".$this->getName().'_FindNearAddress");
115
                    var options = {
116
                        \'location_type\' : \'ROOFTOP\'
117
                    };
118
                    var autocomplete = new google.maps.places.Autocomplete(input, options);
119
                    '.$setTypeLine.'
120
                }
121
                google.maps.event.addDomListener(window, "load", init_search_by_address_form);
122
                ',
123
                "SearchByAddressFormInit"
124
            );
125
        }
126
        $this->disableSecurityToken();
127
        return $this;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
128
    }
129
130
    public function findnearaddress($data, $form)
0 ignored issues
show
Unused Code introduced by
The parameter $form 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...
131
    {
132
        $address = Convert::raw2sql($data["FindNearAddress"]);
133
        $classNames = Convert::raw2sql($data["ClassNamesSearchedFor"]);
134
        $pointArray = GetLatLngFromGoogleUsingAddress::get_placemark_as_array($address);
0 ignored issues
show
Bug introduced by
It seems like $address defined by \Convert::raw2sql($data['FindNearAddress']) on line 132 can also be of type array; however, GetLatLngFromGoogleUsing...et_placemark_as_array() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
135
136
        if (!$pointArray || !isset($pointArray["Longitude"]) || !isset($pointArray["Latitude"])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $pointArray of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
137
            GoogleMapSearchRecord::create_new(
138
                Convert::raw2sql($address),
139
                $this->getController()->dataRecord->ID,
140
                false
141
            );
142
            $this->addErrorMessage(
143
                'FindNearAddress',
144
                _t("GoogleMapLocationsDOD.ADDRESSNOTFOUND", "Sorry, address could not be found..."),
145
                'warning'
146
            );
147
            return array();
148
        } else {
149
            GoogleMapSearchRecord::create_new(
150
                Convert::raw2sql($address),
151
                $this->getController()->dataRecord->ID,
152
                false
153
            );
154
        }
155
        $this->address = $pointArray["FullAddress"];
0 ignored issues
show
Bug introduced by
The property address does not seem to exist. Did you mean defaultAddress?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
156
        $lng = $pointArray["Longitude"];
157
        $lat = $pointArray["Latitude"];
158
        //$form->Fields()->fieldByName("Address")->setValue($pointArray["address"]); //does not work ....
159
        //$this->owner->addMap($action = "showsearchpoint", "Your search", $lng, $lat);
160
        $action = "showaroundmexml";
161
        $title = _t("GoogleMap.CLOSEST_TO_YOUR_SEARCH", "Closest to ").$this->address;
0 ignored issues
show
Bug introduced by
The property address does not seem to exist. Did you mean defaultAddress?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
162
        if (Director::is_ajax()) {
163
            $this->getController()->response->setBody(json_encode(array(
164
                'Action' =>  $action,
165
                'Title' => urlencode($title),
166
                'ParentID' => $this->getController()->ID,
167
                'Lng'=> $lng,
168
                'Lat'=> $lat,
169
                'ClassNames'=> $classNames
170
            )));
171
172
            $this->getController()->response->addHeader("Content-type", "application/json");
173
174
            return $this->getController()->response;
175
        }
176
        $this->getController()->addMap($action, $title, $lng, $lat, $classNames);
177
178
        return [];
179
    }
180
181
    /**
182
     * turns 0 into false and 1 into true
183
     * @param Mixed
184
     * @return String (true|false)
185
     */
186
    protected function showFalseOrTrue($v)
187
    {
188
        if ($v === true || 1 == $v) {
189
            return "true";
190
        } else {
191
            return "false";
192
        }
193
    }
194
}
195