Completed
Push — master ( 2fc117...7cb9e8 )
by Nicolaas
02:21
created

StockistCountryPage::AllChildLocations()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
/**
4
 *
5
 *
6
 *
7
 *
8
 *
9
 *
10
 *
11
 */
12
13
class StockistCountryPage extends StockistSearchPage
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...
14
{
15
16
    /**
17
     * @inherited
18
     */
19
    private static $icon = 'mysite/images/treeicons/StockistCountryPage';
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 $icon 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...
20
21
    /**
22
     * @inherited
23
     */
24
    private static $db = 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 $db 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...
25
        'CountryCode' => 'Varchar(3)'
26
    );
27
    /**
28
     * @inherited
29
     */
30
    private static $indexes = array(
0 ignored issues
show
Unused Code introduced by
The property $indexes 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...
31
        'CountryCode' => true
32
    );
33
34
    /**
35
     * @inherited
36
     */
37
    private static $many_many = array(
0 ignored issues
show
Unused Code introduced by
The property $many_many 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...
38
        'AdditionalCountries' => 'EcommerceCountry'
39
    );
40
41
    /**
42
     * extended by lumberjack
43
     * @var array
44
     */
45
    private static $extensions = array(
0 ignored issues
show
Unused Code introduced by
The property $extensions 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
        'Lumberjack',
47
    );
48
49
    /**
50
     * @inherited
51
     */
52
    //private static $indexes = array(
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
53
    //	'Country' => array ( 'type' => 'unique', 'value' => 'Country' )
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% 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...
54
    //);
55
56
    /**
57
     * @inherited
58
     */
59
    private static $default_child = 'StockistPage';
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 $default_child 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...
60
61
    /**
62
     * @inherited
63
     */
64
    private static $allowed_children = array('StockistPage', 'StockistCountryPage');
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_children 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...
65
66
    /**
67
     * @inherited
68
     */
69
    private static $can_be_root = false;
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 $can_be_root 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...
70
71
    /**
72
     * Standard SS variable.
73
     */
74
    private static $singular_name = "Stockist Country Page";
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 $singular_name 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...
75
    public function i18n_singular_name()
76
    {
77
        return "Stockist Country Page";
78
    }
79
80
    /**
81
     * Standard SS variable.
82
     */
83
    private static $plural_name = "Stockist Country Pages";
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 $plural_name 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...
84
    public function i18n_plural_name()
85
    {
86
        return "Stockist Country Pages";
87
    }
88
89
    /**
90
     * @inherited
91
     */
92
    private static $description = 'Stockist Country Page';
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 $description 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...
93
94
    public function getCMSFields()
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...
95
    {
96
        $fields = parent::getCMSFields();
97
        $fields->removeByName("Map");
98
        $fields->removeFieldFromTab('Root.Main', 'Content');
99
        $countryArrayWithCodes = EcommerceCountry::get()->map("Code", "Name")->toArray();
100
        $countryArrayWithIDs = EcommerceCountry::get()->map("ID", "Name")->toArray();
101
        $title = singleton("EcommerceCountry")->i18n_singular_name();
102
        $countryField = new DropdownField('CountryCode', $title, array("" => " -- please select -- ") + $countryArrayWithCodes);
103
        $fields->addFieldsToTab('Root.Countries', $countryField);
104
        $fields->addFieldsToTab('Root.Countries', new CheckboxSetField('AdditionalCountries', 'Also for ', $countryArrayWithIDs));
105
        $gridField = new GridField(
106
            'StockistPage',
107
            'Stockists',
108
            $this->Children(),
109
            new GridFieldConfig_Lumberjack()
110
        );
111
        $fields->addFieldsToTab('Root.Stockists', $gridField);
112
        return $fields;
113
    }
114
115
116
    public function validate()
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...
117
    {
118
        if ($this->CountryCode) {
119
            $items = StockistCountryPage::get()
120
                ->filter(array("CountryCode" => $this->CountryCode))
121
                ->exclude(array("ID" => $this->ID));
122
            if ($items->count()) {
123
                $otherCountries = implode(", ", $items->map("ID", "Title")->toArray());
124
                return new ValidationResult(false, "Another country with the same country code already exists: ".$this->CountryCode." namely: ".$otherCountries.".  Please change the country.");
125
            }
126
        } elseif (!StockistSearchPage::get()->byID($this->ParentID)) {
127
            return new ValidationResult(false, "You need to add a country to any Stockist Country Page that is not a continent!  Continents are defined as pages that are children of the main stockist search page.");
128
        }
129
        return parent::validate();
130
    }
131
132
    public function onBeforeWrite()
