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

BaseElement::CMSEditLink()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 33
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.439
c 0
b 0
f 0
cc 5
eloc 24
nc 7
nop 1
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
151
                if ($this->VirtualClones()->Count() > 0) {
0 ignored issues
show
Documentation Bug introduced by
The method VirtualClones 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...
152
                    $tab = $fields->findOrMakeTab('Root.VirtualClones');
153
                    $tab->setTitle(_t('BaseElement.VIRTUALTABTITLE', 'Linked To'));
154
155
                    $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...
156
                    $tab->push(new LiteralField('DisplaysOnPage', sprintf(
157
                        "<p>The original content block appears on <a href='%s'>%s</a></p>",
158
                        ($ownerPage->hasMethod('CMSEditLink') && $ownerPage->canEdit()) ? $ownerPage->CMSEditLink() : $ownerPage->Link(),
159
                        $ownerPage->MenuTitle
160
                    )));
161
162
                    $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...
163
                    $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...
164
                        ->setTitle(_t('BaseElement.OTHERPAGES', 'Other pages'))
165
                        ->getConfig()
166
                            ->removeComponentsByType('GridFieldAddExistingAutocompleter')
167
                            ->removeComponentsByType('GridFieldAddNewButton')
168
                            ->removeComponentsByType('GridFieldDeleteAction')
169
                            ->removeComponentsByType('GridFieldDetailForm')
170
                            ->addComponent(new ElementalGridFieldDeleteAction());
171
172
                    $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...
173
                        ->getComponentByType('GridFieldDataColumns')
174
                        ->setDisplayFields(array(
175
                            'getPage.Title' => 'Title',
176
                            'getPage.Link' => 'Link'
177
                        ));
178
                } else {
179
                    $fields->removeByName('VirtualClones');
180
                }
181
            }
182
        }
183
184
        $this->extend('updateCMSFields', $fields);
185
186
        if ($this->IsInDB()) {
187
            if ($this->isEndofLine('BaseElement') && $this->hasExtension('VersionViewerDataObject')) {
188
                $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...
189
            }
190
        }
191
192
        return $fields;
193
    }
194
195
    /**
196
     * Version viewer must only be added at if this is the final getCMSFields for a class.
197
     * in order to avoid having to rename all fields from eg Root.Main to Root.Current.Main
198
     * To do this we test if getCMSFields is from the current class
199
     */
200
    public function isEndofLine($className)
201
    {
202
        $methodFromClass = ClassInfo::has_method_from(
203
            $this->ClassName, 'getCMSFields', $className
204
        );
205
206
        if($methodFromClass) {
207
            return true;
208
        }
209
    }
210
211
212
    public function onBeforeWrite()
213
    {
214
        parent::onBeforeWrite();
215
216
        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...
217
            $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...
218
219
            $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...
220
        }
221
222
        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...
223
            $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...
224
        }
225
    }
226
227
    /**
228
     * Ensure that if there are elements that are virtualised from this element
229
     * that we move the original element to replace one of the virtual elements
230
     * But only if it's a delete not an unpublish
231
     */
232
    public function onBeforeDelete() {
233
        parent::onBeforeDelete();
234
235
        if(Versioned::get_reading_mode() == 'Stage.Stage') {
236
            $firstVirtual = false;
237
            $allVirtual = $this->getVirtualLinkedElements();
238
            if ($this->getPublishedVirtualLinkedElements()->Count() > 0) {
239
                // choose the first one
240
                $firstVirtual = $this->getPublishedVirtualLinkedElements()->First();
241
                $wasPublished = true;
242
            } else if ($allVirtual->Count() > 0) {
243
                // choose the first one
244
                $firstVirtual = $this->getVirtualLinkedElements()->First();
245
                $wasPublished = false;
246
            }
247
            if ($firstVirtual) {
248
                $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...
249
                $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...
250
251
                $clone = $this->duplicate(false);
252
253
                // set clones values to first virtual's values
254
                $clone->ParentID = $firstVirtual->ParentID;
255
                $clone->Sort = $firstVirtual->Sort;
256
257
                $clone->write();
258
                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...
259
                    $clone->doPublish();
260
                    $firstVirtual->doUnpublish();
261
                }
262
263
                // clone has a new ID, so need to repoint
264
                // all the other virtual elements
265
                foreach($allVirtual as $virtual) {
266
                    if ($virtual->ID == $firstVirtual->ID) {
267
                        continue;
268
                    }
269
                    $pub = false;
270
                    if ($virtual->isPublished()) {
271
                        $pub = true;
272
                    }
273
                    $virtual->LinkedElementID = $clone->ID;
274
                    $virtual->write();
275
                    if ($pub) {
276
                        $virtual->doPublish();
277
                    }
278
                }
279
280
                $firstVirtual->delete();
281
            }
282
        }
283
    }
284
285
    /**
286
     * @return string
287
     */
288
    public function i18n_singular_name()
289
    {
290
        return _t(__CLASS__, $this->config()->title);
291
    }
292
293
    /**
294
     * @return string
295
     */
296
    public function getElementType()
297
    {
298
        return $this->i18n_singular_name();
299
    }
300
301
    /**
302
     * @return string
303
     */
304 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...
305
    {
306
        if ($title = $this->getField('Title')) {
307
            return $title;
308
        } else {
309
            if (!$this->isInDb()) {
310
                return;
311
            }
312
313
            return $this->config()->title;
314
        }
315
    }
316
317
    /**
318
     * Get a unique anchor name
319
     *
320
     * @return string
321
     */
