Completed
Pull Request — master (#54)
by John
02:07
created

BaseElement   F

Complexity

Total Complexity 53

Size/Duplication

Total Lines 402
Duplicated Lines 5.72 %

Coupling/Cohesion

Components 3
Dependencies 24

Importance

Changes 0
Metric Value
wmc 53
lcom 3
cbo 24
dl 23
loc 402
rs 2.1524
c 0
b 0
f 0

18 Methods

Rating   Name   Duplication   Size   Complexity  
C getCMSFields() 0 79 13
A isEndofLine() 0 10 2
A onBeforeWrite() 0 14 4
C onBeforeDelete() 0 52 10
A i18n_singular_name() 0 4 1
A getElementType() 0 4 1
A getTitle() 12 12 3
A getCMSTitle() 11 11 3
A ControllerTop() 0 4 1
A getPage() 0 14 3
A forTemplate() 0 4 1
A getEditLink() 0 8 1
A onBeforeVersionedPublish() 0 4 1
B all_allowed_elements() 0 28 5
A getDefaultSearchContext() 0 16 1
A setVirtualOwner() 0 3 1
A getVirtualLinkedElements() 0 3 1
A getPublishedVirtualLinkedElements() 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 BaseElement 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 BaseElement, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @package elemental
5
 */
6
class BaseElement extends Widget
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...
7
{
8
    /**
9
     * @var array $db
10
     */
11
    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...
12
        'ExtraClass' => 'Varchar(255)',
13
        'HideTitle' => 'Boolean'
14
    );
15
16
    /**
17
     * @var array $has_one
18
     */
19
    private static $has_one = 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 $has_one 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
        'List' => 'ElementList' // optional.
21
    );
22
23
    /**
24
     * @var array $has_many
25
     */
26
    private static $has_many = 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 $has_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...
27
        'VirtualClones' => 'ElementVirtualLinked'
28
    );
29
30
    /**
31
     * @var string
32
     */
33
    private static $title = "Content Block";
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 $title 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...
34
35
    /**
36
     * @var string
37
     */
38
    private static $singular_name = 'Content Block';
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...
39
40
    /**
41
     * @var array
42
     */
43
    private static $summary_fields = 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 $summary_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...
44
        'ID' => 'ID',
45
        'Title' => 'Title',
46
        'ElementType' => 'Type'
47
    );
48
49
    /**
50
     * @var array
51
     */
52
    private static $searchable_fields = 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 $searchable_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...
53
        'ID' => array(
54
            'field' => 'NumericField'
55
        ),
56
        'Title',
57
        'LastEdited',
58
        'ClassName'
59
    );
60
61
    /**
62
     * @var boolean
63
     */
64
    private static $enable_title_in_template = false;
0 ignored issues
show
Unused Code introduced by
The property $enable_title_in_template 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
     * @var Object
68
     * The virtual owner VirtualLinkedElement
69
     */
70
    public $virtualOwner;
71
72
73
    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...
