Completed
Pull Request — master (#71)
by John
02:19
created

BaseElement::onBeforeVersionedPublish()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 0
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
        'AvailableGlobally' => 'Boolean(1)'
15
    );
16
17
    /**
18
     * @var array $has_one
19
     */
20
    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...
21
        'List' => 'ElementList' // optional.
22
    );
23
24
    /**
25
     * @var array $has_many
26
     */
27
    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...
28
        'VirtualClones' => 'ElementVirtualLinked'
29
    );
30
31
    /**
32
     * @var string
33
     */
34
    private static $title = 'Content Block';
0 ignored issues
show
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...
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
35
36
    /**
37
     * @var string
38
     */
39
    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...
40
41
    /**
42
     * @var array
43
     */
44
    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...
45
        'ID' => 'ID',
46
        'Title' => 'Title',
47
        'ElementType' => 'Type'
48
    );
49
50
    /**
51
     * @var array
52
     */
53
    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...
54
        'ID' => array(
55
            'field' => 'NumericField'
56
        ),
57
        'Title',
58
        'LastEdited',
59
        'ClassName',
60
        'AvailableGlobally'
61
    );
62
63
    /**
64
     * @var boolean
65
     */
66
    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...
67
68
    /**
69
     * Enable for backwards compatibility
70
     *
71
     * @var boolean
72
     */
73
    private static $disable_pretty_anchor_name = false;
0 ignored issues
show
Unused Code introduced by
The property $disable_pretty_anchor_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...
74
75
    /**
76
     * Store used anchor names, this is to avoid title clashes
77
     * when calling 'getAnchor'
78
     *
79
     * @var array
80
     */
81
    protected static $_used_anchors = array();
82
83
    /**
84
     * For caching 'getAnchor'
85
     *
86
     * @var string
87
     */
88
    protected $_anchor = null;
89
90
    /**
91
     * @var Object
92
     * The virtual owner VirtualLinkedElement
93
     */
94
    public $virtualOwner;
95
96
    /**
97
     * @config
98
     * Elements available globally by default
99
     */
100
     private static $default_global_elements = true;
0 ignored issues
show
Unused Code introduced by
The property $default_global_elements 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...
101
102
     public function populateDefaults() {
103
        $this->AvailableGlobally = $this->config()->get('default_global_elements');
0 ignored issues
show
Documentation introduced by
The property AvailableGlobally 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...
104
        parent::populateDefaults();
105
     }
106
107
    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...
