Completed
Pull Request — master (#71)
by John
01:50
created

BaseElement::getDefaultSearchContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
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
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
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
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...
35
36
    /**
37
     * @var string
38
     */
39
    private static $singular_name = 'Content Block';
0 ignored issues
show
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
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
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');
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');
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);
137
138
            if ($lists->exists()) {
139
                $fields->addFieldToTab('Root.Settings',
140
                    $move = new DropdownField('MoveToListID', 'Move this to another list', $lists->map('ID', 'CMSTitle'), '')
141
                );
142
143
                $move->setEmptyString('Select a list..');
144
                $move->setHasEmptyDefault(true);
145
            }
146
        }
147
148
        if($virtual = $fields->dataFieldByName('VirtualClones')) {
149
            if($this->Parent() && $this->Parent()->exists() && $this->Parent()->getOwnerPage() && $this->Parent()->getOwnerPage()->exists()) {
150
                $tab = $fields->findOrMakeTab('Root.VirtualClones');
151
                $tab->setTitle(_t('BaseElement.VIRTUALTABTITLE', 'Linked To'));
152
153
                $ownerPage = $this->Parent()->getOwnerPage();
154
                $tab->push(new LiteralField('DisplaysOnPage', sprintf(
155
                    "<p>The original content block appears on <a href='%s'>%s</a></p>",
156
                    ($ownerPage->hasMethod('CMSEditLink') && $ownerPage->canEdit()) ? $ownerPage->CMSEditLink() : $ownerPage->Link(),
157
                    $ownerPage->MenuTitle
158
                )));
159
160
                $virtual->setConfig(new GridFieldConfig_Base());
161
                $virtual
162
                    ->setTitle(_t('BaseElement.OTHERPAGES', 'Other pages'))
163
                    ->getConfig()
164
                        ->removeComponentsByType('GridFieldAddExistingAutocompleter')
165
                        ->removeComponentsByType('GridFieldAddNewButton')
166
                        ->removeComponentsByType('GridFieldDeleteAction')
167
                        ->removeComponentsByType('GridFieldDetailForm')
168
                        ->addComponent(new ElementalGridFieldDeleteAction());
169
170
                $virtual->getConfig()
171
                    ->getComponentByType('GridFieldDataColumns')
172
                    ->setDisplayFields(array(
173
                        'getPage.Title' => 'Title',
174
                        'getPage.Link' => 'Link'
175
                    ));
176
            }
177
        }
178
179
        $this->extend('updateCMSFields', $fields);
180
181
        if ($this->IsInDB()) {
182
            if ($this->isEndofLine('BaseElement') && $this->hasExtension('VersionViewerDataObject')) {
183
                $fields = $this->addVersionViewer($fields, $this);
184
            }
185
        }
186
187
        return $fields;
188
    }
189
190
    /**
191
     * Version viewer must only be added at if this is the final getCMSFields for a class.
192
     * in order to avoid having to rename all fields from eg Root.Main to Root.Current.Main
193
     * To do this we test if getCMSFields is from the current class
194
     */
195
    public function isEndofLine($className)
196
    {
197
        $methodFromClass = ClassInfo::has_method_from(
198
            $this->ClassName, 'getCMSFields', $className
199
        );
200
201
        if($methodFromClass) {
202
            return true;
203
        }
204
    }
205
206
207
    public function onBeforeWrite()
208
    {
209
        parent::onBeforeWrite();
210
211
        if (!$this->Sort) {
212
            $parentID = ($this->ParentID) ? $this->ParentID : 0;
213
214
            $this->Sort = DB::query("SELECT MAX(\"Sort\") + 1 FROM \"Widget\" WHERE \"ParentID\" = $parentID")->value();
215
        }
216
217
        if ($this->MoveToListID) {
218
            $this->ListID = $this->MoveToListID;
219
        }
220
    }
221
222
    /**
223
     * Ensure that if there are elements that are virtualised from this element
224
     * that we move the original element to replace one of the virtual elements
225
     * But only if it's a delete not an unpublish
226
     */