74
    {
75
        $fields = $this->scaffoldFormFields(array(
76
            'includeRelations' => ($this->ID > 0),
77
            'tabbed' => true,
78
            'ajaxSafe' => true
79
        ));
80
81
        $fields->insertAfter(new ReadonlyField('ClassNameTranslated', _t('BaseElement.TYPE', 'Type'), $this->i18n_singular_name()), 'Title');
0 ignored issues
show
Documentation introduced by
'Title' is of type string, but the function expects a object<FormField>.

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...
82
        $fields->removeByName('ListID');
83
        $fields->removeByName('ParentID');
84
        $fields->removeByName('Sort');
85
        $fields->removeByName('ExtraClass');
86
87
        if (!$this->config()->enable_title_in_template) {
88
            $fields->removeByName('HideTitle');
89
            $title = $fields->fieldByName('Root.Main.Title');
90
91
            if ($title) {
92
                $title->setRightTitle('For reference only. Does not appear in the template.');
93
            }
94
        }
95
96
        $fields->addFieldToTab('Root.Settings', new TextField('ExtraClass', 'Extra CSS Classes to add'));
97
98
        if (!is_a($this, 'ElementList')) {
99
            $lists = ElementList::get()->filter('ParentID', $this->ParentID);
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<BaseElement>. 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...
100
101
            if ($lists->exists()) {
102
                $fields->addFieldToTab('Root.Settings',
103
                    $move = new DropdownField('MoveToListID', 'Move this to another list', $lists->map('ID', 'CMSTitle'), '')
104
                );
105
106
                $move->setEmptyString('Select a list..');
107
                $move->setHasEmptyDefault(true);
108
            }
109
        }
110
111
112
        if($virtual = $fields->dataFieldByName('VirtualClones')) {
113
            if($this->Parent() && $this->Parent()->exists() && $this->Parent()->getOwnerPage() && $this->Parent()->getOwnerPage()->exists()) {
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on BaseElement. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
114
                $tab = $fields->findOrMakeTab('Root.VirtualClones');
115
                $tab->setTitle(_t('BaseElement.VIRTUALTABTITLE', 'Linked To'));
116
117
                $tab->push(new LiteralField('DisplaysOnPage', sprintf(
118
                    "<p>The original content block appears on <a href='%s'>%s</a></p>",
119
                    $this->Parent()->getOwnerPage()->Link(),
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on BaseElement. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
120
                    $this->Parent()->getOwnerPage()->MenuTitle
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on BaseElement. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
121
                )));
122
123
                $virtual->setConfig(new GridFieldConfig_Base());
0 ignored issues
show
Bug introduced by
The method setConfig() does not exist on FormField. Did you maybe mean config()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
124
                $virtual
0 ignored issues
show
Bug introduced by
The method getConfig() does not exist on FormField. Did you maybe mean config()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
125
                    ->setTitle(_t('BaseElement.OTHERPAGES', 'Other pages'))
126
                    ->getConfig()
127
                        ->removeComponentsByType('GridFieldAddExistingAutocompleter')
128
                        ->removeComponentsByType('GridFieldAddNewButton')
129
                        ->removeComponentsByType('GridFieldDeleteAction')
130
                        ->removeComponentsByType('GridFieldDetailForm')
131
                        ->addComponent(new ElementalGridFieldDeleteAction());
132
133
                $virtual->getConfig()
0 ignored issues
show
Bug introduced by
The method getConfig() does not exist on FormField. Did you maybe mean config()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
134
                    ->getComponentByType('GridFieldDataColumns')
135
                    ->setDisplayFields(array(
136
                        'getPage.Title' => 'Title',
137
                        'getPage.Link' => 'Link'
138
                    ));
139
            }
140
        }
141
142
        $this->extend('updateCMSFields', $fields);
143
144
        if ($this->IsInDB()) {
145
            if ($this->isEndofLine('BaseElement') && $this->hasExtension('VersionViewerDataObject')) {
146
                $fields = $this->addVersionViewer($fields, $this);
0 ignored issues
show
Documentation Bug introduced by
The method addVersionViewer does not exist on object<BaseElement>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
147
            }
148
        }
149
150
        return $fields;
151
    }
152
153
    /**
154
     * Version viewer must only be added at if this is the final getCMSFields for a class.
155
     * in order to avoid having to rename all fields from eg Root.Main to Root.Current.Main
156
     * To do this we test if getCMSFields is from the current class
157
     */
158
    public function isEndofLine($className)
159
    {
160
        $methodFromClass = ClassInfo::has_method_from(
161
            $this->ClassName, 'getCMSFields', $className
162
        );
163
164
        if($methodFromClass) {
165
            return true;
166
        }
167
    }
168
169
170
    public function onBeforeWrite()
