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