Completed
Push — master ( 5cca73...7a2a08 )
by John
10s
created

BaseElement::onBeforeVersionedPublish()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

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

namespace YourVendor;

class YourClass { }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Loading history...
65
66
    /**
67
     * @var Object
68
     * The virtual owner VirtualLinkedElement
69
     */
70
    public $virtualOwner;
71
72
73
    public function getCMSFields()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
74
    {
75
        $fields = $this->scaffoldFormFields(array(
76
            'includeRelations' => ($this->ID > 0),
77
            'tabbed' => true,
78
            'ajaxSafe' => true
79
        ));
80
81
        $fields->insertAfter(new ReadonlyField('ClassNameTranslated', _t('BaseElement.TYPE', 'Type'), $this->i18n_singular_name()), 'Title');
0 ignored issues
show
Documentation introduced by
'Title' is of type string, but the function expects a object<FormField>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
82
        $fields->removeByName('ListID');
83
        $fields->removeByName('ParentID');
84
        $fields->removeByName('Sort');
85
        $fields->removeByName('ExtraClass');
86
87
        if (!$this->config()->enable_title_in_template) {
88
            $fields->removeByName('HideTitle');
89
            $title = $fields->fieldByName('Root.Main.Title');
90
91
            if ($title) {
92
                $title->setRightTitle('For reference only. Does not appear in the template.');
93
            }
94
        }
95
96
        $fields->addFieldToTab('Root.Settings', new TextField('ExtraClass', 'Extra CSS Classes to add'));
97
98
        if (!is_a($this, 'ElementList')) {
99
            $lists = ElementList::get()->filter('ParentID', $this->ParentID);
0 ignored issues
show
Documentation introduced by
The property ParentID does not exist on object<BaseElement>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
100
101
            if ($lists->exists()) {
102
                $fields->addFieldToTab('Root.Settings',
103
                    $move = new DropdownField('MoveToListID', 'Move this to another list', $lists->map('ID', 'CMSTitle'), '')
104
                );
105
106
                $move->setEmptyString('Select a list..');
107
                $move->setHasEmptyDefault(true);
108
            }
109
        }
110
111
112
        if($virtual = $fields->dataFieldByName('VirtualClones')) {
113
            if($this->Parent() && $this->Parent()->exists() && $this->Parent()->getOwnerPage() && $this->Parent()->getOwnerPage()->exists()) {
0 ignored issues
show
Bug introduced by
The method Parent() does not exist on BaseElement. Did you maybe mean parentClass()?

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

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

Loading history...
114
                $tab = $fields->findOrMakeTab('Root.VirtualClones');
115
                $tab->setTitle(_t('BaseElement.VIRTUALTABTITLE', 'Linked To'));
116
117
                $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...
118
                $tab->push(new LiteralField('DisplaysOnPage', sprintf(
119
                    "<p>The original content block appears on <a href='%s'>%s</a></p>",
120
                    ($ownerPage->hasMethod('CMSEditLink') && $ownerPage->canEdit()) ? $ownerPage->CMSEditLink() : $ownerPage->Link(),
121
                    $ownerPage->MenuTitle
122
                )));
123
124
                $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...
125
                $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...
126
                    ->setTitle(_t('BaseElement.OTHERPAGES', 'Other pages'))
127
                    ->getConfig()
128
                        ->removeComponentsByType('GridFieldAddExistingAutocompleter')
129
                        ->removeComponentsByType('GridFieldAddNewButton')
130
                        ->removeComponentsByType('GridFieldDeleteAction')
131
                        ->removeComponentsByType('GridFieldDetailForm')
132
                        ->addComponent(new ElementalGridFieldDeleteAction());
133
134
                $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...
135
                    ->getComponentByType('GridFieldDataColumns')
136
                    ->setDisplayFields(array(
137
                        'getPage.Title' => 'Title',
138
                        'getPage.Link' => 'Link'
139
                    ));
140
            }
141
        }
142
143
        $this->extend('updateCMSFields', $fields);
144
145
        if ($this->IsInDB()) {
146
            if ($this->isEndofLine('BaseElement') && $this->hasExtension('VersionViewerDataObject')) {
147
                $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...
148
            }
149
        }
150
151
        return $fields;
152
    }
153
154
    /**
155
     * Version viewer must only be added at if this is the final getCMSFields for a class.
156
     * in order to avoid having to rename all fields from eg Root.Main to Root.Current.Main
157
     * To do this we test if getCMSFields is from the current class
158
     */
159
    public function isEndofLine($className)
160
    {
161
        $methodFromClass = ClassInfo::has_method_from(
162
            $this->ClassName, 'getCMSFields', $className
163
        );
164
165
        if($methodFromClass) {
166
            return true;
167
        }
168
    }
169
170
171
    public function onBeforeWrite()
172
    {
173
        parent::onBeforeWrite();
174
175
        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...
176
            $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...
177
178
            $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...
179
        }
180
181
        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...
182
            $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...
183
        }
184
    }
185
186
    /**
187
     * Ensure that if there are elements that are virtualised from this element
188
     * that we move the original element to replace one of the virtual elements
189
     * But only if it's a delete not an unpublish
190
     */