108
    {
109
        $fields = $this->scaffoldFormFields(array(
110
            'includeRelations' => ($this->ID > 0),
111
            'tabbed' => true,
112
            'ajaxSafe' => true
113
        ));
114
115
        $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...
116
        $fields->removeByName('ListID');
117
        $fields->removeByName('ParentID');
118
        $fields->removeByName('Sort');
119
        $fields->removeByName('ExtraClass');
120
        $fields->removeByName('AvailableGlobally');
121
122
        if (!$this->config()->enable_title_in_template) {
123
            $fields->removeByName('HideTitle');
124
            $title = $fields->fieldByName('Root.Main.Title');
125
126
            if ($title) {
127
                $title->setRightTitle('For reference only. Does not appear in the template.');
128
            }
129
        }
130
131
        $fields->addFieldToTab('Root.Settings', new CheckboxField('Enabled'));
132
        $fields->addFieldToTab('Root.Settings', new CheckboxField('AvailableGlobally', 'Available globally - can be linked to multiple pages'));
133
        $fields->addFieldToTab('Root.Settings', new TextField('ExtraClass', 'Extra CSS Classes to add'));
134
135
        if (!is_a($this, 'ElementList')) {
136
            $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...
137
138
            if ($lists->exists()) {
139
                $fields->addFieldToTab('Root.Settings',
140
                    $move = new DropdownField('MoveToListID', 'Move this to another list', $lists->map('ID', 'CMSTitle'), '')
141
                );
142
143
                $move->setEmptyString('Select a list..');
144
                $move->setHasEmptyDefault(true);
145
            }
146
        }
147
148
        if($virtual = $fields->dataFieldByName('VirtualClones')) {
149
            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...
150
                $tab = $fields->findOrMakeTab('Root.VirtualClones');
151
                $tab->setTitle(_t('BaseElement.VIRTUALTABTITLE', 'Linked To'));
152
153
                $ownerPage = $this->Parent()->getOwnerPage();
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...
154
                $tab->push(new LiteralField('DisplaysOnPage', sprintf(
155
                    "<p>The original content block appears on <a href='%s'>%s</a></p>",
156
                    ($ownerPage->hasMethod('CMSEditLink') && $ownerPage->canEdit()) ? $ownerPage->CMSEditLink() : $ownerPage->Link(),
157
                    $ownerPage->MenuTitle
158
                )));
159
160
                $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...
161
                $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...
162
                    ->setTitle(_t('BaseElement.OTHERPAGES', 'Other pages'))
163
                    ->getConfig()
164
                        ->removeComponentsByType('GridFieldAddExistingAutocompleter')
165
                        ->removeComponentsByType('GridFieldAddNewButton')
166
                        ->removeComponentsByType('GridFieldDeleteAction')
167
                        ->removeComponentsByType('GridFieldDetailForm')
168
                        ->addComponent(new ElementalGridFieldDeleteAction());
169
170
                $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...
171
                    ->getComponentByType('GridFieldDataColumns')
172
                    ->setDisplayFields(array(
173
                        'getPage.Title' => 'Title',
174
                        'getPage.Link' => 'Link'
175
                    ));
176
            }
177
        }
178
179
        $this->extend('updateCMSFields', $fields);
180
181
        if ($this->IsInDB()) {
182
            if ($this->isEndofLine('BaseElement') && $this->hasExtension('VersionViewerDataObject')) {
183
                $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...
184
            }
185
        }
186
187
        return $fields;
188
    }
189
190
    /**
191
     * Version viewer must only be added at if this is the final getCMSFields for a class.
192
     * in order to avoid having to rename all fields from eg Root.Main to Root.Current.Main
193
     * To do this we test if getCMSFields is from the current class
194
     */
195
    public function isEndofLine($className)
196
    {
197
        $methodFromClass = ClassInfo::has_method_from(
198
            $this->ClassName, 'getCMSFields', $className
199
        );
200
201
        if($methodFromClass) {
202
            return true;
203
        }
204
    }
205
206
207
    public function onBeforeWrite()
208
    {
209
        parent::onBeforeWrite();
210
211
        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...
212
            $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...
213
214
            $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...
215
        }
216
217
        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...
218
            $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...
219
        }
220
    }
221
222
    /**
223
     * Ensure that if there are elements that are virtualised from this element
224
     * that we move the original element to replace one of the virtual elements
225
     * But only if it's a delete not an unpublish
226
     */
227
    public function onBeforeDelete() {
228
        parent::onBeforeDelete();
229
230
        if(Versioned::get_reading_mode() == 'Stage.Stage') {
231
            $firstVirtual = false;
232
            $allVirtual = $this->getVirtualLinkedElements();
233
            if ($this->getPublishedVirtualLinkedElements()->Count() > 0) {
234
                // choose the first one
235
                $firstVirtual = $this->getPublishedVirtualLinkedElements()->First();
236
                $wasPublished = true;
237
            } else if ($allVirtual->Count() > 0) {
238
                // choose the first one
239
                $firstVirtual = $this->getVirtualLinkedElements()->First();
240
                $wasPublished = false;
241
            }
242
            if ($firstVirtual) {
243
                $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...
244
                $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...
245
246
                $clone = $this->duplicate(false);
247
248
                // set clones values to first virtual's values
249
                $clone->ParentID = $firstVirtual->ParentID;
250
                $clone->Sort = $firstVirtual->Sort;
251
252
                $clone->write();
253
                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...
254
                    $clone->doPublish();
255
                    $firstVirtual->doUnpublish();
256
                }
257
258
                // clone has a new ID, so need to repoint
259
                // all the other virtual elements
260
                foreach($allVirtual as $virtual) {
261
                    if ($virtual->ID == $firstVirtual->ID) {
262
                        continue;
263
                    }
264
                    $pub = false;
265
                    if ($virtual->isPublished()) {
266
                        $pub = true;
267
                    }
268
                    $virtual->LinkedElementID = $clone->ID;
269
                    $virtual->write();
270
                    if ($pub) {
271
                        $virtual->doPublish();
272
                    }
273
                }
274
275
                $firstVirtual->delete();
276
            }
277
        }
