Completed
Push — master ( b65f29...9b4aae )
by Will
9s
created

BaseElement::getPublishedVirtualLinkedElements()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 0
1
<?php
2
3
/**
4
 * @package elemental
5
 */
6
class BaseElement extends Widget
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
7
{
8
    /**
9
     * @var array $db
10
     */
11
    private static $db = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $db is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
12
        'ExtraClass' => 'Varchar(255)',
13
        'HideTitle' => 'Boolean'
14
    );
15
16
    /**
17
     * @var array $has_one
18
     */
19
    private static $has_one = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $has_one is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
20
        'List' => 'ElementList' // optional.
21
    );
22
23
    /**
24
     * @var array $has_many
25
     */
26
    private static $has_many = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $has_many is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
27
        'VirtualClones' => 'ElementVirtualLinked'
28
    );
29
30
    /**
31
     * @var string
32
     */
33
    private static $title = "Content Block";
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $title is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
34
35
    /**
36
     * @var string
37
     */
38
    private static $singular_name = 'Content Block';
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $singular_name is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
39
40
    /**
41
     * @var array
42
     */
43
    private static $summary_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $summary_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
44
        'ID' => 'ID',
45
        'Title' => 'Title',
46
        'ElementType' => 'Type'
47
    );
48
49
    /**
50
     * @var array
51
     */
52
    private static $searchable_fields = array(
0 ignored issues
show
Comprehensibility introduced by
Consider using a different property name as you override a private property of the parent class.
Loading history...
Unused Code introduced by
The property $searchable_fields is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
53
        'ID' => array(
54
            'field' => 'NumericField'
55
        ),
56
        'Title',
57
        'LastEdited',
58
        'ClassName'
59
    );
60
61
    /**
62
     * @var boolean
63
     */
64
    private static $enable_title_in_template = false;
0 ignored issues
show
Unused Code introduced by
The property $enable_title_in_template is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

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