Completed
Push — master ( 2b9bd3...31a468 )
by Nicolaas
01:33
created

API   F

Complexity

Total Complexity 77

Size/Duplication

Total Lines 433
Duplicated Lines 8.31 %

Coupling/Cohesion

Components 5
Dependencies 5

Importance

Changes 0
Metric Value
wmc 77
lcom 5
cbo 5
dl 36
loc 433
rs 2.1739
c 0
b 0
f 0

26 Methods

Rating   Name   Duplication   Size   Complexity  
A inst() 0 10 2
A setBaseClass() 0 4 1
B retrieveDBFields() 0 14 5
C DbFields() 6 40 12
A MyDbFields() 0 4 1
A MyDbFieldsWithDefaults() 0 8 1
A mydbfieldsfancywithbelongswithbasicfields() 0 4 1
A MyDbFieldsFancyWithBelongs() 0 4 1
D MyDbFieldsFancyWithoutBelongs() 0 43 12
A MyDbFieldsAndHasOnes() 0 6 1
A MyDbFieldsAndHasOnesWithIDs() 0 11 2
A MyDbFieldsAndIndexes() 0 10 1
A MyAllFieldsWithBelongs() 0 4 1
A MyAllFieldsWithoutBelongs() 0 16 3
A IndexOptions() 0 8 1
A RequiredOptions() 0 7 1
A PossibleRelationsWithBaseClass() 0 11 2
C PossibleRelations() 15 30 8
A PossibleSearchFilters() 0 15 4
B ModelAdminOptions() 0 21 5
A SortOptions() 0 7 1
A CanOptions() 0 16 2
B SiteTreeList() 15 21 6
A AllowedChildrenOptions() 0 4 1
A TrueOrFalseListWithIgnore() 0 7 1
A TrueOrFalseList() 0 7 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like API often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use API, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace SunnySideUp\BuildDataObject;
4
5
class API extends \Object
6
{
7
    private static $excluded_data_objects = [
0 ignored issues
show
Unused Code introduced by
The property $excluded_data_objects 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...
8
        'Image_Cached',
9
        'PermissionRoleCode',
10
        'LoginAttempt',
11
        'MemberPassword',
12
        'MemberPassword',
13
        'SiteConfig'
14
    ];
15
16
    private static $excluded_db_fields_types = [
0 ignored issues
show
Unused Code introduced by
The property $excluded_db_fields_types 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...
17
        'DBField',
18
        'Field',
19
        'DBLocale',
20
        'Locale',
21
        'StringField',
22
        'CompositeField',
23
        'PrimaryKey',
24
        'ForeignKey'
25
    ];
26
27
    private static $additional_db_fields = [
0 ignored issues
show
Unused Code introduced by
The property $additional_db_fields 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...
28
        'ID',
29
        'Created',
30
        'LastEdited',
31
        'ClassName'
32
    ];
33
34
    protected $rootBaseClass = 'DataObject';
35
36
    protected $myBaseClass = '';
37
38
    protected $_data = null;
39
40
    private static $_my_singleton = [];
41
42
    public static function inst($myBaseClass = 'DataObject', $data)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
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...
43
    {
44
        if (! isset(self::$_my_singleton[$myBaseClass])) {
45
            self::$_my_singleton[$myBaseClass] = \Injector::inst()->get('SunnySideUp\BuildDataObject\API');
46
        }
47
        self::$_my_singleton[$myBaseClass]->_data = $data;
48
        self::$_my_singleton[$myBaseClass]->setBaseClass($myBaseClass);
49
50
        return self::$_my_singleton[$myBaseClass];
51
    }
52
53
    public function setBaseClass($myBaseClass)
54
    {
55
        $this->myBaseClass = $myBaseClass;
56
    }
57
58
59
    protected function retrieveDBFields($name)
60
    {
61
        $data = $this->_data;
62
        $ar = [];
63
        if (isset($data->$name)) {
64
            foreach ($data->$name as $data) {
65
                if ($data->Key && $data->Value) {
66
                    $ar[$data->Key] = $data->Key;
67
                }
68
            }
69
        }
70
71
        return $ar;
72
    }
73
74
    protected $_dbfieldCache = [];
75
76
    public function DbFields()
77
    {
78
        if (count($this->_dbfieldCache) === 0) {
79
            $list = \ClassInfo::subclassesFor('DbField');
80
            $newList = [];
81
            foreach ($list as $class) {
0 ignored issues
show
Bug introduced by
The expression $list of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
82 View Code Duplication
                if (substr($class, 0, 2) == 'DB') {
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...
83
                    $class = substr($class, 2, strlen($class));
84
                }
85 View Code Duplication
                if (substr($class, 0, 3) == 'SS_') {
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...
86
                    $class = substr($class, 3, strlen($class));
87
                }
88
                if ('Varchar' === $class) {
89
                    $class = 'Varchar(n)';
90
                }
91
                if ('HTMLVarchar' === $class) {
92
                    $class = 'HTMLVarchar(n)';
93
                }
94
                if ('Enum' === $class) {
95
                    $class = 'Enum(\\\'Foo,Bar\\\', \\\'FOO\\\')';
96
                }
97
                if ('MultiEnum' === $class) {
98
                    $class = 'MultiEnum(\\\'Foo,Bar\\\', \\\'FOO\\\')';
99
                }
100
                if (
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...
101
                    $class == 'DbField' ||
102
                    is_subclass_of($class, 'TestOnly') ||
103
                    in_array($class, $this->Config()->get('excluded_db_fields_types'))
104
                ) {
105
                    //do nothing
106
                } else {
107
                    $newList[$class] = $class;
108
                }
109
            }
110
            ksort($newList);
111
            $this->_dbfieldCache = $newList;
112
        }
113
114
        return $this->_dbfieldCache;
115
    }
116
117
    public function MyDbFields()
118
    {
119
        return $this->retrieveDBFields('db');
120
    }
121
122
    public function MyDbFieldsWithDefaults()
123
    {
124
        $list = $this->retrieveDBFields('db');
125
        $toAdd = $this->Config()->get('additional_db_fields');
126
        $toAdd = array_combine($toAdd, $toAdd);
127
128
        return $toAdd + $list;
129
    }
130
131
    public function mydbfieldsfancywithbelongswithbasicfields()
132
    {
133
        return $this->MyDbFieldsFancyWithBelongs();
134
    }
135
    
136
    public function MyDbFieldsFancyWithBelongs()
137
    {
138
        return $this->myDbFieldsFancyWithoutBelongs(true);
139
    }
140
141
    public function MyDbFieldsFancyWithoutBelongs($includeBelongs = false)
142
    {
143
        $ar = [];
144
        $list = $this->retrieveDBFields('db');
145
        foreach ($list as $key => $value) {
146
            $ar[$key] = $key;
147
            $shortValue = explode('(', $value);
148
            $shortValue = $shortValue[0];
149
            switch ($shortValue) {
150
                case 'Varchar':
151
                case 'HTMLTextField':
152
                case 'HTMLVarchar':
153
                case 'Text':
154
                    $ar[$key.'.LimitCharacters'] = $key.'.LimitCharacters';
155
                    break;
156
                default:
157
                    $ar[$key.'.Nice'] = $key.'.Nice';
158
            }
159
        }
160
        $list = [];
161
        if ($includeBelongs) {
162
            $list += $this->retrieveDBFields('belongs_to');
163
        }
164
        $list += $this->retrieveDBFields('has_one');
165
        foreach ($list as $key => $value) {
166
            if ($value === 'Image' || is_subclass_of($value, 'Image')) {
167
                $ar[$key.'.Thumbnail'] = $key.'.Thumbnail';
168
            } else {
169
                $ar[$key.'.Title'] = $key.'.Title';
170
            }
171
        }
172
        $list =
173
            $this->retrieveDBFields('has_many') +
174
            $this->retrieveDBFields('many_many');
175
        if ($includeBelongs) {
176
            $list += $this->retrieveDBFields('belongs_many_many');
177
        }
178
        foreach ($list as $key => $value) {
179
            $ar[$key.'.Count'] = $key.'.Count';
180
        }
181
182
        return $ar;
183
    }
184
185
    public function MyDbFieldsAndHasOnes()
186
    {
187
        return
188
            $this->retrieveDBFields('db') +
189
            $this->retrieveDBFields('has_one');
190
    }
191
192
    public function MyDbFieldsAndHasOnesWithIDs()
193
    {
194
        $list = $this->retrieveDBFields('db');
195
        $hasOnes = $this->retrieveDBFields('has_one');
196
        foreach ($hasOnes as $field => $type) {
197
            $fieldWithID = $field . 'ID';
198
            $list[$fieldWithID] = $fieldWithID;
199
        }
200
201
        return $list;
202
    }
203
204
    public function MyDbFieldsAndIndexes()
205
    {
206
        return
207
            $this->MyDbFieldsWithDefaults() +
208
            ['index1' => 'index1'] +
209
            ['index2' => 'index2'] +
210
            ['index3' => 'index3'] +
211
            ['index4' => 'index4'] +
212
            ['index5' => 'index5'];
213
    }
214
215
    public function MyAllFieldsWithBelongs()
216
    {
217
        return $this->myAllFieldsWithoutBelongs(true);
218
    }
219
220
    public function MyAllFieldsWithoutBelongs($includeBelongs = false)
221
    {
222
        $list = $this->MyDbFieldsWithDefaults();
223
        if ($includeBelongs) {
224
            $list += $this->retrieveDBFields('belongs_to');
225
        }
226
        $list +=
227
            $this->retrieveDBFields('has_one') +
228
            $this->retrieveDBFields('has_many') +
229
            $this->retrieveDBFields('many_many');
230
        if ($includeBelongs) {
231
            $list += $this->retrieveDBFields('belongs_many_many');
232
        }
233
234
        return $list;
235
    }
236
237
238
    public function IndexOptions()
239
    {
240
        return [
241
            'true' => 'true',
242
            'unique("<column-name>")' => 'unique',
243
            '[\'type\' => \'<type>\', \'value\' => \'"<column-name>"\']' => 'other'
244
        ];
245
    }
246
247
    public function RequiredOptions()
248
    {
249
        return [
250
            'true' => 'true',
251
            'unique' => 'unique'
252
        ];
253
    }
254
255
256
    public function PossibleRelationsWithBaseClass($rootClass = '')
257
    {
258
        if($rootClass) {
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...
259
            //
260
        } else {
261
            $rootClass = $this->rootBaseClass;
262
        }
263
        return
264
            [$rootClass => $rootClass] +
265
            $this->possibleRelations();
266
    }
267
268
    protected $_classesCache = [];
269
270
    /**
271
     *
272
     * @return array
273
     */
274
    public function PossibleRelations($rootClass = '')
275
    {
276
        if($rootClass) {
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...
277
            //
278
        } else {
279
            $rootClass = $this->rootBaseClass;
280
        }
281
        if (!isset($this->_classesCache[$rootClass])) {
282
            $list = \ClassInfo::subclassesFor($rootClass);
283
            $newList = [];
284 View Code Duplication
            foreach ($list as $class) {
0 ignored issues
show
Bug introduced by
The expression $list of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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...
285
                if (
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...
286
                    $class == $rootClass ||
287
                    is_subclass_of($class, 'TestOnly') ||
288
                    in_array($class, $this->Config()->get('excluded_data_objects'))
289
                ) {
290
                    //do nothing
291
                } else {
292
                    $newList[$class] = $class;
293
                    $name = \Injector::inst()->get($class)->singular_name();
294
                    if ($name !== $class) {
295
                        $newList[$class] .= ' ('.$name.')';
296
                    }
297
                }
298
            }
299
            $this->_classesCache[$rootClass] = $newList;
300
        }
301
302
        return $this->_classesCache[$rootClass];
303
    }
304
305
    protected $_filtersCache = [];
306
307
    public function PossibleSearchFilters()
308
    {
309
        if (count($this->_filtersCache) === 0) {
310
            $list = \ClassInfo::subclassesFor('SearchFilter');
311
            $newList = [];
312
            foreach ($list as $class) {
0 ignored issues
show
Bug introduced by
The expression $list of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
313
                if ($class !== 'SearchFilter') {
314
                    $newList[$class] = $class;
315
                }
316
            }
317
            $this->_filtersCache = $newList;
318
        }
319
320
        return $this->_filtersCache;
321
    }
322
323
    protected $_modelAdmins = [];
324
325
    public function ModelAdminOptions()
326
    {
327
        if (count($this->_modelAdmins) === 0) {
328
            $list = \ClassInfo::subclassesFor('ModelAdmin');
329
            $newList = [];
330
            foreach ($list as $class) {
0 ignored issues
show
Bug introduced by
The expression $list of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
331
                if (
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...
332
                    $class == 'ModelAdmin' ||
333
                    is_subclass_of($class, 'TestOnly')
334
                ) {
335
                    //do nothing
336
                } else {
337
                    $newList[$class] = $class;
338
                }
339
            }
340
            $newList['tba'] = 'tba';
341
            $this->_modelAdmins = $newList;
342
        }
343
344
        return $this->_modelAdmins;
345
    }
346
347
348
    public function SortOptions()
349
    {
350
        return [
351
            'ASC' => 'ASC',
352
            'DESC' => 'DESC'
353
        ];
354
    }
355
356
    protected $_canOptions = null;
357
358
    public function CanOptions()
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...
359
    {
360
        if (! $this->_canOptions) {
361
            $ar = [
362
                'true' => 'always',
363
                'false' => 'never',
364
                'parent' => 'use parent class',
365
            ];
366
            $permissions = \Permission::get()->column('Code');
367
            $ar = $ar + array_combine($permissions, $permissions);
368
369
            $this->_canOptions = $ar;
370
        }
371
372
        return $this->_canOptions;
373
    }
374
375
376
377
    /**
378
     *
379
     * @return array
380
     */
381
    public function SiteTreeList($rootClass = 'SiteTree')
382
    {
383
        $list = \ClassInfo::subclassesFor($rootClass);
384 View Code Duplication
        foreach ($list as $class) {
0 ignored issues
show
Bug introduced by
The expression $list of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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...
385
            if (
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...
386
                $class == $rootClass ||
387
                is_subclass_of($class, 'TestOnly') ||
388
                in_array($class, $this->Config()->get('excluded_data_objects'))
389
            ) {
390
                //do nothing
391
            } else {
392
                $newList[$class] = $class;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$newList was never initialized. Although not strictly required by PHP, it is generally a good practice to add $newList = 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...
393
                $name = \Injector::inst()->get($class)->singular_name();
394
                if ($name !== $class) {
395
                    $newList[$class] .= ' ('.$name.')';
396
                }
397
            }
398
        }
399
400
        return $newList;
0 ignored issues
show
Bug introduced by
The variable $newList 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...
401
    }
402
403
404
    /**
405
     *
406
     * @return array
407
     */
408
    public function AllowedChildrenOptions($rootClass = 'SiteTree')
409
    {
410
        return ['none' => 'none'] + $this->SiteTreeList($rootClass);
411
    }
412
413
    /**
414
     *
415
     * @return array
416
     */
417
    public function TrueOrFalseListWithIgnore()
418
    {
419
        return [
420
            '' => '-- ignore --'
421
        ] +
422
        $this->TrueOrFalseList();
423
    }
424
425
    /**
426
     *
427
     * @return array
428
     */
429
    public function TrueOrFalseList()
430
    {
431
        return [
432
            'true' => 'YES',
433
            'false' => 'NO'
434
        ];
435
    }
436
437
}
438