227
    public function onBeforeDelete() {
228
        parent::onBeforeDelete();
229
230
        if(Versioned::get_reading_mode() == 'Stage.Stage') {
231
            $firstVirtual = false;
232
            $allVirtual = $this->getVirtualLinkedElements();
233
            if ($this->getPublishedVirtualLinkedElements()->Count() > 0) {
234
                // choose the first one
235
                $firstVirtual = $this->getPublishedVirtualLinkedElements()->First();
236
                $wasPublished = true;
237
            } else if ($allVirtual->Count() > 0) {
238
                // choose the first one
239
                $firstVirtual = $this->getVirtualLinkedElements()->First();
240
                $wasPublished = false;
241
            }
242
            if ($firstVirtual) {
243
                $origParentID = $this->ParentID;
0 ignored issues
show
Unused Code introduced by
$origParentID is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
244
                $origSort = $this->Sort;
0 ignored issues
show
Unused Code introduced by
$origSort is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
245
246
                $clone = $this->duplicate(false);
247
248
                // set clones values to first virtual's values
249
                $clone->ParentID = $firstVirtual->ParentID;
250
                $clone->Sort = $firstVirtual->Sort;
251
252
                $clone->write();
253
                if ($wasPublished) {
0 ignored issues
show
Bug introduced by
The variable $wasPublished does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
254
                    $clone->doPublish();
255
                    $firstVirtual->doUnpublish();
256
                }
257
258
                // clone has a new ID, so need to repoint
259
                // all the other virtual elements
260
                foreach($allVirtual as $virtual) {
261
                    if ($virtual->ID == $firstVirtual->ID) {
262
                        continue;
263
                    }
264
                    $pub = false;
265
                    if ($virtual->isPublished()) {
266
                        $pub = true;
267
                    }
268
                    $virtual->LinkedElementID = $clone->ID;
269
                    $virtual->write();
270
                    if ($pub) {
271
                        $virtual->doPublish();
272
                    }
273
                }
274
275
                $firstVirtual->delete();
276
            }
277
        }
278
    }
279
280
    /**
281
     * @return string
282
     */
283
    public function i18n_singular_name()
284
    {
285
        return _t(__CLASS__, $this->config()->title);
286
    }
287
288
    /**
289
     * @return string
290
     */
291
    public function getElementType()
292
    {
293
        return $this->i18n_singular_name();
294
    }
295
296
    /**
297
     * @return string
298
     */
299 View Code Duplication
    public function getTitle()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
300
    {
301
        if ($title = $this->getField('Title')) {
302
            return $title;
303
        } else {
304
            if (!$this->isInDb()) {
305
                return;
306
            }
307
308
            return $this->config()->title;
309
        }
310
    }
311
312
    /**
313
     * Get a unique anchor name
314
     *
315
     * @return string
316
     */
317
    public function getAnchor() {
318
        if ($this->_anchor !== null) {
319
            return $this->_anchor;
320
        }
321
322
        $anchorTitle = '';
323
        if (!$this->config()->disable_pretty_anchor_name) {
324
            if ($this->hasMethod('getAnchorTitle')) {
325
                $anchorTitle = $this->getAnchorTitle();
326
            } else if ($this->config()->enable_title_in_template) {
327
                $anchorTitle = $this->getField('Title');
328
            }
329
        }
330
        if (!$anchorTitle) {
331
            $anchorTitle = 'e'.$this->ID;
332
        }
333
334
        $filter = URLSegmentFilter::create();
335
        $titleAsURL = $filter->filter($anchorTitle);
336
337
        // Ensure that this anchor name isn't already in use
338
        // ie. If two elemental blocks have the same title, it'll append '-2', '-3'
339
        $result = $titleAsURL;
340
        $count = 1;
341
        while (isset(self::$_used_anchors[$result]) && self::$_used_anchors[$result] !== $this->ID) {
342
            ++$count;
343
            $result = $titleAsURL.'-'.$count;
344
        }
345
        self::$_used_anchors[$result] = $this->ID;
346
        return $this->_anchor = $result;
347
    }
348
349
    /**
350
     * @return string
351
     */