322
    public function getAnchor() {
323
        if ($this->_anchor !== null) {
324
            return $this->_anchor;
325
        }
326
327
        $anchorTitle = '';
328
        if (!$this->config()->disable_pretty_anchor_name) {
329
            if ($this->hasMethod('getAnchorTitle')) {
330
                $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...
331
            } else if ($this->config()->enable_title_in_template) {
332
                $anchorTitle = $this->getField('Title');
333
            }
334
        }
335
        if (!$anchorTitle) {
336
            $anchorTitle = 'e'.$this->ID;
337
        }
338
339
        $filter = URLSegmentFilter::create();
340
        $titleAsURL = $filter->filter($anchorTitle);
341
342
        // Ensure that this anchor name isn't already in use
343
        // ie. If two elemental blocks have the same title, it'll append '-2', '-3'
344
        $result = $titleAsURL;
345
        $count = 1;
346
        while (isset(self::$_used_anchors[$result]) && self::$_used_anchors[$result] !== $this->ID) {
347
            ++$count;
348
            $result = $titleAsURL.'-'.$count;
349
        }
350
        self::$_used_anchors[$result] = $this->ID;
351
        return $this->_anchor = $result;
352
    }
353
354
    /**
355
     * @return string
356
     */
357 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...
358
    {
359
        if ($title = $this->getField('Title')) {
360
            return $this->config()->title . ': ' . $title;
361
        } else {
362
            if (!$this->isInDb()) {
363
                return;
364
            }
365
            return $this->config()->title;
366
        }
367
    }
368
369
    public function ControllerTop()
370
    {
371
        return Controller::curr();
372
    }
373
374
    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...
375
    {
376
        if ($this->virtualOwner) {
377
            return $this->virtualOwner->getPage();
378
        }
379
380
        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...
381
            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...
382
        }
383
384
        $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...
385
386
        if ($area instanceof ElementalArea) {
387
            return $area->getOwnerPage();
388
        }
389
390
        return null;
391
    }
392
393
    /**
394
     * Override the {@link Widget::forTemplate()} method so that holders are not rendered twice. The controller should
395
     * render with widget inside the
396
     *
397
     * @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...
398
     */
399
    public function forTemplate($holder = true)
400
    {
401
        $config = SiteConfig::current_site_config();
402
403
        if ($config->Theme) Config::inst()->update('SSViewer', 'theme', $config->Theme);
404
405
        return $this->renderWith($this->class);
406
    }
407
408
    /**
409
     * @return string
410
     */
411
    public function getEditLink() {
412
        return $this->CMSEditLink();
413
    }
414
415
    /**
416
     * @return string
417
     */
418
    public function CMSEditLink($inList = false) {
419
        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...
420
            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...
421
                return Controller::join_links(
422
                    $parentLink,
423
                    'ItemEditForm/field/Elements/item/',
424
                    $this->ID,
425
                    'edit'
426
                );
427
            }
428
        }
429
        if (!$this->getPage()) {
430
            return Controller::join_links(
431
                Director::absoluteBaseURL(),
432
                'admin/elemental/BaseElement/EditForm/field/BaseElement/item',
433
                $this->ID,
434
                'edit'
435
            );
436
        }
437
        $link = Controller::join_links(
438
            singleton('CMSPageEditController')->Link('EditForm'),
439
            $this->getPage()->ID,
440
            'field/ElementArea/item/',
441
            $this->ID
442
        );
443
        if ($inList) {
444
            return $link;
445
        }
446
        return Controller::join_links(
447
            $link,
448
            'edit'
449
        );
450
    }
451
452
    public function UsedOn() {
453
        if ($page = $this->getPage()) {
454
            $html = new HTMLText('UsedOn');
455
            $html->setValue('<a href="' . $page->CMSEditLink() . '">' . $page->Title . '</a>');
456
            return $html;
457
        }
458
    }
459
460
    public static function all_allowed_elements() {
461
        $classes = array();
462
463
        // get all dataobject with the elemental extension
464
        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...
465
            if(Object::has_extension($className, 'ElementPageExtension')) {
466
               $classes[] = $className;
467
            }
468
        }
469
470
        // get all allowd_elements for these classes
471
        $allowed = array();
472
        foreach($classes as $className) {
473
            $allowed_elements = Config::inst()->get($className, 'allowed_elements');
474
            if ($allowed_elements) {
475
                $allowed = array_merge($allowed, $allowed_elements);
476
            }
477
        }
478
479
       // $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...
480
        $allowed = array_unique($allowed);
481
482
        $elements = array();
483
        foreach($allowed as $className) {
484
            $elements[$className] = _t($className, Config::inst()->get($className, 'title'));
485
        }
486
487
        asort($elements);
488
489
        return $elements;
490
    }
491
492
    public function getDefaultSearchContext()
493
    {
494
        $fields = $this->scaffoldSearchFields();
495
496
        $elements = BaseElement::all_allowed_elements();
497
498
        $fields->push(DropdownField::create('ClassName', 'Element Type', $elements)
499
            ->setEmptyString('All types'));
500
        $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...
501
502
        return new SearchContext(
503
            $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...
504
            $fields,
505
            $filters
506
        );
507
    }
508
509
    public function setVirtualOwner(ElementVirtualLinked $virtualOwner) {
510
        $this->virtualOwner = $virtualOwner;
511
    }
512
513
    /**
514
     * Finds and returns elements
515
     * that are virtual elements which link to this element
516
     */
517
    public function getVirtualLinkedElements() {
518
        return ElementVirtualLinked::get()->filter('LinkedElementID', $this->ID);
519
    }
520
521
    /**
522
     * Finds and returns published elements
523
     * that are virtual elements which link to this element
524
     */
525
    public function getPublishedVirtualLinkedElements() {
526
        $current = Versioned::get_reading_mode();
527
        Versioned::set_reading_mode('Stage.Live');
528
        $v = $this->getVirtualLinkedElements();
529
        Versioned::set_reading_mode($current);
530
        return $v;
531
    }
532
}
533