278
    }
279
280
    /**
281
     * @return string
282
     */
283
    public function i18n_singular_name()
284
    {
285
        return _t(__CLASS__, $this->config()->title);
286
    }
287
288
    /**
289
     * @return string
290
     */
291
    public function getElementType()
292
    {
293
        return $this->i18n_singular_name();
294
    }
295
296
    /**
297
     * @return string
298
     */
299 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...
300
    {
301
        if ($title = $this->getField('Title')) {
302
            return $title;
303
        } else {
304
            if (!$this->isInDb()) {
305
                return;
306
            }
307
308
            return $this->config()->title;
309
        }
310
    }
311
312
    /**
313
     * Get a unique anchor name
314
     *
315
     * @return string
316
     */
317
    public function getAnchor() {
318
        if ($this->_anchor !== null) {
319
            return $this->_anchor;
320
        }
321
322
        $anchorTitle = '';
323
        if (!$this->config()->disable_pretty_anchor_name) {
324
            if ($this->hasMethod('getAnchorTitle')) {
325
                $anchorTitle = $this->getAnchorTitle();
0 ignored issues
show
Documentation Bug introduced by
The method getAnchorTitle 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...
326
            } else if ($this->config()->enable_title_in_template) {
327
                $anchorTitle = $this->getField('Title');
328
            }
329
        }
330
        if (!$anchorTitle) {
331
            $anchorTitle = 'e'.$this->ID;
332
        }
333
334
        $filter = URLSegmentFilter::create();
335
        $titleAsURL = $filter->filter($anchorTitle);
336
337
        // Ensure that this anchor name isn't already in use
338
        // ie. If two elemental blocks have the same title, it'll append '-2', '-3'
339
        $result = $titleAsURL;
340
        $count = 1;
341
        while (isset(self::$_used_anchors[$result]) && self::$_used_anchors[$result] !== $this->ID) {
342
            ++$count;
343
            $result = $titleAsURL.'-'.$count;
344
        }
345
        self::$_used_anchors[$result] = $this->ID;
346
        return $this->_anchor = $result;
347
    }
348
349
    /**
350
     * @return string
351
     */
352 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...
353
    {
354
        if ($title = $this->getField('Title')) {
355
            return $this->config()->title . ': ' . $title;
356
        } else {
357
            if (!$this->isInDb()) {
358
                return;
359
            }
360
            return $this->config()->title;
361
        }
362
    }
363
364
    public function ControllerTop()
365
    {
366
        return Controller::curr();
367
    }
368
369
    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...
370
    {
371
        if ($this->virtualOwner) {
372
            return $this->virtualOwner->getPage();
373
        }
374
375
        if ($this->ListID) {
0 ignored issues
show
Documentation introduced by
The property ListID 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
            return $this->List()->getPage();
0 ignored issues
show
Documentation Bug introduced by
The method List 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...
377
        }
378
379
        $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...
380
381
        if ($area instanceof ElementalArea) {
382
            return $area->getOwnerPage();
383
        }
384
385
        return null;
386
    }
387
388
    /**
389
     * Override the {@link Widget::forTemplate()} method so that holders are not rendered twice. The controller should
390
     * render with widget inside the
391
     *
392
     * @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...
393
     */
394
    public function forTemplate($holder = true)