352 View Code Duplication
    public function getCMSTitle()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
353
    {
354
        if ($title = $this->getField('Title')) {
355
            return $this->config()->title . ': ' . $title;
356
        } else {
357
            if (!$this->isInDb()) {
358
                return;
359
            }
360
            return $this->config()->title;
361
        }
362
    }
363
364
    public function ControllerTop()
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...
365
    {
366
        return Controller::curr();
367
    }
368
369
    public function getPage()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

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

Loading history...
370
    {
371
        if ($this->virtualOwner) {
372
            return $this->virtualOwner->getPage();
373
        }
374
375
        if ($this->ListID) {
376
            return $this->List()->getPage();
377
        }
378
379
        $area = $this->Parent();
380
381
        if ($area instanceof ElementalArea) {
382
            return $area->getOwnerPage();
383
        }
384
385
        return null;
386
    }
387
388
    /**
389
     * Override the {@link Widget::forTemplate()} method so that holders are not rendered twice. The controller should
390
     * render with widget inside the
391
     *
392
     * @return HTML
393
     */
394
    public function forTemplate($holder = true)
395
    {
396
        $config = SiteConfig::current_site_config();
397
398
        if ($config->Theme) Config::inst()->update('SSViewer', 'theme', $config->Theme);
399
400
        return $this->renderWith($this->class);
401
    }
402
403
    /**
404
     * @return string
405
     */
406
    public function getEditLink() {
407
        return Controller::join_links(
408
            Director::absoluteBaseURL(),
409
            'admin/elemental/BaseElement/EditForm/field/BaseElement/item',
410
            $this->ID,
411
            'edit'
412
        );
413
    }
414
415
    public function onBeforeVersionedPublish()
416
    {
417
418
    }
419
420
		public static function all_allowed_elements() {
421
        $classes = array();
422
423
        // get all dataobject with the elemental extension
424
        foreach(ClassInfo::subclassesFor('DataObject') as $className) {
425
            if(Object::has_extension($className, 'ElementPageExtension')) {
426
               $classes[] = $className;
427
            }
428
        }
429
430
        // get all allowd_elements for these classes
431
        $allowed = array();
432
        foreach($classes as $className) {
433
            $allowed_elements = Config::inst()->get($className, 'allowed_elements');
434
            if ($allowed_elements) {
435
                $allowed = array_merge($allowed, $allowed_elements);
436
            }
437
        }
438
439
       // $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...
440
        $allowed = array_unique($allowed);
441
442
        $elements = array();
443
        foreach($allowed as $className) {
444
            $elements[$className] = _t($className, Config::inst()->get($className, 'title'));
445
        }
446
447
        asort($elements);
448
449
        return $elements;
450
    }
451
452
    public function getDefaultSearchContext()
453
    {
454
        $fields = $this->scaffoldSearchFields();
455
456
        $elements = BaseElement::all_allowed_elements();
457
458
        $fields->push(DropdownField::create('ClassName', 'Element Type', $elements)
459
            ->setEmptyString('All types'));
460
        $filters = $this->owner->defaultSearchFilters();
461
462
        return new SearchContext(
463
            $this->owner->class,
464
            $fields,
465
            $filters
466
        );
467
    }
468
469
    public function setVirtualOwner(ElementVirtualLinked $virtualOwner) {
470
        $this->virtualOwner = $virtualOwner;
471
    }
472
473
    /**
474
     * Finds and returns elements
475
     * that are virtual elements which link to this element
476
     */
477
    public function getVirtualLinkedElements() {
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...
478
        return ElementVirtualLinked::get()->filter('LinkedElementID', $this->ID);
479
    }
480
481
    /**
482
     * Finds and returns published elements
483
     * that are virtual elements which link to this element
484
     */
485
    public function getPublishedVirtualLinkedElements() {
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...
486
        $current = Versioned::get_reading_mode();
487
        Versioned::set_reading_mode('Stage.Live');
488
        $v = $this->getVirtualLinkedElements();
489
        Versioned::set_reading_mode($current);
490
        return $v;
491
    }
492
}
493