171
    {
172
        parent::onBeforeWrite();
173
174
        if (!$this->Sort) {
0 ignored issues
show
Documentation introduced by
The property Sort does not exist on object<BaseElement>. 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...
175
            $parentID = ($this->ParentID) ? $this->ParentID : 0;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<BaseElement>. 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...
176
177
            $this->Sort = DB::query("SELECT MAX(\"Sort\") + 1 FROM \"Widget\" WHERE \"ParentID\" = $parentID")->value();
0 ignored issues
show
Documentation introduced by
The property Sort does not exist on object<BaseElement>. 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...
178
        }
179
180
        if ($this->MoveToListID) {
0 ignored issues
show
Documentation introduced by
The property MoveToListID does not exist on object<BaseElement>. 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...
181
            $this->ListID = $this->MoveToListID;
0 ignored issues
show
Documentation introduced by
The property ListID does not exist on object<BaseElement>. 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...
Documentation introduced by
The property MoveToListID does not exist on object<BaseElement>. 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...
182
        }
183
    }
184
185
    /**
186
     * Ensure that if there are elements that are virtualised from this element
187
     * that we move the original element to replace one of the virtual elements
188
     * But only if it's a delete not an unpublish
189
     */
190
    public function onBeforeDelete() {
191
        parent::onBeforeDelete();
192
193
        if(Versioned::get_reading_mode() == 'Stage.Stage') {
194
            $firstVirtual = false;
195
            $allVirtual = $this->getVirtualLinkedElements();
196
            if ($this->getPublishedVirtualLinkedElements()->Count() > 0) {
197
                // choose the first one
198
                $firstVirtual = $this->getPublishedVirtualLinkedElements()->First();
199
                $wasPublished = true;
200
            } else if ($allVirtual->Count() > 0) {
201
                // choose the first one
202
                $firstVirtual = $this->getVirtualLinkedElements()->First();
203
                $wasPublished = false;
204
            }
205
            if ($firstVirtual) {
206
                $origParentID = $this->ParentID;
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<BaseElement>. 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...
Unused Code introduced by
$origParentID 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...
207
                $origSort = $this->Sort;
0 ignored issues
show
Documentation introduced by
The property Sort does not exist on object<BaseElement>. 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...
Unused Code introduced by
$origSort 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...
208
209
                $clone = $this->duplicate(false);
210
211
                // set clones values to first virtual's values
212
                $clone->ParentID = $firstVirtual->ParentID;
213
                $clone->Sort = $firstVirtual->Sort;
214
215
                $clone->write();
216
                if ($wasPublished) {
0 ignored issues
show
Bug introduced by
The variable $wasPublished 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...
217
                    $clone->doPublish();
218
                    $firstVirtual->doUnpublish();
219
                }
220
221
                // clone has a new ID, so need to repoint
222
                // all the other virtual elements
223
                foreach($allVirtual as $virtual) {
224
                    if ($virtual->ID == $firstVirtual->ID) {
225
                        continue;
226
                    }
227
                    $pub = false;
228
                    if ($virtual->isPublished()) {
229
                        $pub = true;
230
                    }
231
                    $virtual->LinkedElementID = $clone->ID;
232
                    $virtual->write();
233
                    if ($pub) {
234
                        $virtual->doPublish();
235
                    }
236
                }
237
238
                $firstVirtual->delete();
239
            }
240
        }
241
    }
242
243
    /**
244
     * @return string
245
     */
246
    public function i18n_singular_name()
247
    {
248
        return _t(__CLASS__, $this->config()->title);
249
    }
250
251
    /**
252
     * @return string
253
     */
254
    public function getElementType()
255
    {
256
        return $this->i18n_singular_name();
257
    }
258
259
    /**
260
     * @return string
261
     */
262 View Code Duplication
    public function getTitle()
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...
263
    {
264
        if ($title = $this->getField('Title')) {
265
            return $title;
266
        } else {
267
            if (!$this->isInDb()) {
268
                return;
269
            }
270
271
            return $this->config()->title;
272
        }
273
    }
274
275
    /**
276
     * @return string
277
     */
278 View Code Duplication
    public function getCMSTitle()
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...
279
    {
280
        if ($title = $this->getField('Title')) {
281
            return $this->config()->title . ': ' . $title;
282
        } else {
283
            if (!$this->isInDb()) {
284
                return;
285
            }
286
            return $this->config()->title;
287
        }
288
    }