133
    {
134
        parent::onBeforeWrite();
135
        $this->CountryCode = strtoupper($this->CountryCode);
136
    }
137
138
    /**
139
     * returns an array of stockist types that can be shown in a map.
140
     * @return Array
141
     */
142
    public function getMapTypes()
143
    {
144
        $allTypes = singleton("StockistPage")->dbObject('Type')->enumValues();
145
        foreach ($allTypes as $key => $type) {
146
            if ($key == "Online Store") {
147
                unset($allTypes[$key]);
148
            }
149
        }
150
        return $allTypes;
151
    }
152
153
    /**
154
     *
155
     * create as many as you like
156
     * @inherited
157
     * @return Boolean
158
     */
159
    public function canCreate($member = null)
160
    {
161
        return true;
162
    }
163
164
    /**
165
     * a list of IDs of all child StockistCountryPages (recursive) and the page itself...
166
     * @return Array
167
     */
168
    public function AllChildrenIDs()
169
    {
170
        $array[$this->ID] = $this->ID;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$array was never initialized. Although not strictly required by PHP, it is generally a good practice to add $array = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
171
        $countries = $this->ChildCountries();
172
        foreach ($countries as $country) {
173
            $children = $country->AllChildrenIDs();
174
            foreach($children as $childIDKey => $childIDValue) {
175
                $array[$childIDKey] = $childIDValue;
176
            }
177
            $array[$country->ID] = $country->ID;
178
        }
179
        return $array;
180
    }
181
182
183
    /**
184
     * returns a data list of all child (recursive) GoogleMapLocationsObjects
185
     * @return DataList (GoogleMapLocationsObject)
186
     */
187
    public function AllChildLocations()
188
    {
189
        $ids = $this->AllChildrenIDs();
190
        $stockists = StockistPage::get()->filter(array('ParentID' => $ids));
191
        return GoogleMapLocationsObject::get()
192
            ->filter(array('ParentID' => $stockists->column('ID')));
193
    }
194
195
    /**
196
     * @return DataList | Null
197
     */
198
    public function ChildCountries()
199
    {
200
        return StockistCountryPage::get()->filter(array("ParentID" => $this->ID))->sort("Title");
201
    }
202
203
    /**
204
     * @return DataList | Null
205
     */
206
    public function AllPhysicalStockists()
207
    {
208
        return StockistPage::get()->filter(array("HasPhysicalStore" => true, "ParentID" => $this->AllChildrenIDs()));
209
    }
210
211
    /**
212
     * @return DataList | Null
213
     */
214
    public function AllOnlineStockists()
215
    {
216
        return StockistPage::get()->filter(array("HasWebStore" => 1, "ParentID" => $this->AllChildrenIDs()));
217
    }
218
219
    /**
220
     * alias for getStockistPointField
221
     * @return array
222
     */
223
    public function StockistPointValueList($fieldName = 'LocalityName')
224
    {
225
        return $this->getStockistPointValueList($fieldName);
226
    }
227
228
229
    /**
230
     * get a list of all values for one field for all stockists in this country
231
     * for example, all cities for Zimbabwe... (as defined by
232
     * its stockist pages AND the values saved in the stockists' geo locations.
233
     *
234
     * NB values are cached
235
     *
236
     * @param string $fieldName
0 ignored issues
show
Documentation introduced by
There is no parameter named $fieldName. Did you maybe mean $fieldNames?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
237
     * @return array
238
     */
239
    public function getStockistPointValueList($fieldNames = 'LocalityName')
240
    {
241
        if (!is_array($fieldNames)) {
242
            $fieldNames = array($fieldNames);
243
        }
244
        $cachekey = "getStockistPointField".'_'.$this->ID.'_'.implode('_', $fieldNames);
245
        $cache = SS_Cache::factory($cachekey);
246
        if (!($result = $cache->load($cachekey))) {
247
            $stockists = StockistPage::get()->filter(array("ParentID" => $this->AllChildrenIDs()));
248
            $array = array();
249
            foreach ($stockists as $stockist) {
250
                $array = array_merge($array, $stockist->getPointValues($fieldNames));
251
            }
252
            sort($array);
253
            $cache->save(serialize($array), $cachekey);
254
            return $array;
255
        }
256
257
        return unserialize($result);
258
    }
259
260
    /**
261
     * @return ArrayList
262
     */
263
    public function Cities()