395
    {
396
        $config = SiteConfig::current_site_config();
397
398
        if ($config->Theme) Config::inst()->update('SSViewer', 'theme', $config->Theme);
399
400
        return $this->renderWith($this->class);
401
    }
402
403
    /**
404
     * @return string
405
     */
406
    public function getEditLink() {
407
        return $this->CMSEditLink();
408
    }
409
410
    /**
411
     * @return string
412
     */
413
    public function CMSEditLink($inList = false) {
414
        if ($this->ListID) {
0 ignored issues
show
Documentation introduced by
The property ListID 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...
415
            if ($parentLink = $this->List()->CMSEditLink(true)) {
0 ignored issues
show
Documentation Bug introduced by
The method List 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...
416
                return Controller::join_links(
417
                    $parentLink,
418
                    'ItemEditForm/field/Elements/item/',
419
                    $this->ID,
420
                    'edit'
421
                );
422
            }
423
        }
424
        if (!$this->getPage()) {
425
            return Controller::join_links(
426
                Director::absoluteBaseURL(),
427
                'admin/elemental/BaseElement/EditForm/field/BaseElement/item',
428
                $this->ID,
429
                'edit'
430
            );
431
        }
432
        $link = Controller::join_links(
433
            singleton('CMSPageEditController')->Link('EditForm'),
434
            $this->getPage()->ID,
435
            'field/ElementArea/item/',
436
            $this->ID
437
        );
438
        if ($inList) {
439
            return $link;
440
        }
441
        return Controller::join_links(
442
            $link,
443
            'edit'
444
        );
445
    }
446
447
    public function UsedOn() {
448
        if ($page = $this->getPage()) {
449
            $html = new HTMLText('UsedOn');
450
            $html->setValue('<a href="' . $page->CMSEditLink() . '">' . $page->Title . '</a>');
451
            return $html;
452
        }
453
    }
454
455
    public static function all_allowed_elements() {
456
        $classes = array();
457
458
        // get all dataobject with the elemental extension
459
        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...
460
            if(Object::has_extension($className, 'ElementPageExtension')) {
461
               $classes[] = $className;
462
            }
463
        }
464
465
        // get all allowd_elements for these classes
466
        $allowed = array();
467
        foreach($classes as $className) {
468
            $allowed_elements = Config::inst()->get($className, 'allowed_elements');
469
            if ($allowed_elements) {
470
                $allowed = array_merge($allowed, $allowed_elements);
471
            }
472
        }
473
474
       // $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...
475
        $allowed = array_unique($allowed);
476
477
        $elements = array();
478
        foreach($allowed as $className) {
479
            $elements[$className] = _t($className, Config::inst()->get($className, 'title'));
480
        }
481
482
        asort($elements);
483
484
        return $elements;
485
    }
486
487
    public function getDefaultSearchContext()
488
    {
489
        $fields = $this->scaffoldSearchFields();
490
491
        $elements = BaseElement::all_allowed_elements();
492
493
        $fields->push(DropdownField::create('ClassName', 'Element Type', $elements)
494
            ->setEmptyString('All types'));
495
        $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...
496
497
        return new SearchContext(
498
            $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...
499
            $fields,
500
            $filters
501
        );
502
    }
503
504
    public function setVirtualOwner(ElementVirtualLinked $virtualOwner) {
505
        $this->virtualOwner = $virtualOwner;
506
    }
507
508
    /**
509
     * Finds and returns elements
510
     * that are virtual elements which link to this element
511
     */
512
    public function getVirtualLinkedElements() {
513
        return ElementVirtualLinked::get()->filter('LinkedElementID', $this->ID);
514
    }
515
516
    /**
517
     * Finds and returns published elements
518
     * that are virtual elements which link to this element
519
     */
520
    public function getPublishedVirtualLinkedElements() {
521
        $current = Versioned::get_reading_mode();
522
        Versioned::set_reading_mode('Stage.Live');
523
        $v = $this->getVirtualLinkedElements();
524
        Versioned::set_reading_mode($current);
525
        return $v;
526
    }
527
}
528