289
290
    public function ControllerTop()
291
    {
292
        return Controller::curr();
293
    }
294
295
    public function getPage()
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...
296
    {
297
        if ($this->virtualOwner) {
298
            return $this->virtualOwner->getPage();
299
        }
300
301
        $area = $this->Parent();
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on BaseElement. Did you maybe mean parentClass()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
302
303
        if ($area instanceof ElementalArea) {
304
            return $area->getOwnerPage();
305
        }
306
307
        return null;
308
    }
309
310
    /**
311
     * Override the {@link Widget::forTemplate()} method so that holders are not rendered twice. The controller should
312
     * render with widget inside the
313
     *
314
     * @return HTML
0 ignored issues
show
Documentation introduced by
Should the return type not be HTMLText?

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...
315
     */
316
    public function forTemplate($holder = true)
317
    {
318
        return $this->renderWith($this->class);
319
    }
320
321
    /**
322
     * @return string
323
     */
324
    public function getEditLink() {
325
        return Controller::join_links(
326
            Director::absoluteBaseURL(),
327
            'admin/elemental/BaseElement/EditForm/field/BaseElement/item',
328
            $this->ID,
329
            'edit'
330
        );
331
    }
332
333
    public function onBeforeVersionedPublish()
334
    {
335
336
    }
337
338
		public static function all_allowed_elements() {
339
        $classes = array();
340
341
        // get all dataobject with the elemental extension
342
        foreach(ClassInfo::subclassesFor('DataObject') as $className) {
0 ignored issues
show
Bug introduced by
The expression \ClassInfo::subclassesFor('DataObject') 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...
343
            if(Object::has_extension($className, 'ElementPageExtension')) {
344
               $classes[] = $className;
345
            }
346
        }
347
348
        // get all allowd_elements for these classes
349
        $allowed = array();
350
        foreach($classes as $className) {
351
            $allowed = array_merge($allowed, Config::inst()->get($className, 'allowed_elements'));
352
        }
353
354
       // $allowed[] = 'ElementVirtualLinked';
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
355
        $allowed = array_unique($allowed);
356
357
        $elements = array();
358
        foreach($allowed as $className) {
359
            $elements[$className] = _t($className, Config::inst()->get($className, 'title'));
360
        }
361
362
        asort($elements);
363
364
        return $elements;
365
    }
366
367
    public function getDefaultSearchContext()
368
    {
369
        $fields = $this->scaffoldSearchFields();
370
371
        $elements = BaseElement::all_allowed_elements();
372
373
        $fields->push(DropdownField::create('ClassName', 'Element Type', $elements)
374
            ->setEmptyString('All types'));
375
        $filters = $this->owner->defaultSearchFilters();
0 ignored issues
show
Documentation introduced by
The property owner does not exist on object<BaseElement>. 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...
376
377
        return new SearchContext(
378
            $this->owner->class,
0 ignored issues
show
Documentation introduced by
The property owner does not exist on object<BaseElement>. 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...
379
            $fields,
380
            $filters
381
        );
382
    }
383
384
    public function setVirtualOwner(ElementVirtualLinked $virtualOwner) {
385
        $this->virtualOwner = $virtualOwner;
386
    }
387
388
    /**
389
     * Finds and returns elements
390
     * that are virtual elements which link to this element
391
     */
392
    public function getVirtualLinkedElements() {
393
        return ElementVirtualLinked::get()->filter('LinkedElementID', $this->ID);
394
    }
395
396
    /**
397
     * Finds and returns published elements
398
     * that are virtual elements which link to this element
399
     */
400
    public function getPublishedVirtualLinkedElements() {
401
        $current = Versioned::get_reading_mode();
402
        Versioned::set_reading_mode('Stage.Live');
403
        $v = $this->getVirtualLinkedElements();
404
        Versioned::set_reading_mode($current);
405
        return $v;
406
    }
407
}
408
409
410