264
    {
265
        $headingsCreated = array();
266
        $al = ArrayList::create();
267
        $array = $this->getStockistPointValueList(array('AdministrativeAreaName', 'LocalityName'));
268
        foreach ($array as $fieldInfo) {
269
            $childrenArray = explode(',', $fieldInfo);
270
            $URLSegmentFromFieldInfo = implode(',', array_map('urlencode', $childrenArray));
271
            if (count($childrenArray) > 1) {
272
                foreach ($childrenArray as $key => $child) {
273
                    if ($key == 0) {
274
                        $primaryChild = $child;
275
                        if (! isset($headingsCreated[$primaryChild])) {
276
                            $headingsCreated[$primaryChild] = ArrayList::create();
277
                            $arrayData = array(
278
                                "ID" => preg_replace("/[^A-Za-z0-9 ]/", '-', $child),
279
                                "Title" => $child,
280
                                "Link" => "",
281
                                "HasChildren" => true,
282
                                "Children" => $headingsCreated[$primaryChild]
283
                            );
284
                            $al->push(
285
                                ArrayData::create($arrayData)
286
                            );
287
                        }
288 View Code Duplication
                    } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
289
                        $arrayData = array(
290
                            "ID" => preg_replace("/[^A-Za-z0-9 ]/", '-', $child),
291
                            "Title" => $child,
292
                            "Link" => $this->Link("filter/LocalityName,AdministrativeAreaName/".$URLSegmentFromFieldInfo."/"),
293
                            "HasChildren" => false,
294
                            "Children" => null
295
                        );
296
                        $headingsCreated[$primaryChild]->push($arrayData);
0 ignored issues
show
Bug introduced by
The variable $primaryChild does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
297
                    }
298
                }
299 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
300
                $arrayData = array(
301
                    "ID" => preg_replace("/[^A-Za-z0-9 ]/", '-', $fieldInfo),
302
                    "Title" => $fieldInfo,
303
                    "Link" => $this->Link("filter/LocalityName,AdministrativeAreaName/".$URLSegmentFromFieldInfo."/"),
304
                    "HasChildren" => false,
305
                    "Children" => null
306
                );
307
                $al->push(
308
                    ArrayData::create($arrayData)
309
                );
310
            }
311
        }
312
        $al->sort("City");
313
        return $al;
314
    }
315
}
316
317
class StockistCountryPage_Controller extends StockistSearchPage_Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
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...
318
{
319
    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...
320
        'filter'
321
    );
322
323
324
    public function init()
325
    {
326
        parent::init();
327
        if ($this->CountryCode) {
328
            $this->myCurrentCountryCode = $this->CountryCode;
329
        }
330
        //Requirements::customScript("jQuery(document).ready(function(){jQuery('#MapSidebar').show();});");
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
331
    }
332
333
    public function index()
334
    {
335
        $this->addMap("showchildpointsmapxml");
336
        return array();
337
    }
338
339
    /**
340
     * for template
341
     * @return Boolean
342
     */
343
    public function IsSearchPage()
344
    {
345
        return false;
346
    }
347
348
    public function filter($request)
349
    {
350
        $points = $this->locationsForCurrentCountry($request)->column("ID");
351
        $this->Title .= ' - '. urldecode($this->request->param("OtherID"));
352
        $this->addMap(
353
            $action = "showpointbyid",
354
            $title = $this->Title,
355
            $lng = 0,
356
            $lat = 0,
357
            implode(',', $points)
358
        );
359
360
        return array();
361
    }
362
363
    public function locationsForCurrentCountry()
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...
364
    {
365
        $fields = explode(",", $this->request->param("ID"));
366
        $values = explode(",", $this->request->param("OtherID"));
367
        if (count($fields) && count($values)) {
368
            $whereArrayOuter = array();
369
            $whereArrayOuterOuter = array();
370
371
            foreach ($values as $value) {
372
                if ($value) {
373
                    $whereArrayInner = array();
374
                    foreach ($fields as $field) {
375
                        $whereArrayInner[] = Convert::raw2sql(trim($field))." = '".Convert::raw2sql(trim($value))."'";
376
                    }
377
                    $whereArrayOuter[] = '('.implode(' OR ', $whereArrayInner).')';
378
                }
379
            }
380
            if (count($whereArrayOuter)) {
381
                $whereArrayOuterOuter[] = '('.implode(' AND ', $whereArrayOuter).')';
382
            }
383
            if (count($this->myCurrentCountryCode)) {
384
                $whereArrayOuterOuter[] = '("CountryNameCode" = \''.$this->myCurrentCountryCode.'\')';
385
            }
386
            $points = GoogleMapLocationsObject::get();
387
            if (count($whereArrayOuterOuter)) {
388
                $points = $points->where('('.implode(' ) AND (', $whereArrayOuterOuter).')');
389
            }
390
        } else {
391
            $points = GoogleMapLocationsObject::get()->filter(array("CountryNameCode" => $this->myCurrentCountryCode));
392
        }
393
394
        return $points;
395
    }
396
}
397