191
    public function onBeforeDelete() {
192
        parent::onBeforeDelete();
193
194
        if(Versioned::get_reading_mode() == 'Stage.Stage') {
195
            $firstVirtual = false;
196
            $allVirtual = $this->getVirtualLinkedElements();
197
            if ($this->getPublishedVirtualLinkedElements()->Count() > 0) {
198
                // choose the first one
199
                $firstVirtual = $this->getPublishedVirtualLinkedElements()->First();
200
                $wasPublished = true;
201
            } else if ($allVirtual->Count() > 0) {
202
                // choose the first one
203
                $firstVirtual = $this->getVirtualLinkedElements()->First();
204
                $wasPublished = false;
205
            }
206
            if ($firstVirtual) {
207
                $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...
208
                $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...
209
210
                $clone = $this->duplicate(false);
211
212
                // set clones values to first virtual's values
213
                $clone->ParentID = $firstVirtual->ParentID;
214
                $clone->Sort = $firstVirtual->Sort;
215
216
                $clone->write();
217
                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...
218
                    $clone->doPublish();
219
                    $firstVirtual->doUnpublish();
220
                }
221
222
                // clone has a new ID, so need to repoint
223
                // all the other virtual elements
224
                foreach($allVirtual as $virtual) {
225
                    if ($virtual->ID == $firstVirtual->ID) {
226
                        continue;
227
                    }
228
                    $pub = false;
229
                    if ($virtual->isPublished()) {
230
                        $pub = true;
231
                    }
232
                    $virtual->LinkedElementID = $clone->ID;
233
                    $virtual->write();
234
                    if ($pub) {
235
                        $virtual->doPublish();
236
                    }
237
                }
238
239
                $firstVirtual->delete();
240
            }
241
        }
242
    }
243
244
    /**
245
     * @return string
246
     */
247
    public function i18n_singular_name()
248
    {
249
        return _t(__CLASS__, $this->config()->title);
250
    }
251
252
    /**
253
     * @return string
254
     */
255
    public function getElementType()
256
    {
257
        return $this->i18n_singular_name();
258
    }
259
260
    /**
261
     * @return string
262
     */
263 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...
264
    {
265
        if ($title = $this->getField('Title')) {
266
            return $title;
267
        } else {
268
            if (!$this->isInDb()) {
269
                return;
270
            }
271
272
            return $this->config()->title;
273
        }
274
    }
275
276
    /**
277
     * @return string
278
     */
279 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...
280
    {
281
        if ($title = $this->getField('Title')) {
282
            return $this->config()->title . ': ' . $title;
283
        } else {
284
            if (!$this->isInDb()) {
285
                return;
286
            }
287
            return $this->config()->title;
288
        }
289
    }
290
291
    public function ControllerTop()
292
    {
293
        return Controller::curr();
294
    }
295
296
    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...
297
    {
298
        if ($this->virtualOwner) {
299
            return $this->virtualOwner->getPage();
300
        }
301
302
        $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...
303
304
        if ($area instanceof ElementalArea) {
305
            return $area->getOwnerPage();
306
        }
307
308
        return null;
309
    }
310
311
    /**
312
     * Override the {@link Widget::forTemplate()} method so that holders are not rendered twice. The controller should
313
     * render with widget inside the
314
     *
315
     * @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...
316
     */
317
    public function forTemplate($holder = true)
318
    {
319
        return $this->renderWith($this->class);
320
    }
321
322
    /**
323
     * @return string
324
     */
325
    public function getEditLink() {
326
        return Controller::join_links(
327
            Director::absoluteBaseURL(),
328
            'admin/elemental/BaseElement/EditForm/field/BaseElement/item',
329
            $this->ID,
330
            'edit'
331
        );
332
    }
333
334
    public function onBeforeVersionedPublish()
335
    {
336
337
    }
338
339
		public static function all_allowed_elements() {
340
        $classes = array();
341
342
        // get all dataobject with the elemental extension
343
        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...
344
            if(Object::has_extension($className, 'ElementPageExtension')) {
345
               $classes[] = $className;
346
            }
347
        }
348
349
        // get all allowd_elements for these classes
350
        $allowed = array();
351
        foreach($classes as $className) {
352
            $allowed_elements = Config::inst()->get($className, 'allowed_elements');
353
            if ($allowed_elements) {
354
                $allowed = array_merge($allowed, $allowed_elements);
355
            }
356
        }
357
358
       // $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...
359
        $allowed = array_unique($allowed);
360
361
        $elements = array();
362
        foreach($allowed as $className) {
363
            $elements[$className] = _t($className, Config::inst()->get($className, 'title'));
364
        }
365
366
        asort($elements);
367
368
        return $elements;
369
    }
370
371
    public function getDefaultSearchContext()
372
    {
373
        $fields = $this->scaffoldSearchFields();
374
375
        $elements = BaseElement::all_allowed_elements();
376
377
        $fields->push(DropdownField::create('ClassName', 'Element Type', $elements)
378
            ->setEmptyString('All types'));
379
        $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...
380
381
        return new SearchContext(
382
            $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...
383
            $fields,
384
            $filters
385
        );
386
    }
387
388
    public function setVirtualOwner(ElementVirtualLinked $virtualOwner) {
389
        $this->virtualOwner = $virtualOwner;
390
    }
391
392
    /**
393
     * Finds and returns elements
394
     * that are virtual elements which link to this element
395
     */
396
    public function getVirtualLinkedElements() {
397
        return ElementVirtualLinked::get()->filter('LinkedElementID', $this->ID);
398
    }
399
400
    /**
401
     * Finds and returns published elements
402
     * that are virtual elements which link to this element
403
     */
404
    public function getPublishedVirtualLinkedElements() {
405
        $current = Versioned::get_reading_mode();
406
        Versioned::set_reading_mode('Stage.Live');
407
        $v = $this->getVirtualLinkedElements();
408
        Versioned::set_reading_mode($current);
409
        return $v;
410
    }
411
}
412
413
414